babylon.max.js 2.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673
  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 Color3 = (function () {
  23. /**
  24. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  25. */
  26. function Color3(r, g, b) {
  27. if (r === void 0) { r = 0; }
  28. if (g === void 0) { g = 0; }
  29. if (b === void 0) { b = 0; }
  30. this.r = r;
  31. this.g = g;
  32. this.b = b;
  33. }
  34. /**
  35. * Returns a string with the Color3 current values.
  36. */
  37. Color3.prototype.toString = function () {
  38. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  39. };
  40. /**
  41. * Returns the string "Color3".
  42. */
  43. Color3.prototype.getClassName = function () {
  44. return "Color3";
  45. };
  46. /**
  47. * Returns the Color3 hash code.
  48. */
  49. Color3.prototype.getHashCode = function () {
  50. var hash = this.r || 0;
  51. hash = (hash * 397) ^ (this.g || 0);
  52. hash = (hash * 397) ^ (this.b || 0);
  53. return hash;
  54. };
  55. // Operators
  56. /**
  57. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  58. * Returns the Color3.
  59. */
  60. Color3.prototype.toArray = function (array, index) {
  61. if (index === undefined) {
  62. index = 0;
  63. }
  64. array[index] = this.r;
  65. array[index + 1] = this.g;
  66. array[index + 2] = this.b;
  67. return this;
  68. };
  69. /**
  70. * Returns a new Color4 object from the current Color3 and the passed alpha.
  71. */
  72. Color3.prototype.toColor4 = function (alpha) {
  73. if (alpha === void 0) { alpha = 1; }
  74. return new Color4(this.r, this.g, this.b, alpha);
  75. };
  76. /**
  77. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  78. */
  79. Color3.prototype.asArray = function () {
  80. var result = [];
  81. this.toArray(result, 0);
  82. return result;
  83. };
  84. /**
  85. * Returns the luminance value (float).
  86. */
  87. Color3.prototype.toLuminance = function () {
  88. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  89. };
  90. /**
  91. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  92. * Returns this new object.
  93. */
  94. Color3.prototype.multiply = function (otherColor) {
  95. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  96. };
  97. /**
  98. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  99. * Returns the current Color3.
  100. */
  101. Color3.prototype.multiplyToRef = function (otherColor, result) {
  102. result.r = this.r * otherColor.r;
  103. result.g = this.g * otherColor.g;
  104. result.b = this.b * otherColor.b;
  105. return this;
  106. };
  107. /**
  108. * Boolean : True if the rgb values are equal to the passed ones.
  109. */
  110. Color3.prototype.equals = function (otherColor) {
  111. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  112. };
  113. /**
  114. * Boolean : True if the rgb values are equal to the passed ones.
  115. */
  116. Color3.prototype.equalsFloats = function (r, g, b) {
  117. return this.r === r && this.g === g && this.b === b;
  118. };
  119. /**
  120. * Multiplies in place each rgb value by scale.
  121. * Returns the updated Color3.
  122. */
  123. Color3.prototype.scale = function (scale) {
  124. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  125. };
  126. /**
  127. * Multiplies the rgb values by scale and stores the result into "result".
  128. * Returns the unmodified current Color3.
  129. */
  130. Color3.prototype.scaleToRef = function (scale, result) {
  131. result.r = this.r * scale;
  132. result.g = this.g * scale;
  133. result.b = this.b * scale;
  134. return this;
  135. };
  136. /**
  137. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  138. */
  139. Color3.prototype.add = function (otherColor) {
  140. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  141. };
  142. /**
  143. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  144. * Returns the unmodified current Color3.
  145. */
  146. Color3.prototype.addToRef = function (otherColor, result) {
  147. result.r = this.r + otherColor.r;
  148. result.g = this.g + otherColor.g;
  149. result.b = this.b + otherColor.b;
  150. return this;
  151. };
  152. /**
  153. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  154. */
  155. Color3.prototype.subtract = function (otherColor) {
  156. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  157. };
  158. /**
  159. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  160. * Returns the unmodified current Color3.
  161. */
  162. Color3.prototype.subtractToRef = function (otherColor, result) {
  163. result.r = this.r - otherColor.r;
  164. result.g = this.g - otherColor.g;
  165. result.b = this.b - otherColor.b;
  166. return this;
  167. };
  168. /**
  169. * Returns a new Color3 copied the current one.
  170. */
  171. Color3.prototype.clone = function () {
  172. return new Color3(this.r, this.g, this.b);
  173. };
  174. /**
  175. * Copies the rgb values from the source in the current Color3.
  176. * Returns the updated Color3.
  177. */
  178. Color3.prototype.copyFrom = function (source) {
  179. this.r = source.r;
  180. this.g = source.g;
  181. this.b = source.b;
  182. return this;
  183. };
  184. /**
  185. * Updates the Color3 rgb values from the passed floats.
  186. * Returns the Color3.
  187. */
  188. Color3.prototype.copyFromFloats = function (r, g, b) {
  189. this.r = r;
  190. this.g = g;
  191. this.b = b;
  192. return this;
  193. };
  194. /**
  195. * Updates the Color3 rgb values from the passed floats.
  196. * Returns the Color3.
  197. */
  198. Color3.prototype.set = function (r, g, b) {
  199. return this.copyFromFloats(r, g, b);
  200. };
  201. /**
  202. * Returns the Color3 hexadecimal code as a string.
  203. */
  204. Color3.prototype.toHexString = function () {
  205. var intR = (this.r * 255) | 0;
  206. var intG = (this.g * 255) | 0;
  207. var intB = (this.b * 255) | 0;
  208. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  209. };
  210. /**
  211. * Returns a new Color3 converted to linear space.
  212. */
  213. Color3.prototype.toLinearSpace = function () {
  214. var convertedColor = new Color3();
  215. this.toLinearSpaceToRef(convertedColor);
  216. return convertedColor;
  217. };
  218. /**
  219. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  220. * Returns the unmodified Color3.
  221. */
  222. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  223. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  224. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  225. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  226. return this;
  227. };
  228. /**
  229. * Returns a new Color3 converted to gamma space.
  230. */
  231. Color3.prototype.toGammaSpace = function () {
  232. var convertedColor = new Color3();
  233. this.toGammaSpaceToRef(convertedColor);
  234. return convertedColor;
  235. };
  236. /**
  237. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  238. * Returns the unmodified Color3.
  239. */
  240. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  241. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  242. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  243. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  244. return this;
  245. };
  246. // Statics
  247. /**
  248. * Creates a new Color3 from the string containing valid hexadecimal values.
  249. */
  250. Color3.FromHexString = function (hex) {
  251. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  252. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  253. return new Color3(0, 0, 0);
  254. }
  255. var r = parseInt(hex.substring(1, 3), 16);
  256. var g = parseInt(hex.substring(3, 5), 16);
  257. var b = parseInt(hex.substring(5, 7), 16);
  258. return Color3.FromInts(r, g, b);
  259. };
  260. /**
  261. * Creates a new Vector3 from the startind index of the passed array.
  262. */
  263. Color3.FromArray = function (array, offset) {
  264. if (offset === void 0) { offset = 0; }
  265. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  266. };
  267. /**
  268. * Creates a new Color3 from integer values ( < 256).
  269. */
  270. Color3.FromInts = function (r, g, b) {
  271. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  272. };
  273. /**
  274. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  275. */
  276. Color3.Lerp = function (start, end, amount) {
  277. var r = start.r + ((end.r - start.r) * amount);
  278. var g = start.g + ((end.g - start.g) * amount);
  279. var b = start.b + ((end.b - start.b) * amount);
  280. return new Color3(r, g, b);
  281. };
  282. Color3.Red = function () { return new Color3(1, 0, 0); };
  283. Color3.Green = function () { return new Color3(0, 1, 0); };
  284. Color3.Blue = function () { return new Color3(0, 0, 1); };
  285. Color3.Black = function () { return new Color3(0, 0, 0); };
  286. Color3.White = function () { return new Color3(1, 1, 1); };
  287. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  288. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  289. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  290. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  291. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  292. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  293. return Color3;
  294. }());
  295. BABYLON.Color3 = Color3;
  296. var Color4 = (function () {
  297. /**
  298. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  299. */
  300. function Color4(r, g, b, a) {
  301. if (r === void 0) { r = 0; }
  302. if (g === void 0) { g = 0; }
  303. if (b === void 0) { b = 0; }
  304. if (a === void 0) { a = 1; }
  305. this.r = r;
  306. this.g = g;
  307. this.b = b;
  308. this.a = a;
  309. }
  310. // Operators
  311. /**
  312. * Adds in place the passed Color4 values to the current Color4.
  313. * Returns the updated Color4.
  314. */
  315. Color4.prototype.addInPlace = function (right) {
  316. this.r += right.r;
  317. this.g += right.g;
  318. this.b += right.b;
  319. this.a += right.a;
  320. return this;
  321. };
  322. /**
  323. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  324. */
  325. Color4.prototype.asArray = function () {
  326. var result = [];
  327. this.toArray(result, 0);
  328. return result;
  329. };
  330. /**
  331. * Stores from the starting index in the passed array the Color4 successive values.
  332. * Returns the Color4.
  333. */
  334. Color4.prototype.toArray = function (array, index) {
  335. if (index === undefined) {
  336. index = 0;
  337. }
  338. array[index] = this.r;
  339. array[index + 1] = this.g;
  340. array[index + 2] = this.b;
  341. array[index + 3] = this.a;
  342. return this;
  343. };
  344. /**
  345. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  346. */
  347. Color4.prototype.add = function (right) {
  348. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  349. };
  350. /**
  351. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  352. */
  353. Color4.prototype.subtract = function (right) {
  354. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  355. };
  356. /**
  357. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  358. * Returns the Color4.
  359. */
  360. Color4.prototype.subtractToRef = function (right, result) {
  361. result.r = this.r - right.r;
  362. result.g = this.g - right.g;
  363. result.b = this.b - right.b;
  364. result.a = this.a - right.a;
  365. return this;
  366. };
  367. /**
  368. * Creates a new Color4 with the current Color4 values multiplied by scale.
  369. */
  370. Color4.prototype.scale = function (scale) {
  371. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  372. };
  373. /**
  374. * Multiplies the current Color4 values by scale and stores the result in "result".
  375. * Returns the Color4.
  376. */
  377. Color4.prototype.scaleToRef = function (scale, result) {
  378. result.r = this.r * scale;
  379. result.g = this.g * scale;
  380. result.b = this.b * scale;
  381. result.a = this.a * scale;
  382. return this;
  383. };
  384. /**
  385. * Multipy an RGBA Color4 value by another and return a new Color4 object
  386. * @param color The Color4 (RGBA) value to multiply by
  387. * @returns A new Color4.
  388. */
  389. Color4.prototype.multiply = function (color) {
  390. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  391. };
  392. /**
  393. * Multipy an RGBA Color4 value by another and push the result in a reference value
  394. * @param color The Color4 (RGBA) value to multiply by
  395. * @param result The Color4 (RGBA) to fill the result in
  396. * @returns the result Color4.
  397. */
  398. Color4.prototype.multiplyToRef = function (color, result) {
  399. result.r = this.r * color.r;
  400. result.g = this.g * color.g;
  401. result.b = this.b * color.b;
  402. result.a = this.a * color.a;
  403. return result;
  404. };
  405. /**
  406. * Returns a string with the Color4 values.
  407. */
  408. Color4.prototype.toString = function () {
  409. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  410. };
  411. /**
  412. * Returns the string "Color4"
  413. */
  414. Color4.prototype.getClassName = function () {
  415. return "Color4";
  416. };
  417. /**
  418. * Return the Color4 hash code as a number.
  419. */
  420. Color4.prototype.getHashCode = function () {
  421. var hash = this.r || 0;
  422. hash = (hash * 397) ^ (this.g || 0);
  423. hash = (hash * 397) ^ (this.b || 0);
  424. hash = (hash * 397) ^ (this.a || 0);
  425. return hash;
  426. };
  427. /**
  428. * Creates a new Color4 copied from the current one.
  429. */
  430. Color4.prototype.clone = function () {
  431. return new Color4(this.r, this.g, this.b, this.a);
  432. };
  433. /**
  434. * Copies the passed Color4 values into the current one.
  435. * Returns the updated Color4.
  436. */
  437. Color4.prototype.copyFrom = function (source) {
  438. this.r = source.r;
  439. this.g = source.g;
  440. this.b = source.b;
  441. this.a = source.a;
  442. return this;
  443. };
  444. /**
  445. * Copies the passed float values into the current one.
  446. * Returns the updated Color4.
  447. */
  448. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  449. this.r = r;
  450. this.g = g;
  451. this.b = b;
  452. this.a = a;
  453. return this;
  454. };
  455. /**
  456. * Copies the passed float values into the current one.
  457. * Returns the updated Color4.
  458. */
  459. Color4.prototype.set = function (r, g, b, a) {
  460. return this.copyFromFloats(r, g, b, a);
  461. };
  462. /**
  463. * Returns a string containing the hexadecimal Color4 code.
  464. */
  465. Color4.prototype.toHexString = function () {
  466. var intR = (this.r * 255) | 0;
  467. var intG = (this.g * 255) | 0;
  468. var intB = (this.b * 255) | 0;
  469. var intA = (this.a * 255) | 0;
  470. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  471. };
  472. /**
  473. * Returns a new Color4 converted to linear space.
  474. */
  475. Color4.prototype.toLinearSpace = function () {
  476. var convertedColor = new Color4();
  477. this.toLinearSpaceToRef(convertedColor);
  478. return convertedColor;
  479. };
  480. /**
  481. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  482. * Returns the unmodified Color4.
  483. */
  484. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  485. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  486. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  487. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  488. convertedColor.a = this.a;
  489. return this;
  490. };
  491. /**
  492. * Returns a new Color4 converted to gamma space.
  493. */
  494. Color4.prototype.toGammaSpace = function () {
  495. var convertedColor = new Color4();
  496. this.toGammaSpaceToRef(convertedColor);
  497. return convertedColor;
  498. };
  499. /**
  500. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  501. * Returns the unmodified Color4.
  502. */
  503. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  504. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  505. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  506. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  507. convertedColor.a = this.a;
  508. return this;
  509. };
  510. // Statics
  511. /**
  512. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  513. */
  514. Color4.FromHexString = function (hex) {
  515. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  516. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  517. return new Color4(0.0, 0.0, 0.0, 0.0);
  518. }
  519. var r = parseInt(hex.substring(1, 3), 16);
  520. var g = parseInt(hex.substring(3, 5), 16);
  521. var b = parseInt(hex.substring(5, 7), 16);
  522. var a = parseInt(hex.substring(7, 9), 16);
  523. return Color4.FromInts(r, g, b, a);
  524. };
  525. /**
  526. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  527. */
  528. Color4.Lerp = function (left, right, amount) {
  529. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  530. Color4.LerpToRef(left, right, amount, result);
  531. return result;
  532. };
  533. /**
  534. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  535. */
  536. Color4.LerpToRef = function (left, right, amount, result) {
  537. result.r = left.r + (right.r - left.r) * amount;
  538. result.g = left.g + (right.g - left.g) * amount;
  539. result.b = left.b + (right.b - left.b) * amount;
  540. result.a = left.a + (right.a - left.a) * amount;
  541. };
  542. /**
  543. * Creates a new Color4 from the starting index element of the passed array.
  544. */
  545. Color4.FromArray = function (array, offset) {
  546. if (offset === void 0) { offset = 0; }
  547. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  548. };
  549. /**
  550. * Creates a new Color4 from the passed integers ( < 256 ).
  551. */
  552. Color4.FromInts = function (r, g, b, a) {
  553. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  554. };
  555. Color4.CheckColors4 = function (colors, count) {
  556. // Check if color3 was used
  557. if (colors.length === count * 3) {
  558. var colors4 = [];
  559. for (var index = 0; index < colors.length; index += 3) {
  560. var newIndex = (index / 3) * 4;
  561. colors4[newIndex] = colors[index];
  562. colors4[newIndex + 1] = colors[index + 1];
  563. colors4[newIndex + 2] = colors[index + 2];
  564. colors4[newIndex + 3] = 1.0;
  565. }
  566. return colors4;
  567. }
  568. return colors;
  569. };
  570. return Color4;
  571. }());
  572. BABYLON.Color4 = Color4;
  573. var Vector2 = (function () {
  574. /**
  575. * Creates a new Vector2 from the passed x and y coordinates.
  576. */
  577. function Vector2(x, y) {
  578. this.x = x;
  579. this.y = y;
  580. }
  581. /**
  582. * Returns a string with the Vector2 coordinates.
  583. */
  584. Vector2.prototype.toString = function () {
  585. return "{X: " + this.x + " Y:" + this.y + "}";
  586. };
  587. /**
  588. * Returns the string "Vector2"
  589. */
  590. Vector2.prototype.getClassName = function () {
  591. return "Vector2";
  592. };
  593. /**
  594. * Returns the Vector2 hash code as a number.
  595. */
  596. Vector2.prototype.getHashCode = function () {
  597. var hash = this.x || 0;
  598. hash = (hash * 397) ^ (this.y || 0);
  599. return hash;
  600. };
  601. // Operators
  602. /**
  603. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  604. * Returns the Vector2.
  605. */
  606. Vector2.prototype.toArray = function (array, index) {
  607. if (index === void 0) { index = 0; }
  608. array[index] = this.x;
  609. array[index + 1] = this.y;
  610. return this;
  611. };
  612. /**
  613. * Returns a new array with 2 elements : the Vector2 coordinates.
  614. */
  615. Vector2.prototype.asArray = function () {
  616. var result = [];
  617. this.toArray(result, 0);
  618. return result;
  619. };
  620. /**
  621. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  622. * Returns the updated Vector2.
  623. */
  624. Vector2.prototype.copyFrom = function (source) {
  625. this.x = source.x;
  626. this.y = source.y;
  627. return this;
  628. };
  629. /**
  630. * Sets the Vector2 coordinates with the passed floats.
  631. * Returns the updated Vector2.
  632. */
  633. Vector2.prototype.copyFromFloats = function (x, y) {
  634. this.x = x;
  635. this.y = y;
  636. return this;
  637. };
  638. /**
  639. * Sets the Vector2 coordinates with the passed floats.
  640. * Returns the updated Vector2.
  641. */
  642. Vector2.prototype.set = function (x, y) {
  643. return this.copyFromFloats(x, y);
  644. };
  645. /**
  646. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  647. */
  648. Vector2.prototype.add = function (otherVector) {
  649. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  650. };
  651. /**
  652. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  653. * Returns the Vector2.
  654. */
  655. Vector2.prototype.addToRef = function (otherVector, result) {
  656. result.x = this.x + otherVector.x;
  657. result.y = this.y + otherVector.y;
  658. return this;
  659. };
  660. /**
  661. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  662. * Returns the updated Vector2.
  663. */
  664. Vector2.prototype.addInPlace = function (otherVector) {
  665. this.x += otherVector.x;
  666. this.y += otherVector.y;
  667. return this;
  668. };
  669. /**
  670. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  671. */
  672. Vector2.prototype.addVector3 = function (otherVector) {
  673. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  674. };
  675. /**
  676. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  677. */
  678. Vector2.prototype.subtract = function (otherVector) {
  679. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  680. };
  681. /**
  682. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  683. * Returns the Vector2.
  684. */
  685. Vector2.prototype.subtractToRef = function (otherVector, result) {
  686. result.x = this.x - otherVector.x;
  687. result.y = this.y - otherVector.y;
  688. return this;
  689. };
  690. /**
  691. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  692. * Returns the updated Vector2.
  693. */
  694. Vector2.prototype.subtractInPlace = function (otherVector) {
  695. this.x -= otherVector.x;
  696. this.y -= otherVector.y;
  697. return this;
  698. };
  699. /**
  700. * Multiplies in place the current Vector2 coordinates by the passed ones.
  701. * Returns the updated Vector2.
  702. */
  703. Vector2.prototype.multiplyInPlace = function (otherVector) {
  704. this.x *= otherVector.x;
  705. this.y *= otherVector.y;
  706. return this;
  707. };
  708. /**
  709. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  710. */
  711. Vector2.prototype.multiply = function (otherVector) {
  712. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  713. };
  714. /**
  715. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  716. * Returns the Vector2.
  717. */
  718. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  719. result.x = this.x * otherVector.x;
  720. result.y = this.y * otherVector.y;
  721. return this;
  722. };
  723. /**
  724. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  725. */
  726. Vector2.prototype.multiplyByFloats = function (x, y) {
  727. return new Vector2(this.x * x, this.y * y);
  728. };
  729. /**
  730. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  731. */
  732. Vector2.prototype.divide = function (otherVector) {
  733. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  734. };
  735. /**
  736. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  737. * Returns the Vector2.
  738. */
  739. Vector2.prototype.divideToRef = function (otherVector, result) {
  740. result.x = this.x / otherVector.x;
  741. result.y = this.y / otherVector.y;
  742. return this;
  743. };
  744. /**
  745. * Returns a new Vector2 with current Vector2 negated coordinates.
  746. */
  747. Vector2.prototype.negate = function () {
  748. return new Vector2(-this.x, -this.y);
  749. };
  750. /**
  751. * Multiply the Vector2 coordinates by scale.
  752. * Returns the updated Vector2.
  753. */
  754. Vector2.prototype.scaleInPlace = function (scale) {
  755. this.x *= scale;
  756. this.y *= scale;
  757. return this;
  758. };
  759. /**
  760. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  761. */
  762. Vector2.prototype.scale = function (scale) {
  763. return new Vector2(this.x * scale, this.y * scale);
  764. };
  765. /**
  766. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  767. */
  768. Vector2.prototype.equals = function (otherVector) {
  769. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  770. };
  771. /**
  772. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  773. */
  774. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  775. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  776. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  777. };
  778. // Properties
  779. /**
  780. * Returns the vector length (float).
  781. */
  782. Vector2.prototype.length = function () {
  783. return Math.sqrt(this.x * this.x + this.y * this.y);
  784. };
  785. /**
  786. * Returns the vector squared length (float);
  787. */
  788. Vector2.prototype.lengthSquared = function () {
  789. return (this.x * this.x + this.y * this.y);
  790. };
  791. // Methods
  792. /**
  793. * Normalize the vector.
  794. * Returns the updated Vector2.
  795. */
  796. Vector2.prototype.normalize = function () {
  797. var len = this.length();
  798. if (len === 0)
  799. return this;
  800. var num = 1.0 / len;
  801. this.x *= num;
  802. this.y *= num;
  803. return this;
  804. };
  805. /**
  806. * Returns a new Vector2 copied from the Vector2.
  807. */
  808. Vector2.prototype.clone = function () {
  809. return new Vector2(this.x, this.y);
  810. };
  811. // Statics
  812. /**
  813. * Returns a new Vector2(0, 0)
  814. */
  815. Vector2.Zero = function () {
  816. return new Vector2(0, 0);
  817. };
  818. /**
  819. * Returns a new Vector2(1, 1)
  820. */
  821. Vector2.One = function () {
  822. return new Vector2(1, 1);
  823. };
  824. /**
  825. * Returns a new Vector2 set from the passed index element of the passed array.
  826. */
  827. Vector2.FromArray = function (array, offset) {
  828. if (offset === void 0) { offset = 0; }
  829. return new Vector2(array[offset], array[offset + 1]);
  830. };
  831. /**
  832. * Sets "result" from the passed index element of the passed array.
  833. */
  834. Vector2.FromArrayToRef = function (array, offset, result) {
  835. result.x = array[offset];
  836. result.y = array[offset + 1];
  837. };
  838. /**
  839. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  840. */
  841. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  842. var squared = amount * amount;
  843. var cubed = amount * squared;
  844. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  845. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  846. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  847. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  848. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  849. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  850. return new Vector2(x, y);
  851. };
  852. /**
  853. * 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".
  854. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  855. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  856. */
  857. Vector2.Clamp = function (value, min, max) {
  858. var x = value.x;
  859. x = (x > max.x) ? max.x : x;
  860. x = (x < min.x) ? min.x : x;
  861. var y = value.y;
  862. y = (y > max.y) ? max.y : y;
  863. y = (y < min.y) ? min.y : y;
  864. return new Vector2(x, y);
  865. };
  866. /**
  867. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  868. */
  869. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  870. var squared = amount * amount;
  871. var cubed = amount * squared;
  872. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  873. var part2 = (-2.0 * cubed) + (3.0 * squared);
  874. var part3 = (cubed - (2.0 * squared)) + amount;
  875. var part4 = cubed - squared;
  876. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  877. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  878. return new Vector2(x, y);
  879. };
  880. /**
  881. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  882. */
  883. Vector2.Lerp = function (start, end, amount) {
  884. var x = start.x + ((end.x - start.x) * amount);
  885. var y = start.y + ((end.y - start.y) * amount);
  886. return new Vector2(x, y);
  887. };
  888. /**
  889. * Returns the dot product (float) of the vector "left" and the vector "right".
  890. */
  891. Vector2.Dot = function (left, right) {
  892. return left.x * right.x + left.y * right.y;
  893. };
  894. /**
  895. * Returns a new Vector2 equal to the normalized passed vector.
  896. */
  897. Vector2.Normalize = function (vector) {
  898. var newVector = vector.clone();
  899. newVector.normalize();
  900. return newVector;
  901. };
  902. /**
  903. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  904. */
  905. Vector2.Minimize = function (left, right) {
  906. var x = (left.x < right.x) ? left.x : right.x;
  907. var y = (left.y < right.y) ? left.y : right.y;
  908. return new Vector2(x, y);
  909. };
  910. /**
  911. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  912. */
  913. Vector2.Maximize = function (left, right) {
  914. var x = (left.x > right.x) ? left.x : right.x;
  915. var y = (left.y > right.y) ? left.y : right.y;
  916. return new Vector2(x, y);
  917. };
  918. /**
  919. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  920. */
  921. Vector2.Transform = function (vector, transformation) {
  922. var r = Vector2.Zero();
  923. Vector2.TransformToRef(vector, transformation, r);
  924. return r;
  925. };
  926. /**
  927. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  928. */
  929. Vector2.TransformToRef = function (vector, transformation, result) {
  930. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  931. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  932. result.x = x;
  933. result.y = y;
  934. };
  935. /**
  936. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  937. */
  938. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  939. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  940. var sign = a < 0 ? -1 : 1;
  941. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  942. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  943. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  944. };
  945. /**
  946. * Returns the distance (float) between the vectors "value1" and "value2".
  947. */
  948. Vector2.Distance = function (value1, value2) {
  949. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  950. };
  951. /**
  952. * Returns the squared distance (float) between the vectors "value1" and "value2".
  953. */
  954. Vector2.DistanceSquared = function (value1, value2) {
  955. var x = value1.x - value2.x;
  956. var y = value1.y - value2.y;
  957. return (x * x) + (y * y);
  958. };
  959. /**
  960. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  961. */
  962. Vector2.Center = function (value1, value2) {
  963. var center = value1.add(value2);
  964. center.scaleInPlace(0.5);
  965. return center;
  966. };
  967. /**
  968. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  969. */
  970. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  971. var l2 = Vector2.DistanceSquared(segA, segB);
  972. if (l2 === 0.0) {
  973. return Vector2.Distance(p, segA);
  974. }
  975. var v = segB.subtract(segA);
  976. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  977. var proj = segA.add(v.multiplyByFloats(t, t));
  978. return Vector2.Distance(p, proj);
  979. };
  980. return Vector2;
  981. }());
  982. BABYLON.Vector2 = Vector2;
  983. var Vector3 = (function () {
  984. /**
  985. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  986. * A Vector3 is the main object used in 3D geometry.
  987. * It can represent etiher the coordinates of a point the space, either a direction.
  988. */
  989. function Vector3(x, y, z) {
  990. this.x = x;
  991. this.y = y;
  992. this.z = z;
  993. }
  994. /**
  995. * Returns a string with the Vector3 coordinates.
  996. */
  997. Vector3.prototype.toString = function () {
  998. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  999. };
  1000. /**
  1001. * Returns the string "Vector3"
  1002. */
  1003. Vector3.prototype.getClassName = function () {
  1004. return "Vector3";
  1005. };
  1006. /**
  1007. * Returns the Vector hash code.
  1008. */
  1009. Vector3.prototype.getHashCode = function () {
  1010. var hash = this.x || 0;
  1011. hash = (hash * 397) ^ (this.y || 0);
  1012. hash = (hash * 397) ^ (this.z || 0);
  1013. return hash;
  1014. };
  1015. // Operators
  1016. /**
  1017. * Returns a new array with three elements : the coordinates the Vector3.
  1018. */
  1019. Vector3.prototype.asArray = function () {
  1020. var result = [];
  1021. this.toArray(result, 0);
  1022. return result;
  1023. };
  1024. /**
  1025. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1026. * Returns the Vector3.
  1027. */
  1028. Vector3.prototype.toArray = function (array, index) {
  1029. if (index === void 0) { index = 0; }
  1030. array[index] = this.x;
  1031. array[index + 1] = this.y;
  1032. array[index + 2] = this.z;
  1033. return this;
  1034. };
  1035. /**
  1036. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1037. */
  1038. Vector3.prototype.toQuaternion = function () {
  1039. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1040. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1041. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1042. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1043. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1044. var cosy = Math.cos(this.y * 0.5);
  1045. var siny = Math.sin(this.y * 0.5);
  1046. result.x = coszMinusx * siny;
  1047. result.y = -sinzMinusx * siny;
  1048. result.z = sinxPlusz * cosy;
  1049. result.w = cosxPlusz * cosy;
  1050. return result;
  1051. };
  1052. /**
  1053. * Adds the passed vector to the current Vector3.
  1054. * Returns the updated Vector3.
  1055. */
  1056. Vector3.prototype.addInPlace = function (otherVector) {
  1057. this.x += otherVector.x;
  1058. this.y += otherVector.y;
  1059. this.z += otherVector.z;
  1060. return this;
  1061. };
  1062. /**
  1063. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1064. */
  1065. Vector3.prototype.add = function (otherVector) {
  1066. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1067. };
  1068. /**
  1069. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1070. * Returns the current Vector3.
  1071. */
  1072. Vector3.prototype.addToRef = function (otherVector, result) {
  1073. result.x = this.x + otherVector.x;
  1074. result.y = this.y + otherVector.y;
  1075. result.z = this.z + otherVector.z;
  1076. return this;
  1077. };
  1078. /**
  1079. * Subtract the passed vector from the current Vector3.
  1080. * Returns the updated Vector3.
  1081. */
  1082. Vector3.prototype.subtractInPlace = function (otherVector) {
  1083. this.x -= otherVector.x;
  1084. this.y -= otherVector.y;
  1085. this.z -= otherVector.z;
  1086. return this;
  1087. };
  1088. /**
  1089. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1090. */
  1091. Vector3.prototype.subtract = function (otherVector) {
  1092. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1093. };
  1094. /**
  1095. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1096. * Returns the current Vector3.
  1097. */
  1098. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1099. result.x = this.x - otherVector.x;
  1100. result.y = this.y - otherVector.y;
  1101. result.z = this.z - otherVector.z;
  1102. return this;
  1103. };
  1104. /**
  1105. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1106. */
  1107. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1108. return new Vector3(this.x - x, this.y - y, this.z - z);
  1109. };
  1110. /**
  1111. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1112. * Returns the current Vector3.
  1113. */
  1114. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1115. result.x = this.x - x;
  1116. result.y = this.y - y;
  1117. result.z = this.z - z;
  1118. return this;
  1119. };
  1120. /**
  1121. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1122. */
  1123. Vector3.prototype.negate = function () {
  1124. return new Vector3(-this.x, -this.y, -this.z);
  1125. };
  1126. /**
  1127. * Multiplies the Vector3 coordinates by the float "scale".
  1128. * Returns the updated Vector3.
  1129. */
  1130. Vector3.prototype.scaleInPlace = function (scale) {
  1131. this.x *= scale;
  1132. this.y *= scale;
  1133. this.z *= scale;
  1134. return this;
  1135. };
  1136. /**
  1137. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1138. */
  1139. Vector3.prototype.scale = function (scale) {
  1140. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1141. };
  1142. /**
  1143. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1144. * Returns the current Vector3.
  1145. */
  1146. Vector3.prototype.scaleToRef = function (scale, result) {
  1147. result.x = this.x * scale;
  1148. result.y = this.y * scale;
  1149. result.z = this.z * scale;
  1150. return this;
  1151. };
  1152. /**
  1153. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1154. */
  1155. Vector3.prototype.equals = function (otherVector) {
  1156. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1157. };
  1158. /**
  1159. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1160. */
  1161. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1162. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1163. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1164. };
  1165. /**
  1166. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1167. */
  1168. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1169. return this.x === x && this.y === y && this.z === z;
  1170. };
  1171. /**
  1172. * Muliplies the current Vector3 coordinates by the passed ones.
  1173. * Returns the updated Vector3.
  1174. */
  1175. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1176. this.x *= otherVector.x;
  1177. this.y *= otherVector.y;
  1178. this.z *= otherVector.z;
  1179. return this;
  1180. };
  1181. /**
  1182. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1183. */
  1184. Vector3.prototype.multiply = function (otherVector) {
  1185. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1186. };
  1187. /**
  1188. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1189. * Returns the current Vector3.
  1190. */
  1191. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1192. result.x = this.x * otherVector.x;
  1193. result.y = this.y * otherVector.y;
  1194. result.z = this.z * otherVector.z;
  1195. return this;
  1196. };
  1197. /**
  1198. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1199. */
  1200. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1201. return new Vector3(this.x * x, this.y * y, this.z * z);
  1202. };
  1203. /**
  1204. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1205. */
  1206. Vector3.prototype.divide = function (otherVector) {
  1207. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1208. };
  1209. /**
  1210. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1211. * Returns the current Vector3.
  1212. */
  1213. Vector3.prototype.divideToRef = function (otherVector, result) {
  1214. result.x = this.x / otherVector.x;
  1215. result.y = this.y / otherVector.y;
  1216. result.z = this.z / otherVector.z;
  1217. return this;
  1218. };
  1219. /**
  1220. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1221. * Returns the updated Vector3.
  1222. */
  1223. Vector3.prototype.MinimizeInPlace = function (other) {
  1224. if (other.x < this.x)
  1225. this.x = other.x;
  1226. if (other.y < this.y)
  1227. this.y = other.y;
  1228. if (other.z < this.z)
  1229. this.z = other.z;
  1230. return this;
  1231. };
  1232. /**
  1233. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1234. * Returns the updated Vector3.
  1235. */
  1236. Vector3.prototype.MaximizeInPlace = function (other) {
  1237. if (other.x > this.x)
  1238. this.x = other.x;
  1239. if (other.y > this.y)
  1240. this.y = other.y;
  1241. if (other.z > this.z)
  1242. this.z = other.z;
  1243. return this;
  1244. };
  1245. // Properties
  1246. /**
  1247. * Returns the length of the Vector3 (float).
  1248. */
  1249. Vector3.prototype.length = function () {
  1250. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1251. };
  1252. /**
  1253. * Returns the squared length of the Vector3 (float).
  1254. */
  1255. Vector3.prototype.lengthSquared = function () {
  1256. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1257. };
  1258. // Methods
  1259. /**
  1260. * Normalize the current Vector3.
  1261. * Returns the updated Vector3.
  1262. */
  1263. Vector3.prototype.normalize = function () {
  1264. var len = this.length();
  1265. if (len === 0 || len === 1.0)
  1266. return this;
  1267. var num = 1.0 / len;
  1268. this.x *= num;
  1269. this.y *= num;
  1270. this.z *= num;
  1271. return this;
  1272. };
  1273. /**
  1274. * Returns a new Vector3 copied from the current Vector3.
  1275. */
  1276. Vector3.prototype.clone = function () {
  1277. return new Vector3(this.x, this.y, this.z);
  1278. };
  1279. /**
  1280. * Copies the passed vector coordinates to the current Vector3 ones.
  1281. * Returns the updated Vector3.
  1282. */
  1283. Vector3.prototype.copyFrom = function (source) {
  1284. this.x = source.x;
  1285. this.y = source.y;
  1286. this.z = source.z;
  1287. return this;
  1288. };
  1289. /**
  1290. * Copies the passed floats to the current Vector3 coordinates.
  1291. * Returns the updated Vector3.
  1292. */
  1293. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1294. this.x = x;
  1295. this.y = y;
  1296. this.z = z;
  1297. return this;
  1298. };
  1299. /**
  1300. * Copies the passed floats to the current Vector3 coordinates.
  1301. * Returns the updated Vector3.
  1302. */
  1303. Vector3.prototype.set = function (x, y, z) {
  1304. return this.copyFromFloats(x, y, z);
  1305. };
  1306. // Statics
  1307. /**
  1308. *
  1309. */
  1310. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1311. var d0 = Vector3.Dot(vector0, axis) - size;
  1312. var d1 = Vector3.Dot(vector1, axis) - size;
  1313. var s = d0 / (d0 - d1);
  1314. return s;
  1315. };
  1316. /**
  1317. * Returns a new Vector3 set from the index "offset" of the passed array.
  1318. */
  1319. Vector3.FromArray = function (array, offset) {
  1320. if (!offset) {
  1321. offset = 0;
  1322. }
  1323. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1324. };
  1325. /**
  1326. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1327. * This function is deprecated. Use FromArray instead.
  1328. */
  1329. Vector3.FromFloatArray = function (array, offset) {
  1330. return Vector3.FromArray(array, offset);
  1331. };
  1332. /**
  1333. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1334. */
  1335. Vector3.FromArrayToRef = function (array, offset, result) {
  1336. result.x = array[offset];
  1337. result.y = array[offset + 1];
  1338. result.z = array[offset + 2];
  1339. };
  1340. /**
  1341. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1342. * This function is deprecated. Use FromArrayToRef instead.
  1343. */
  1344. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1345. return Vector3.FromArrayToRef(array, offset, result);
  1346. };
  1347. /**
  1348. * Sets the passed vector "result" with the passed floats.
  1349. */
  1350. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1351. result.x = x;
  1352. result.y = y;
  1353. result.z = z;
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1357. */
  1358. Vector3.Zero = function () {
  1359. return new Vector3(0.0, 0.0, 0.0);
  1360. };
  1361. /**
  1362. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1363. */
  1364. Vector3.One = function () {
  1365. return new Vector3(1.0, 1.0, 1.0);
  1366. };
  1367. /**
  1368. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1369. */
  1370. Vector3.Up = function () {
  1371. return new Vector3(0.0, 1.0, 0.0);
  1372. };
  1373. /**
  1374. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1375. */
  1376. Vector3.Forward = function () {
  1377. return new Vector3(0.0, 0.0, 1.0);
  1378. };
  1379. /**
  1380. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1381. */
  1382. Vector3.Right = function () {
  1383. return new Vector3(1.0, 0.0, 0.0);
  1384. };
  1385. /**
  1386. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1387. */
  1388. Vector3.Left = function () {
  1389. return new Vector3(-1.0, 0.0, 0.0);
  1390. };
  1391. /**
  1392. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1393. * This method computes tranformed coordinates only, not transformed direction vectors.
  1394. */
  1395. Vector3.TransformCoordinates = function (vector, transformation) {
  1396. var result = Vector3.Zero();
  1397. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1398. return result;
  1399. };
  1400. /**
  1401. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1402. * This method computes tranformed coordinates only, not transformed direction vectors.
  1403. */
  1404. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1408. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1409. result.x = x / w;
  1410. result.y = y / w;
  1411. result.z = z / w;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1418. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1419. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1420. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1421. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1422. result.x = rx / rw;
  1423. result.y = ry / rw;
  1424. result.z = rz / rw;
  1425. };
  1426. /**
  1427. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1428. * This methods computes transformed normalized direction vectors only.
  1429. */
  1430. Vector3.TransformNormal = function (vector, transformation) {
  1431. var result = Vector3.Zero();
  1432. Vector3.TransformNormalToRef(vector, transformation, result);
  1433. return result;
  1434. };
  1435. /**
  1436. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1437. * This methods computes transformed normalized direction vectors only.
  1438. */
  1439. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1440. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1441. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1442. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1443. result.x = x;
  1444. result.y = y;
  1445. result.z = z;
  1446. };
  1447. /**
  1448. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1449. * This methods computes transformed normalized direction vectors only.
  1450. */
  1451. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1452. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1453. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1454. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1455. };
  1456. /**
  1457. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1458. */
  1459. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1460. var squared = amount * amount;
  1461. var cubed = amount * squared;
  1462. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1463. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1464. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1465. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1466. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1467. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1468. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1469. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1470. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1471. return new Vector3(x, y, z);
  1472. };
  1473. /**
  1474. * 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".
  1475. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1476. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1477. */
  1478. Vector3.Clamp = function (value, min, max) {
  1479. var x = value.x;
  1480. x = (x > max.x) ? max.x : x;
  1481. x = (x < min.x) ? min.x : x;
  1482. var y = value.y;
  1483. y = (y > max.y) ? max.y : y;
  1484. y = (y < min.y) ? min.y : y;
  1485. var z = value.z;
  1486. z = (z > max.z) ? max.z : z;
  1487. z = (z < min.z) ? min.z : z;
  1488. return new Vector3(x, y, z);
  1489. };
  1490. /**
  1491. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1492. */
  1493. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1494. var squared = amount * amount;
  1495. var cubed = amount * squared;
  1496. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1497. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1498. var part3 = (cubed - (2.0 * squared)) + amount;
  1499. var part4 = cubed - squared;
  1500. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1501. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1502. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1503. return new Vector3(x, y, z);
  1504. };
  1505. /**
  1506. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1507. */
  1508. Vector3.Lerp = function (start, end, amount) {
  1509. var result = new Vector3(0, 0, 0);
  1510. Vector3.LerpToRef(start, end, amount, result);
  1511. return result;
  1512. };
  1513. /**
  1514. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1515. */
  1516. Vector3.LerpToRef = function (start, end, amount, result) {
  1517. result.x = start.x + ((end.x - start.x) * amount);
  1518. result.y = start.y + ((end.y - start.y) * amount);
  1519. result.z = start.z + ((end.z - start.z) * amount);
  1520. };
  1521. /**
  1522. * Returns the dot product (float) between the vectors "left" and "right".
  1523. */
  1524. Vector3.Dot = function (left, right) {
  1525. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1526. };
  1527. /**
  1528. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1529. * The cross product is then orthogonal to both "left" and "right".
  1530. */
  1531. Vector3.Cross = function (left, right) {
  1532. var result = Vector3.Zero();
  1533. Vector3.CrossToRef(left, right, result);
  1534. return result;
  1535. };
  1536. /**
  1537. * Sets the passed vector "result" with the cross product of "left" and "right".
  1538. * The cross product is then orthogonal to both "left" and "right".
  1539. */
  1540. Vector3.CrossToRef = function (left, right, result) {
  1541. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1542. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1543. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1544. result.copyFrom(MathTmp.Vector3[0]);
  1545. };
  1546. /**
  1547. * Returns a new Vector3 as the normalization of the passed vector.
  1548. */
  1549. Vector3.Normalize = function (vector) {
  1550. var result = Vector3.Zero();
  1551. Vector3.NormalizeToRef(vector, result);
  1552. return result;
  1553. };
  1554. /**
  1555. * Sets the passed vector "result" with the normalization of the passed first vector.
  1556. */
  1557. Vector3.NormalizeToRef = function (vector, result) {
  1558. result.copyFrom(vector);
  1559. result.normalize();
  1560. };
  1561. Vector3.Project = function (vector, world, transform, viewport) {
  1562. var cw = viewport.width;
  1563. var ch = viewport.height;
  1564. var cx = viewport.x;
  1565. var cy = viewport.y;
  1566. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1567. 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);
  1568. var matrix = MathTmp.Matrix[0];
  1569. world.multiplyToRef(transform, matrix);
  1570. matrix.multiplyToRef(viewportMatrix, matrix);
  1571. return Vector3.TransformCoordinates(vector, matrix);
  1572. };
  1573. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1574. var matrix = MathTmp.Matrix[0];
  1575. world.multiplyToRef(transform, matrix);
  1576. matrix.invert();
  1577. source.x = source.x / viewportWidth * 2 - 1;
  1578. source.y = -(source.y / viewportHeight * 2 - 1);
  1579. var vector = Vector3.TransformCoordinates(source, matrix);
  1580. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1581. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1582. vector = vector.scale(1.0 / num);
  1583. }
  1584. return vector;
  1585. };
  1586. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1587. var matrix = MathTmp.Matrix[0];
  1588. world.multiplyToRef(view, matrix);
  1589. matrix.multiplyToRef(projection, matrix);
  1590. matrix.invert();
  1591. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1592. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1593. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1594. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Minimize = function (left, right) {
  1600. var min = left.clone();
  1601. min.MinimizeInPlace(right);
  1602. return min;
  1603. };
  1604. Vector3.Maximize = function (left, right) {
  1605. var max = left.clone();
  1606. max.MaximizeInPlace(right);
  1607. return max;
  1608. };
  1609. /**
  1610. * Returns the distance (float) between the vectors "value1" and "value2".
  1611. */
  1612. Vector3.Distance = function (value1, value2) {
  1613. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1614. };
  1615. /**
  1616. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1617. */
  1618. Vector3.DistanceSquared = function (value1, value2) {
  1619. var x = value1.x - value2.x;
  1620. var y = value1.y - value2.y;
  1621. var z = value1.z - value2.z;
  1622. return (x * x) + (y * y) + (z * z);
  1623. };
  1624. /**
  1625. * Returns a new Vector3 located at the center between "value1" and "value2".
  1626. */
  1627. Vector3.Center = function (value1, value2) {
  1628. var center = value1.add(value2);
  1629. center.scaleInPlace(0.5);
  1630. return center;
  1631. };
  1632. /**
  1633. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1634. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1635. * to something in order to rotate it from its local system to the given target system.
  1636. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1637. * Returns a new Vector3.
  1638. */
  1639. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1640. var rotation = Vector3.Zero();
  1641. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1642. return rotation;
  1643. };
  1644. /**
  1645. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1646. */
  1647. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1648. var quat = MathTmp.Quaternion[0];
  1649. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1650. quat.toEulerAnglesToRef(ref);
  1651. };
  1652. return Vector3;
  1653. }());
  1654. BABYLON.Vector3 = Vector3;
  1655. //Vector4 class created for EulerAngle class conversion to Quaternion
  1656. var Vector4 = (function () {
  1657. /**
  1658. * Creates a Vector4 object from the passed floats.
  1659. */
  1660. function Vector4(x, y, z, w) {
  1661. this.x = x;
  1662. this.y = y;
  1663. this.z = z;
  1664. this.w = w;
  1665. }
  1666. /**
  1667. * Returns the string with the Vector4 coordinates.
  1668. */
  1669. Vector4.prototype.toString = function () {
  1670. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1671. };
  1672. /**
  1673. * Returns the string "Vector4".
  1674. */
  1675. Vector4.prototype.getClassName = function () {
  1676. return "Vector4";
  1677. };
  1678. /**
  1679. * Returns the Vector4 hash code.
  1680. */
  1681. Vector4.prototype.getHashCode = function () {
  1682. var hash = this.x || 0;
  1683. hash = (hash * 397) ^ (this.y || 0);
  1684. hash = (hash * 397) ^ (this.z || 0);
  1685. hash = (hash * 397) ^ (this.w || 0);
  1686. return hash;
  1687. };
  1688. // Operators
  1689. /**
  1690. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1691. */
  1692. Vector4.prototype.asArray = function () {
  1693. var result = [];
  1694. this.toArray(result, 0);
  1695. return result;
  1696. };
  1697. /**
  1698. * Populates the passed array from the passed index with the Vector4 coordinates.
  1699. * Returns the Vector4.
  1700. */
  1701. Vector4.prototype.toArray = function (array, index) {
  1702. if (index === undefined) {
  1703. index = 0;
  1704. }
  1705. array[index] = this.x;
  1706. array[index + 1] = this.y;
  1707. array[index + 2] = this.z;
  1708. array[index + 3] = this.w;
  1709. return this;
  1710. };
  1711. /**
  1712. * Adds the passed vector to the current Vector4.
  1713. * Returns the updated Vector4.
  1714. */
  1715. Vector4.prototype.addInPlace = function (otherVector) {
  1716. this.x += otherVector.x;
  1717. this.y += otherVector.y;
  1718. this.z += otherVector.z;
  1719. this.w += otherVector.w;
  1720. return this;
  1721. };
  1722. /**
  1723. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1724. */
  1725. Vector4.prototype.add = function (otherVector) {
  1726. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1727. };
  1728. /**
  1729. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1730. * Returns the current Vector4.
  1731. */
  1732. Vector4.prototype.addToRef = function (otherVector, result) {
  1733. result.x = this.x + otherVector.x;
  1734. result.y = this.y + otherVector.y;
  1735. result.z = this.z + otherVector.z;
  1736. result.w = this.w + otherVector.w;
  1737. return this;
  1738. };
  1739. /**
  1740. * Subtract in place the passed vector from the current Vector4.
  1741. * Returns the updated Vector4.
  1742. */
  1743. Vector4.prototype.subtractInPlace = function (otherVector) {
  1744. this.x -= otherVector.x;
  1745. this.y -= otherVector.y;
  1746. this.z -= otherVector.z;
  1747. this.w -= otherVector.w;
  1748. return this;
  1749. };
  1750. /**
  1751. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1752. */
  1753. Vector4.prototype.subtract = function (otherVector) {
  1754. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1755. };
  1756. /**
  1757. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1758. * Returns the current Vector4.
  1759. */
  1760. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1761. result.x = this.x - otherVector.x;
  1762. result.y = this.y - otherVector.y;
  1763. result.z = this.z - otherVector.z;
  1764. result.w = this.w - otherVector.w;
  1765. return this;
  1766. };
  1767. /**
  1768. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1769. */
  1770. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1771. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1772. };
  1773. /**
  1774. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1775. * Returns the current Vector4.
  1776. */
  1777. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1778. result.x = this.x - x;
  1779. result.y = this.y - y;
  1780. result.z = this.z - z;
  1781. result.w = this.w - w;
  1782. return this;
  1783. };
  1784. /**
  1785. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1786. */
  1787. Vector4.prototype.negate = function () {
  1788. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1789. };
  1790. /**
  1791. * Multiplies the current Vector4 coordinates by scale (float).
  1792. * Returns the updated Vector4.
  1793. */
  1794. Vector4.prototype.scaleInPlace = function (scale) {
  1795. this.x *= scale;
  1796. this.y *= scale;
  1797. this.z *= scale;
  1798. this.w *= scale;
  1799. return this;
  1800. };
  1801. /**
  1802. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1803. */
  1804. Vector4.prototype.scale = function (scale) {
  1805. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1806. };
  1807. /**
  1808. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1809. * Returns the current Vector4.
  1810. */
  1811. Vector4.prototype.scaleToRef = function (scale, result) {
  1812. result.x = this.x * scale;
  1813. result.y = this.y * scale;
  1814. result.z = this.z * scale;
  1815. result.w = this.w * scale;
  1816. return this;
  1817. };
  1818. /**
  1819. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1820. */
  1821. Vector4.prototype.equals = function (otherVector) {
  1822. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1823. };
  1824. /**
  1825. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1826. */
  1827. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1828. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1829. return otherVector
  1830. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1831. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1832. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1833. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1834. };
  1835. /**
  1836. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1837. */
  1838. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1839. return this.x === x && this.y === y && this.z === z && this.w === w;
  1840. };
  1841. /**
  1842. * Multiplies in place the current Vector4 by the passed one.
  1843. * Returns the updated Vector4.
  1844. */
  1845. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1846. this.x *= otherVector.x;
  1847. this.y *= otherVector.y;
  1848. this.z *= otherVector.z;
  1849. this.w *= otherVector.w;
  1850. return this;
  1851. };
  1852. /**
  1853. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1854. */
  1855. Vector4.prototype.multiply = function (otherVector) {
  1856. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1857. };
  1858. /**
  1859. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1860. * Returns the current Vector4.
  1861. */
  1862. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1863. result.x = this.x * otherVector.x;
  1864. result.y = this.y * otherVector.y;
  1865. result.z = this.z * otherVector.z;
  1866. result.w = this.w * otherVector.w;
  1867. return this;
  1868. };
  1869. /**
  1870. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1871. */
  1872. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1873. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1874. };
  1875. /**
  1876. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1877. */
  1878. Vector4.prototype.divide = function (otherVector) {
  1879. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1880. };
  1881. /**
  1882. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1883. * Returns the current Vector4.
  1884. */
  1885. Vector4.prototype.divideToRef = function (otherVector, result) {
  1886. result.x = this.x / otherVector.x;
  1887. result.y = this.y / otherVector.y;
  1888. result.z = this.z / otherVector.z;
  1889. result.w = this.w / otherVector.w;
  1890. return this;
  1891. };
  1892. /**
  1893. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1894. */
  1895. Vector4.prototype.MinimizeInPlace = function (other) {
  1896. if (other.x < this.x)
  1897. this.x = other.x;
  1898. if (other.y < this.y)
  1899. this.y = other.y;
  1900. if (other.z < this.z)
  1901. this.z = other.z;
  1902. if (other.w < this.w)
  1903. this.w = other.w;
  1904. return this;
  1905. };
  1906. /**
  1907. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1908. */
  1909. Vector4.prototype.MaximizeInPlace = function (other) {
  1910. if (other.x > this.x)
  1911. this.x = other.x;
  1912. if (other.y > this.y)
  1913. this.y = other.y;
  1914. if (other.z > this.z)
  1915. this.z = other.z;
  1916. if (other.w > this.w)
  1917. this.w = other.w;
  1918. return this;
  1919. };
  1920. // Properties
  1921. /**
  1922. * Returns the Vector4 length (float).
  1923. */
  1924. Vector4.prototype.length = function () {
  1925. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1926. };
  1927. /**
  1928. * Returns the Vector4 squared length (float).
  1929. */
  1930. Vector4.prototype.lengthSquared = function () {
  1931. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1932. };
  1933. // Methods
  1934. /**
  1935. * Normalizes in place the Vector4.
  1936. * Returns the updated Vector4.
  1937. */
  1938. Vector4.prototype.normalize = function () {
  1939. var len = this.length();
  1940. if (len === 0)
  1941. return this;
  1942. var num = 1.0 / len;
  1943. this.x *= num;
  1944. this.y *= num;
  1945. this.z *= num;
  1946. this.w *= num;
  1947. return this;
  1948. };
  1949. /**
  1950. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1951. */
  1952. Vector4.prototype.toVector3 = function () {
  1953. return new Vector3(this.x, this.y, this.z);
  1954. };
  1955. /**
  1956. * Returns a new Vector4 copied from the current one.
  1957. */
  1958. Vector4.prototype.clone = function () {
  1959. return new Vector4(this.x, this.y, this.z, this.w);
  1960. };
  1961. /**
  1962. * Updates the current Vector4 with the passed one coordinates.
  1963. * Returns the updated Vector4.
  1964. */
  1965. Vector4.prototype.copyFrom = function (source) {
  1966. this.x = source.x;
  1967. this.y = source.y;
  1968. this.z = source.z;
  1969. this.w = source.w;
  1970. return this;
  1971. };
  1972. /**
  1973. * Updates the current Vector4 coordinates with the passed floats.
  1974. * Returns the updated Vector4.
  1975. */
  1976. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1977. this.x = x;
  1978. this.y = y;
  1979. this.z = z;
  1980. this.w = w;
  1981. return this;
  1982. };
  1983. /**
  1984. * Updates the current Vector4 coordinates with the passed floats.
  1985. * Returns the updated Vector4.
  1986. */
  1987. Vector4.prototype.set = function (x, y, z, w) {
  1988. return this.copyFromFloats(x, y, z, w);
  1989. };
  1990. // Statics
  1991. /**
  1992. * Returns a new Vector4 set from the starting index of the passed array.
  1993. */
  1994. Vector4.FromArray = function (array, offset) {
  1995. if (!offset) {
  1996. offset = 0;
  1997. }
  1998. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1999. };
  2000. /**
  2001. * Updates the passed vector "result" from the starting index of the passed array.
  2002. */
  2003. Vector4.FromArrayToRef = function (array, offset, result) {
  2004. result.x = array[offset];
  2005. result.y = array[offset + 1];
  2006. result.z = array[offset + 2];
  2007. result.w = array[offset + 3];
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2011. */
  2012. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2013. Vector4.FromArrayToRef(array, offset, result);
  2014. };
  2015. /**
  2016. * Updates the passed vector "result" coordinates from the passed floats.
  2017. */
  2018. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2019. result.x = x;
  2020. result.y = y;
  2021. result.z = z;
  2022. result.w = w;
  2023. };
  2024. /**
  2025. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2026. */
  2027. Vector4.Zero = function () {
  2028. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2029. };
  2030. /**
  2031. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2032. */
  2033. Vector4.One = function () {
  2034. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2035. };
  2036. /**
  2037. * Returns a new normalized Vector4 from the passed one.
  2038. */
  2039. Vector4.Normalize = function (vector) {
  2040. var result = Vector4.Zero();
  2041. Vector4.NormalizeToRef(vector, result);
  2042. return result;
  2043. };
  2044. /**
  2045. * Updates the passed vector "result" from the normalization of the passed one.
  2046. */
  2047. Vector4.NormalizeToRef = function (vector, result) {
  2048. result.copyFrom(vector);
  2049. result.normalize();
  2050. };
  2051. Vector4.Minimize = function (left, right) {
  2052. var min = left.clone();
  2053. min.MinimizeInPlace(right);
  2054. return min;
  2055. };
  2056. Vector4.Maximize = function (left, right) {
  2057. var max = left.clone();
  2058. max.MaximizeInPlace(right);
  2059. return max;
  2060. };
  2061. /**
  2062. * Returns the distance (float) between the vectors "value1" and "value2".
  2063. */
  2064. Vector4.Distance = function (value1, value2) {
  2065. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2066. };
  2067. /**
  2068. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2069. */
  2070. Vector4.DistanceSquared = function (value1, value2) {
  2071. var x = value1.x - value2.x;
  2072. var y = value1.y - value2.y;
  2073. var z = value1.z - value2.z;
  2074. var w = value1.w - value2.w;
  2075. return (x * x) + (y * y) + (z * z) + (w * w);
  2076. };
  2077. /**
  2078. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2079. */
  2080. Vector4.Center = function (value1, value2) {
  2081. var center = value1.add(value2);
  2082. center.scaleInPlace(0.5);
  2083. return center;
  2084. };
  2085. /**
  2086. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2087. * This methods computes transformed normalized direction vectors only.
  2088. */
  2089. Vector4.TransformNormal = function (vector, transformation) {
  2090. var result = Vector4.Zero();
  2091. Vector4.TransformNormalToRef(vector, transformation, result);
  2092. return result;
  2093. };
  2094. /**
  2095. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2096. * This methods computes transformed normalized direction vectors only.
  2097. */
  2098. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2099. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2100. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2101. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2102. result.x = x;
  2103. result.y = y;
  2104. result.z = z;
  2105. result.w = vector.w;
  2106. };
  2107. /**
  2108. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2109. * This methods computes transformed normalized direction vectors only.
  2110. */
  2111. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2112. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2113. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2114. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2115. result.w = w;
  2116. };
  2117. return Vector4;
  2118. }());
  2119. BABYLON.Vector4 = Vector4;
  2120. var Size = (function () {
  2121. /**
  2122. * Creates a Size object from the passed width and height (floats).
  2123. */
  2124. function Size(width, height) {
  2125. this.width = width;
  2126. this.height = height;
  2127. }
  2128. // Returns a string with the Size width and height.
  2129. Size.prototype.toString = function () {
  2130. return "{W: " + this.width + ", H: " + this.height + "}";
  2131. };
  2132. /**
  2133. * Returns the string "Size"
  2134. */
  2135. Size.prototype.getClassName = function () {
  2136. return "Size";
  2137. };
  2138. /**
  2139. * Returns the Size hash code.
  2140. */
  2141. Size.prototype.getHashCode = function () {
  2142. var hash = this.width || 0;
  2143. hash = (hash * 397) ^ (this.height || 0);
  2144. return hash;
  2145. };
  2146. /**
  2147. * Updates the current size from the passed one.
  2148. * Returns the updated Size.
  2149. */
  2150. Size.prototype.copyFrom = function (src) {
  2151. this.width = src.width;
  2152. this.height = src.height;
  2153. };
  2154. /**
  2155. * Updates in place the current Size from the passed floats.
  2156. * Returns the updated Size.
  2157. */
  2158. Size.prototype.copyFromFloats = function (width, height) {
  2159. this.width = width;
  2160. this.height = height;
  2161. return this;
  2162. };
  2163. /**
  2164. * Updates in place the current Size from the passed floats.
  2165. * Returns the updated Size.
  2166. */
  2167. Size.prototype.set = function (width, height) {
  2168. return this.copyFromFloats(width, height);
  2169. };
  2170. /**
  2171. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2172. */
  2173. Size.prototype.multiplyByFloats = function (w, h) {
  2174. return new Size(this.width * w, this.height * h);
  2175. };
  2176. /**
  2177. * Returns a new Size copied from the passed one.
  2178. */
  2179. Size.prototype.clone = function () {
  2180. return new Size(this.width, this.height);
  2181. };
  2182. /**
  2183. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2184. */
  2185. Size.prototype.equals = function (other) {
  2186. if (!other) {
  2187. return false;
  2188. }
  2189. return (this.width === other.width) && (this.height === other.height);
  2190. };
  2191. Object.defineProperty(Size.prototype, "surface", {
  2192. /**
  2193. * Returns the surface of the Size : width * height (float).
  2194. */
  2195. get: function () {
  2196. return this.width * this.height;
  2197. },
  2198. enumerable: true,
  2199. configurable: true
  2200. });
  2201. /**
  2202. * Returns a new Size set to (0.0, 0.0)
  2203. */
  2204. Size.Zero = function () {
  2205. return new Size(0.0, 0.0);
  2206. };
  2207. /**
  2208. * Returns a new Size set as the addition result of the current Size and the passed one.
  2209. */
  2210. Size.prototype.add = function (otherSize) {
  2211. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2212. return r;
  2213. };
  2214. /**
  2215. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2216. */
  2217. Size.prototype.subtract = 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 at the linear interpolation "amount" between "start" and "end".
  2223. */
  2224. Size.Lerp = function (start, end, amount) {
  2225. var w = start.width + ((end.width - start.width) * amount);
  2226. var h = start.height + ((end.height - start.height) * amount);
  2227. return new Size(w, h);
  2228. };
  2229. return Size;
  2230. }());
  2231. BABYLON.Size = Size;
  2232. var Quaternion = (function () {
  2233. /**
  2234. * Creates a new Quaternion from the passed floats.
  2235. */
  2236. function Quaternion(x, y, z, w) {
  2237. if (x === void 0) { x = 0.0; }
  2238. if (y === void 0) { y = 0.0; }
  2239. if (z === void 0) { z = 0.0; }
  2240. if (w === void 0) { w = 1.0; }
  2241. this.x = x;
  2242. this.y = y;
  2243. this.z = z;
  2244. this.w = w;
  2245. }
  2246. /**
  2247. * Returns a string with the Quaternion coordinates.
  2248. */
  2249. Quaternion.prototype.toString = function () {
  2250. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2251. };
  2252. /**
  2253. * Returns the string "Quaternion".
  2254. */
  2255. Quaternion.prototype.getClassName = function () {
  2256. return "Quaternion";
  2257. };
  2258. /**
  2259. * Returns the Quaternion hash code.
  2260. */
  2261. Quaternion.prototype.getHashCode = function () {
  2262. var hash = this.x || 0;
  2263. hash = (hash * 397) ^ (this.y || 0);
  2264. hash = (hash * 397) ^ (this.z || 0);
  2265. hash = (hash * 397) ^ (this.w || 0);
  2266. return hash;
  2267. };
  2268. /**
  2269. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2270. */
  2271. Quaternion.prototype.asArray = function () {
  2272. return [this.x, this.y, this.z, this.w];
  2273. };
  2274. /**
  2275. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2276. */
  2277. Quaternion.prototype.equals = function (otherQuaternion) {
  2278. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2279. };
  2280. /**
  2281. * Returns a new Quaternion copied from the current one.
  2282. */
  2283. Quaternion.prototype.clone = function () {
  2284. return new Quaternion(this.x, this.y, this.z, this.w);
  2285. };
  2286. /**
  2287. * Updates the current Quaternion from the passed one coordinates.
  2288. * Returns the updated Quaterion.
  2289. */
  2290. Quaternion.prototype.copyFrom = function (other) {
  2291. this.x = other.x;
  2292. this.y = other.y;
  2293. this.z = other.z;
  2294. this.w = other.w;
  2295. return this;
  2296. };
  2297. /**
  2298. * Updates the current Quaternion from the passed float coordinates.
  2299. * Returns the updated Quaterion.
  2300. */
  2301. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2302. this.x = x;
  2303. this.y = y;
  2304. this.z = z;
  2305. this.w = w;
  2306. return this;
  2307. };
  2308. /**
  2309. * Updates the current Quaternion from the passed float coordinates.
  2310. * Returns the updated Quaterion.
  2311. */
  2312. Quaternion.prototype.set = function (x, y, z, w) {
  2313. return this.copyFromFloats(x, y, z, w);
  2314. };
  2315. /**
  2316. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2317. */
  2318. Quaternion.prototype.add = function (other) {
  2319. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2320. };
  2321. /**
  2322. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2323. */
  2324. Quaternion.prototype.subtract = function (other) {
  2325. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2326. };
  2327. /**
  2328. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2329. */
  2330. Quaternion.prototype.scale = function (value) {
  2331. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2332. };
  2333. /**
  2334. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2335. */
  2336. Quaternion.prototype.multiply = function (q1) {
  2337. var result = new Quaternion(0, 0, 0, 1.0);
  2338. this.multiplyToRef(q1, result);
  2339. return result;
  2340. };
  2341. /**
  2342. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2343. * Returns the current Quaternion.
  2344. */
  2345. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2346. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2347. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2348. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2349. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2350. result.copyFromFloats(x, y, z, w);
  2351. return this;
  2352. };
  2353. /**
  2354. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2355. * Returns the updated Quaternion.
  2356. */
  2357. Quaternion.prototype.multiplyInPlace = function (q1) {
  2358. this.multiplyToRef(q1, this);
  2359. return this;
  2360. };
  2361. /**
  2362. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2363. * Returns the current Quaternion.
  2364. */
  2365. Quaternion.prototype.conjugateToRef = function (ref) {
  2366. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2367. return this;
  2368. };
  2369. /**
  2370. * Conjugates in place the current Quaternion.
  2371. * Returns the updated Quaternion.
  2372. */
  2373. Quaternion.prototype.conjugateInPlace = function () {
  2374. this.x *= -1;
  2375. this.y *= -1;
  2376. this.z *= -1;
  2377. return this;
  2378. };
  2379. /**
  2380. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2381. */
  2382. Quaternion.prototype.conjugate = function () {
  2383. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2384. return result;
  2385. };
  2386. /**
  2387. * Returns the Quaternion length (float).
  2388. */
  2389. Quaternion.prototype.length = function () {
  2390. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2391. };
  2392. /**
  2393. * Normalize in place the current Quaternion.
  2394. * Returns the updated Quaternion.
  2395. */
  2396. Quaternion.prototype.normalize = function () {
  2397. var length = 1.0 / this.length();
  2398. this.x *= length;
  2399. this.y *= length;
  2400. this.z *= length;
  2401. this.w *= length;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2406. */
  2407. Quaternion.prototype.toEulerAngles = function (order) {
  2408. if (order === void 0) { order = "YZX"; }
  2409. var result = Vector3.Zero();
  2410. this.toEulerAnglesToRef(result, order);
  2411. return result;
  2412. };
  2413. /**
  2414. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2415. * Returns the current Quaternion.
  2416. */
  2417. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2418. if (order === void 0) { order = "YZX"; }
  2419. var qz = this.z;
  2420. var qx = this.x;
  2421. var qy = this.y;
  2422. var qw = this.w;
  2423. var sqw = qw * qw;
  2424. var sqz = qz * qz;
  2425. var sqx = qx * qx;
  2426. var sqy = qy * qy;
  2427. var zAxisY = qy * qz - qx * qw;
  2428. var limit = .4999999;
  2429. if (zAxisY < -limit) {
  2430. result.y = 2 * Math.atan2(qy, qw);
  2431. result.x = Math.PI / 2;
  2432. result.z = 0;
  2433. }
  2434. else if (zAxisY > limit) {
  2435. result.y = 2 * Math.atan2(qy, qw);
  2436. result.x = -Math.PI / 2;
  2437. result.z = 0;
  2438. }
  2439. else {
  2440. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2441. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2442. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2443. }
  2444. return this;
  2445. };
  2446. /**
  2447. * Updates the passed rotation matrix with the current Quaternion values.
  2448. * Returns the current Quaternion.
  2449. */
  2450. Quaternion.prototype.toRotationMatrix = function (result) {
  2451. var xx = this.x * this.x;
  2452. var yy = this.y * this.y;
  2453. var zz = this.z * this.z;
  2454. var xy = this.x * this.y;
  2455. var zw = this.z * this.w;
  2456. var zx = this.z * this.x;
  2457. var yw = this.y * this.w;
  2458. var yz = this.y * this.z;
  2459. var xw = this.x * this.w;
  2460. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2461. result.m[1] = 2.0 * (xy + zw);
  2462. result.m[2] = 2.0 * (zx - yw);
  2463. result.m[3] = 0;
  2464. result.m[4] = 2.0 * (xy - zw);
  2465. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2466. result.m[6] = 2.0 * (yz + xw);
  2467. result.m[7] = 0;
  2468. result.m[8] = 2.0 * (zx + yw);
  2469. result.m[9] = 2.0 * (yz - xw);
  2470. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2471. result.m[11] = 0;
  2472. result.m[12] = 0;
  2473. result.m[13] = 0;
  2474. result.m[14] = 0;
  2475. result.m[15] = 1.0;
  2476. result._markAsUpdated();
  2477. return this;
  2478. };
  2479. /**
  2480. * Updates the current Quaternion from the passed rotation matrix values.
  2481. * Returns the updated Quaternion.
  2482. */
  2483. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2484. Quaternion.FromRotationMatrixToRef(matrix, this);
  2485. return this;
  2486. };
  2487. // Statics
  2488. /**
  2489. * Returns a new Quaternion set from the passed rotation matrix values.
  2490. */
  2491. Quaternion.FromRotationMatrix = function (matrix) {
  2492. var result = new Quaternion();
  2493. Quaternion.FromRotationMatrixToRef(matrix, result);
  2494. return result;
  2495. };
  2496. /**
  2497. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2498. */
  2499. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2500. var data = matrix.m;
  2501. var m11 = data[0], m12 = data[4], m13 = data[8];
  2502. var m21 = data[1], m22 = data[5], m23 = data[9];
  2503. var m31 = data[2], m32 = data[6], m33 = data[10];
  2504. var trace = m11 + m22 + m33;
  2505. var s;
  2506. if (trace > 0) {
  2507. s = 0.5 / Math.sqrt(trace + 1.0);
  2508. result.w = 0.25 / s;
  2509. result.x = (m32 - m23) * s;
  2510. result.y = (m13 - m31) * s;
  2511. result.z = (m21 - m12) * s;
  2512. }
  2513. else if (m11 > m22 && m11 > m33) {
  2514. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2515. result.w = (m32 - m23) / s;
  2516. result.x = 0.25 * s;
  2517. result.y = (m12 + m21) / s;
  2518. result.z = (m13 + m31) / s;
  2519. }
  2520. else if (m22 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2522. result.w = (m13 - m31) / s;
  2523. result.x = (m12 + m21) / s;
  2524. result.y = 0.25 * s;
  2525. result.z = (m23 + m32) / s;
  2526. }
  2527. else {
  2528. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2529. result.w = (m21 - m12) / s;
  2530. result.x = (m13 + m31) / s;
  2531. result.y = (m23 + m32) / s;
  2532. result.z = 0.25 * s;
  2533. }
  2534. };
  2535. /**
  2536. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2537. */
  2538. Quaternion.Zero = function () {
  2539. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2540. };
  2541. /**
  2542. * Returns a new Quaternion as the inverted current Quaternion.
  2543. */
  2544. Quaternion.Inverse = function (q) {
  2545. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2546. };
  2547. /**
  2548. * Returns the identity Quaternion.
  2549. */
  2550. Quaternion.Identity = function () {
  2551. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2552. };
  2553. Quaternion.IsIdentity = function (quaternion) {
  2554. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2555. };
  2556. /**
  2557. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2558. */
  2559. Quaternion.RotationAxis = function (axis, angle) {
  2560. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2561. };
  2562. /**
  2563. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2564. */
  2565. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2566. var sin = Math.sin(angle / 2);
  2567. axis.normalize();
  2568. result.w = Math.cos(angle / 2);
  2569. result.x = axis.x * sin;
  2570. result.y = axis.y * sin;
  2571. result.z = axis.z * sin;
  2572. return result;
  2573. };
  2574. /**
  2575. * Retuns a new Quaternion set from the starting index of the passed array.
  2576. */
  2577. Quaternion.FromArray = function (array, offset) {
  2578. if (!offset) {
  2579. offset = 0;
  2580. }
  2581. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2582. };
  2583. /**
  2584. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2585. */
  2586. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2587. var q = new Quaternion();
  2588. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2589. return q;
  2590. };
  2591. /**
  2592. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2593. */
  2594. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2595. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2596. var halfRoll = roll * 0.5;
  2597. var halfPitch = pitch * 0.5;
  2598. var halfYaw = yaw * 0.5;
  2599. var sinRoll = Math.sin(halfRoll);
  2600. var cosRoll = Math.cos(halfRoll);
  2601. var sinPitch = Math.sin(halfPitch);
  2602. var cosPitch = Math.cos(halfPitch);
  2603. var sinYaw = Math.sin(halfYaw);
  2604. var cosYaw = Math.cos(halfYaw);
  2605. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2606. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2607. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2608. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2609. };
  2610. /**
  2611. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2612. */
  2613. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2614. var result = new Quaternion();
  2615. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2616. return result;
  2617. };
  2618. /**
  2619. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2620. */
  2621. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2622. // Produces a quaternion from Euler angles in the z-x-z orientation
  2623. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2624. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2625. var halfBeta = beta * 0.5;
  2626. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2627. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2628. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2629. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2630. };
  2631. /**
  2632. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2633. * cf to Vector3.RotationFromAxis() documentation.
  2634. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2635. */
  2636. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2637. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2638. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2639. return quat;
  2640. };
  2641. /**
  2642. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2643. * cf to Vector3.RotationFromAxis() documentation.
  2644. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2645. */
  2646. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2647. var rotMat = MathTmp.Matrix[0];
  2648. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2649. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2650. };
  2651. Quaternion.Slerp = function (left, right, amount) {
  2652. var result = Quaternion.Identity();
  2653. Quaternion.SlerpToRef(left, right, amount, result);
  2654. return result;
  2655. };
  2656. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2657. var num2;
  2658. var num3;
  2659. var num = amount;
  2660. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2661. var flag = false;
  2662. if (num4 < 0) {
  2663. flag = true;
  2664. num4 = -num4;
  2665. }
  2666. if (num4 > 0.999999) {
  2667. num3 = 1 - num;
  2668. num2 = flag ? -num : num;
  2669. }
  2670. else {
  2671. var num5 = Math.acos(num4);
  2672. var num6 = (1.0 / Math.sin(num5));
  2673. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2674. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2675. }
  2676. result.x = (num3 * left.x) + (num2 * right.x);
  2677. result.y = (num3 * left.y) + (num2 * right.y);
  2678. result.z = (num3 * left.z) + (num2 * right.z);
  2679. result.w = (num3 * left.w) + (num2 * right.w);
  2680. };
  2681. /**
  2682. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2683. */
  2684. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2685. var squared = amount * amount;
  2686. var cubed = amount * squared;
  2687. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2688. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2689. var part3 = (cubed - (2.0 * squared)) + amount;
  2690. var part4 = cubed - squared;
  2691. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2692. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2693. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2694. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2695. return new Quaternion(x, y, z, w);
  2696. };
  2697. return Quaternion;
  2698. }());
  2699. BABYLON.Quaternion = Quaternion;
  2700. var Matrix = (function () {
  2701. function Matrix() {
  2702. this._isIdentity = false;
  2703. this._isIdentityDirty = true;
  2704. this.m = new Float32Array(16);
  2705. this._markAsUpdated();
  2706. }
  2707. Matrix.prototype._markAsUpdated = function () {
  2708. this.updateFlag = Matrix._updateFlagSeed++;
  2709. this._isIdentityDirty = true;
  2710. };
  2711. // Properties
  2712. /**
  2713. * Boolean : True is the matrix is the identity matrix
  2714. */
  2715. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2716. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2717. if (this._isIdentityDirty) {
  2718. this._isIdentityDirty = false;
  2719. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2720. this._isIdentity = false;
  2721. }
  2722. else 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. this._isIdentity = false;
  2727. }
  2728. else {
  2729. this._isIdentity = true;
  2730. }
  2731. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2732. this._isIdentity = false;
  2733. }
  2734. }
  2735. return this._isIdentity;
  2736. };
  2737. /**
  2738. * Returns the matrix determinant (float).
  2739. */
  2740. Matrix.prototype.determinant = function () {
  2741. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2742. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2743. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2744. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2745. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2746. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2747. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2748. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2749. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2750. };
  2751. // Methods
  2752. /**
  2753. * Returns the matrix underlying array.
  2754. */
  2755. Matrix.prototype.toArray = function () {
  2756. return this.m;
  2757. };
  2758. /**
  2759. * Returns the matrix underlying array.
  2760. */
  2761. Matrix.prototype.asArray = function () {
  2762. return this.toArray();
  2763. };
  2764. /**
  2765. * Inverts in place the Matrix.
  2766. * Returns the Matrix inverted.
  2767. */
  2768. Matrix.prototype.invert = function () {
  2769. this.invertToRef(this);
  2770. return this;
  2771. };
  2772. /**
  2773. * Sets all the matrix elements to zero.
  2774. * Returns the Matrix.
  2775. */
  2776. Matrix.prototype.reset = function () {
  2777. for (var index = 0; index < 16; index++) {
  2778. this.m[index] = 0.0;
  2779. }
  2780. this._markAsUpdated();
  2781. return this;
  2782. };
  2783. /**
  2784. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2785. */
  2786. Matrix.prototype.add = function (other) {
  2787. var result = new Matrix();
  2788. this.addToRef(other, result);
  2789. return result;
  2790. };
  2791. /**
  2792. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2793. * Returns the Matrix.
  2794. */
  2795. Matrix.prototype.addToRef = function (other, result) {
  2796. for (var index = 0; index < 16; index++) {
  2797. result.m[index] = this.m[index] + other.m[index];
  2798. }
  2799. result._markAsUpdated();
  2800. return this;
  2801. };
  2802. /**
  2803. * Adds in place the passed matrix to the current Matrix.
  2804. * Returns the updated Matrix.
  2805. */
  2806. Matrix.prototype.addToSelf = function (other) {
  2807. for (var index = 0; index < 16; index++) {
  2808. this.m[index] += other.m[index];
  2809. }
  2810. this._markAsUpdated();
  2811. return this;
  2812. };
  2813. /**
  2814. * Sets the passed matrix with the current inverted Matrix.
  2815. * Returns the unmodified current Matrix.
  2816. */
  2817. Matrix.prototype.invertToRef = function (other) {
  2818. var l1 = this.m[0];
  2819. var l2 = this.m[1];
  2820. var l3 = this.m[2];
  2821. var l4 = this.m[3];
  2822. var l5 = this.m[4];
  2823. var l6 = this.m[5];
  2824. var l7 = this.m[6];
  2825. var l8 = this.m[7];
  2826. var l9 = this.m[8];
  2827. var l10 = this.m[9];
  2828. var l11 = this.m[10];
  2829. var l12 = this.m[11];
  2830. var l13 = this.m[12];
  2831. var l14 = this.m[13];
  2832. var l15 = this.m[14];
  2833. var l16 = this.m[15];
  2834. var l17 = (l11 * l16) - (l12 * l15);
  2835. var l18 = (l10 * l16) - (l12 * l14);
  2836. var l19 = (l10 * l15) - (l11 * l14);
  2837. var l20 = (l9 * l16) - (l12 * l13);
  2838. var l21 = (l9 * l15) - (l11 * l13);
  2839. var l22 = (l9 * l14) - (l10 * l13);
  2840. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2841. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2842. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2843. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2844. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2845. var l28 = (l7 * l16) - (l8 * l15);
  2846. var l29 = (l6 * l16) - (l8 * l14);
  2847. var l30 = (l6 * l15) - (l7 * l14);
  2848. var l31 = (l5 * l16) - (l8 * l13);
  2849. var l32 = (l5 * l15) - (l7 * l13);
  2850. var l33 = (l5 * l14) - (l6 * l13);
  2851. var l34 = (l7 * l12) - (l8 * l11);
  2852. var l35 = (l6 * l12) - (l8 * l10);
  2853. var l36 = (l6 * l11) - (l7 * l10);
  2854. var l37 = (l5 * l12) - (l8 * l9);
  2855. var l38 = (l5 * l11) - (l7 * l9);
  2856. var l39 = (l5 * l10) - (l6 * l9);
  2857. other.m[0] = l23 * l27;
  2858. other.m[4] = l24 * l27;
  2859. other.m[8] = l25 * l27;
  2860. other.m[12] = l26 * l27;
  2861. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2862. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2863. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2864. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2865. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2866. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2867. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2868. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2869. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2870. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2871. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2872. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2873. other._markAsUpdated();
  2874. return this;
  2875. };
  2876. /**
  2877. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2878. * Returns the updated Matrix.
  2879. */
  2880. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2881. this.m[12] = x;
  2882. this.m[13] = y;
  2883. this.m[14] = z;
  2884. this._markAsUpdated();
  2885. return this;
  2886. };
  2887. /**
  2888. * Inserts the translation vector in the current Matrix.
  2889. * Returns the updated Matrix.
  2890. */
  2891. Matrix.prototype.setTranslation = function (vector3) {
  2892. this.m[12] = vector3.x;
  2893. this.m[13] = vector3.y;
  2894. this.m[14] = vector3.z;
  2895. this._markAsUpdated();
  2896. return this;
  2897. };
  2898. /**
  2899. * Returns a new Vector3 as the extracted translation from the Matrix.
  2900. */
  2901. Matrix.prototype.getTranslation = function () {
  2902. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2903. };
  2904. /**
  2905. * Fill a Vector3 with the extracted translation from the Matrix.
  2906. */
  2907. Matrix.prototype.getTranslationToRef = function (result) {
  2908. result.x = this.m[12];
  2909. result.y = this.m[13];
  2910. result.z = this.m[14];
  2911. return this;
  2912. };
  2913. /**
  2914. * Remove rotation and scaling part from the Matrix.
  2915. * Returns the updated Matrix.
  2916. */
  2917. Matrix.prototype.removeRotationAndScaling = function () {
  2918. this.setRowFromFloats(0, 1, 0, 0, 0);
  2919. this.setRowFromFloats(1, 0, 1, 0, 0);
  2920. this.setRowFromFloats(2, 0, 0, 1, 0);
  2921. return this;
  2922. };
  2923. /**
  2924. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2925. */
  2926. Matrix.prototype.multiply = function (other) {
  2927. var result = new Matrix();
  2928. this.multiplyToRef(other, result);
  2929. return result;
  2930. };
  2931. /**
  2932. * Updates the current Matrix from the passed one values.
  2933. * Returns the updated Matrix.
  2934. */
  2935. Matrix.prototype.copyFrom = function (other) {
  2936. for (var index = 0; index < 16; index++) {
  2937. this.m[index] = other.m[index];
  2938. }
  2939. this._markAsUpdated();
  2940. return this;
  2941. };
  2942. /**
  2943. * Populates the passed array from the starting index with the Matrix values.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.copyToArray = function (array, offset) {
  2947. if (offset === void 0) { offset = 0; }
  2948. for (var index = 0; index < 16; index++) {
  2949. array[offset + index] = this.m[index];
  2950. }
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToRef = function (other, result) {
  2957. this.multiplyToArray(other, result.m, 0);
  2958. result._markAsUpdated();
  2959. return this;
  2960. };
  2961. /**
  2962. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2963. */
  2964. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2965. var tm0 = this.m[0];
  2966. var tm1 = this.m[1];
  2967. var tm2 = this.m[2];
  2968. var tm3 = this.m[3];
  2969. var tm4 = this.m[4];
  2970. var tm5 = this.m[5];
  2971. var tm6 = this.m[6];
  2972. var tm7 = this.m[7];
  2973. var tm8 = this.m[8];
  2974. var tm9 = this.m[9];
  2975. var tm10 = this.m[10];
  2976. var tm11 = this.m[11];
  2977. var tm12 = this.m[12];
  2978. var tm13 = this.m[13];
  2979. var tm14 = this.m[14];
  2980. var tm15 = this.m[15];
  2981. var om0 = other.m[0];
  2982. var om1 = other.m[1];
  2983. var om2 = other.m[2];
  2984. var om3 = other.m[3];
  2985. var om4 = other.m[4];
  2986. var om5 = other.m[5];
  2987. var om6 = other.m[6];
  2988. var om7 = other.m[7];
  2989. var om8 = other.m[8];
  2990. var om9 = other.m[9];
  2991. var om10 = other.m[10];
  2992. var om11 = other.m[11];
  2993. var om12 = other.m[12];
  2994. var om13 = other.m[13];
  2995. var om14 = other.m[14];
  2996. var om15 = other.m[15];
  2997. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2998. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2999. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3000. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3001. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3002. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3003. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3004. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3005. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3006. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3007. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3008. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3009. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3010. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3011. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3012. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3013. return this;
  3014. };
  3015. /**
  3016. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3017. */
  3018. Matrix.prototype.equals = function (value) {
  3019. return value &&
  3020. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3021. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3022. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3023. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3024. };
  3025. /**
  3026. * Returns a new Matrix from the current Matrix.
  3027. */
  3028. Matrix.prototype.clone = function () {
  3029. 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]);
  3030. };
  3031. /**
  3032. * Returns the string "Matrix"
  3033. */
  3034. Matrix.prototype.getClassName = function () {
  3035. return "Matrix";
  3036. };
  3037. /**
  3038. * Returns the Matrix hash code.
  3039. */
  3040. Matrix.prototype.getHashCode = function () {
  3041. var hash = this.m[0] || 0;
  3042. for (var i = 1; i < 16; i++) {
  3043. hash = (hash * 397) ^ (this.m[i] || 0);
  3044. }
  3045. return hash;
  3046. };
  3047. /**
  3048. * Decomposes the current Matrix into :
  3049. * - a scale vector3 passed as a reference to update,
  3050. * - a rotation quaternion passed as a reference to update,
  3051. * - a translation vector3 passed as a reference to update.
  3052. * Returns the boolean `true`.
  3053. */
  3054. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3055. translation.x = this.m[12];
  3056. translation.y = this.m[13];
  3057. translation.z = this.m[14];
  3058. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3059. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3060. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3061. if (this.determinant() <= 0) {
  3062. scale.y *= -1;
  3063. }
  3064. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3065. rotation.x = 0;
  3066. rotation.y = 0;
  3067. rotation.z = 0;
  3068. rotation.w = 1;
  3069. return false;
  3070. }
  3071. 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]);
  3072. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3073. return true;
  3074. };
  3075. /**
  3076. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3077. */
  3078. Matrix.prototype.getRotationMatrix = function () {
  3079. var result = Matrix.Identity();
  3080. this.getRotationMatrixToRef(result);
  3081. return result;
  3082. };
  3083. /**
  3084. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3085. * Returns the current Matrix.
  3086. */
  3087. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3088. var m = this.m;
  3089. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3090. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3091. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3092. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3093. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3094. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3095. 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);
  3096. return this;
  3097. };
  3098. // Statics
  3099. /**
  3100. * Returns a new Matrix set from the starting index of the passed array.
  3101. */
  3102. Matrix.FromArray = function (array, offset) {
  3103. var result = new Matrix();
  3104. if (!offset) {
  3105. offset = 0;
  3106. }
  3107. Matrix.FromArrayToRef(array, offset, result);
  3108. return result;
  3109. };
  3110. /**
  3111. * Sets the passed "result" matrix from the starting index of the passed array.
  3112. */
  3113. Matrix.FromArrayToRef = function (array, offset, result) {
  3114. for (var index = 0; index < 16; index++) {
  3115. result.m[index] = array[index + offset];
  3116. }
  3117. result._markAsUpdated();
  3118. };
  3119. /**
  3120. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3121. */
  3122. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3123. for (var index = 0; index < 16; index++) {
  3124. result.m[index] = array[index + offset] * scale;
  3125. }
  3126. result._markAsUpdated();
  3127. };
  3128. /**
  3129. * Sets the passed matrix "result" with the 16 passed floats.
  3130. */
  3131. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3132. result.m[0] = initialM11;
  3133. result.m[1] = initialM12;
  3134. result.m[2] = initialM13;
  3135. result.m[3] = initialM14;
  3136. result.m[4] = initialM21;
  3137. result.m[5] = initialM22;
  3138. result.m[6] = initialM23;
  3139. result.m[7] = initialM24;
  3140. result.m[8] = initialM31;
  3141. result.m[9] = initialM32;
  3142. result.m[10] = initialM33;
  3143. result.m[11] = initialM34;
  3144. result.m[12] = initialM41;
  3145. result.m[13] = initialM42;
  3146. result.m[14] = initialM43;
  3147. result.m[15] = initialM44;
  3148. result._markAsUpdated();
  3149. };
  3150. /**
  3151. * Returns the index-th row of the current matrix as a new Vector4.
  3152. */
  3153. Matrix.prototype.getRow = function (index) {
  3154. if (index < 0 || index > 3) {
  3155. return null;
  3156. }
  3157. var i = index * 4;
  3158. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3159. };
  3160. /**
  3161. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3162. * Returns the updated Matrix.
  3163. */
  3164. Matrix.prototype.setRow = function (index, row) {
  3165. if (index < 0 || index > 3) {
  3166. return this;
  3167. }
  3168. var i = index * 4;
  3169. this.m[i + 0] = row.x;
  3170. this.m[i + 1] = row.y;
  3171. this.m[i + 2] = row.z;
  3172. this.m[i + 3] = row.w;
  3173. this._markAsUpdated();
  3174. return this;
  3175. };
  3176. /**
  3177. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3178. * Returns the updated Matrix.
  3179. */
  3180. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3181. if (index < 0 || index > 3) {
  3182. return this;
  3183. }
  3184. var i = index * 4;
  3185. this.m[i + 0] = x;
  3186. this.m[i + 1] = y;
  3187. this.m[i + 2] = z;
  3188. this.m[i + 3] = w;
  3189. this._markAsUpdated();
  3190. return this;
  3191. };
  3192. /**
  3193. * Returns a new Matrix set from the 16 passed floats.
  3194. */
  3195. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3196. var result = new Matrix();
  3197. result.m[0] = initialM11;
  3198. result.m[1] = initialM12;
  3199. result.m[2] = initialM13;
  3200. result.m[3] = initialM14;
  3201. result.m[4] = initialM21;
  3202. result.m[5] = initialM22;
  3203. result.m[6] = initialM23;
  3204. result.m[7] = initialM24;
  3205. result.m[8] = initialM31;
  3206. result.m[9] = initialM32;
  3207. result.m[10] = initialM33;
  3208. result.m[11] = initialM34;
  3209. result.m[12] = initialM41;
  3210. result.m[13] = initialM42;
  3211. result.m[14] = initialM43;
  3212. result.m[15] = initialM44;
  3213. return result;
  3214. };
  3215. /**
  3216. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.Compose = function (scale, rotation, translation) {
  3219. var result = Matrix.Identity();
  3220. Matrix.ComposeToRef(scale, rotation, translation, result);
  3221. return result;
  3222. };
  3223. /**
  3224. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3225. */
  3226. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3227. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3228. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3229. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3230. result.setTranslation(translation);
  3231. };
  3232. /**
  3233. * Returns a new indentity Matrix.
  3234. */
  3235. Matrix.Identity = function () {
  3236. 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);
  3237. };
  3238. /**
  3239. * Sets the passed "result" as an identity matrix.
  3240. */
  3241. Matrix.IdentityToRef = function (result) {
  3242. 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);
  3243. };
  3244. /**
  3245. * Returns a new zero Matrix.
  3246. */
  3247. Matrix.Zero = function () {
  3248. 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);
  3249. };
  3250. /**
  3251. * Returns a new rotation matrix for "angle" radians around the X axis.
  3252. */
  3253. Matrix.RotationX = function (angle) {
  3254. var result = new Matrix();
  3255. Matrix.RotationXToRef(angle, result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Returns a new Matrix as the passed inverted one.
  3260. */
  3261. Matrix.Invert = function (source) {
  3262. var result = new Matrix();
  3263. source.invertToRef(result);
  3264. return result;
  3265. };
  3266. /**
  3267. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3268. */
  3269. Matrix.RotationXToRef = function (angle, result) {
  3270. var s = Math.sin(angle);
  3271. var c = Math.cos(angle);
  3272. result.m[0] = 1.0;
  3273. result.m[15] = 1.0;
  3274. result.m[5] = c;
  3275. result.m[10] = c;
  3276. result.m[9] = -s;
  3277. result.m[6] = s;
  3278. result.m[1] = 0.0;
  3279. result.m[2] = 0.0;
  3280. result.m[3] = 0.0;
  3281. result.m[4] = 0.0;
  3282. result.m[7] = 0.0;
  3283. result.m[8] = 0.0;
  3284. result.m[11] = 0.0;
  3285. result.m[12] = 0.0;
  3286. result.m[13] = 0.0;
  3287. result.m[14] = 0.0;
  3288. result._markAsUpdated();
  3289. };
  3290. /**
  3291. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationY = function (angle) {
  3294. var result = new Matrix();
  3295. Matrix.RotationYToRef(angle, result);
  3296. return result;
  3297. };
  3298. /**
  3299. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3300. */
  3301. Matrix.RotationYToRef = function (angle, result) {
  3302. var s = Math.sin(angle);
  3303. var c = Math.cos(angle);
  3304. result.m[5] = 1.0;
  3305. result.m[15] = 1.0;
  3306. result.m[0] = c;
  3307. result.m[2] = -s;
  3308. result.m[8] = s;
  3309. result.m[10] = c;
  3310. result.m[1] = 0.0;
  3311. result.m[3] = 0.0;
  3312. result.m[4] = 0.0;
  3313. result.m[6] = 0.0;
  3314. result.m[7] = 0.0;
  3315. result.m[9] = 0.0;
  3316. result.m[11] = 0.0;
  3317. result.m[12] = 0.0;
  3318. result.m[13] = 0.0;
  3319. result.m[14] = 0.0;
  3320. result._markAsUpdated();
  3321. };
  3322. /**
  3323. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZ = function (angle) {
  3326. var result = new Matrix();
  3327. Matrix.RotationZToRef(angle, result);
  3328. return result;
  3329. };
  3330. /**
  3331. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3332. */
  3333. Matrix.RotationZToRef = function (angle, result) {
  3334. var s = Math.sin(angle);
  3335. var c = Math.cos(angle);
  3336. result.m[10] = 1.0;
  3337. result.m[15] = 1.0;
  3338. result.m[0] = c;
  3339. result.m[1] = s;
  3340. result.m[4] = -s;
  3341. result.m[5] = c;
  3342. result.m[2] = 0.0;
  3343. result.m[3] = 0.0;
  3344. result.m[6] = 0.0;
  3345. result.m[7] = 0.0;
  3346. result.m[8] = 0.0;
  3347. result.m[9] = 0.0;
  3348. result.m[11] = 0.0;
  3349. result.m[12] = 0.0;
  3350. result.m[13] = 0.0;
  3351. result.m[14] = 0.0;
  3352. result._markAsUpdated();
  3353. };
  3354. /**
  3355. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxis = function (axis, angle) {
  3358. var result = Matrix.Zero();
  3359. Matrix.RotationAxisToRef(axis, angle, result);
  3360. return result;
  3361. };
  3362. /**
  3363. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3364. */
  3365. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3366. var s = Math.sin(-angle);
  3367. var c = Math.cos(-angle);
  3368. var c1 = 1 - c;
  3369. axis.normalize();
  3370. result.m[0] = (axis.x * axis.x) * c1 + c;
  3371. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3372. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3373. result.m[3] = 0.0;
  3374. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3375. result.m[5] = (axis.y * axis.y) * c1 + c;
  3376. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3377. result.m[7] = 0.0;
  3378. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3379. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3380. result.m[10] = (axis.z * axis.z) * c1 + c;
  3381. result.m[11] = 0.0;
  3382. result.m[15] = 1.0;
  3383. result._markAsUpdated();
  3384. };
  3385. /**
  3386. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3389. var result = new Matrix();
  3390. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3391. return result;
  3392. };
  3393. /**
  3394. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3395. */
  3396. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3397. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3398. this._tempQuaternion.toRotationMatrix(result);
  3399. };
  3400. /**
  3401. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.Scaling = function (x, y, z) {
  3404. var result = Matrix.Zero();
  3405. Matrix.ScalingToRef(x, y, z, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3410. */
  3411. Matrix.ScalingToRef = function (x, y, z, result) {
  3412. result.m[0] = x;
  3413. result.m[1] = 0.0;
  3414. result.m[2] = 0.0;
  3415. result.m[3] = 0.0;
  3416. result.m[4] = 0.0;
  3417. result.m[5] = y;
  3418. result.m[6] = 0.0;
  3419. result.m[7] = 0.0;
  3420. result.m[8] = 0.0;
  3421. result.m[9] = 0.0;
  3422. result.m[10] = z;
  3423. result.m[11] = 0.0;
  3424. result.m[12] = 0.0;
  3425. result.m[13] = 0.0;
  3426. result.m[14] = 0.0;
  3427. result.m[15] = 1.0;
  3428. result._markAsUpdated();
  3429. };
  3430. /**
  3431. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.Translation = function (x, y, z) {
  3434. var result = Matrix.Identity();
  3435. Matrix.TranslationToRef(x, y, z, result);
  3436. return result;
  3437. };
  3438. /**
  3439. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3440. */
  3441. Matrix.TranslationToRef = function (x, y, z, result) {
  3442. 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);
  3443. };
  3444. /**
  3445. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3446. */
  3447. Matrix.Lerp = function (startValue, endValue, gradient) {
  3448. var result = Matrix.Zero();
  3449. for (var index = 0; index < 16; index++) {
  3450. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3451. }
  3452. result._markAsUpdated();
  3453. return result;
  3454. };
  3455. /**
  3456. * Returns a new Matrix whose values are computed by :
  3457. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3458. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3459. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3460. */
  3461. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3462. var startScale = new Vector3(0, 0, 0);
  3463. var startRotation = new Quaternion();
  3464. var startTranslation = new Vector3(0, 0, 0);
  3465. startValue.decompose(startScale, startRotation, startTranslation);
  3466. var endScale = new Vector3(0, 0, 0);
  3467. var endRotation = new Quaternion();
  3468. var endTranslation = new Vector3(0, 0, 0);
  3469. endValue.decompose(endScale, endRotation, endTranslation);
  3470. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3471. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3472. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3473. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3474. };
  3475. /**
  3476. * 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".
  3477. * This methods works for a Left-Handed system.
  3478. */
  3479. Matrix.LookAtLH = function (eye, target, up) {
  3480. var result = Matrix.Zero();
  3481. Matrix.LookAtLHToRef(eye, target, up, result);
  3482. return result;
  3483. };
  3484. /**
  3485. * 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".
  3486. * This methods works for a Left-Handed system.
  3487. */
  3488. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3489. // Z axis
  3490. target.subtractToRef(eye, this._zAxis);
  3491. this._zAxis.normalize();
  3492. // X axis
  3493. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3494. if (this._xAxis.lengthSquared() === 0) {
  3495. this._xAxis.x = 1.0;
  3496. }
  3497. else {
  3498. this._xAxis.normalize();
  3499. }
  3500. // Y axis
  3501. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3502. this._yAxis.normalize();
  3503. // Eye angles
  3504. var ex = -Vector3.Dot(this._xAxis, eye);
  3505. var ey = -Vector3.Dot(this._yAxis, eye);
  3506. var ez = -Vector3.Dot(this._zAxis, eye);
  3507. 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);
  3508. };
  3509. /**
  3510. * 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".
  3511. * This methods works for a Right-Handed system.
  3512. */
  3513. Matrix.LookAtRH = function (eye, target, up) {
  3514. var result = Matrix.Zero();
  3515. Matrix.LookAtRHToRef(eye, target, up, result);
  3516. return result;
  3517. };
  3518. /**
  3519. * 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".
  3520. * This methods works for a Left-Handed system.
  3521. */
  3522. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3523. // Z axis
  3524. eye.subtractToRef(target, this._zAxis);
  3525. this._zAxis.normalize();
  3526. // X axis
  3527. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3528. if (this._xAxis.lengthSquared() === 0) {
  3529. this._xAxis.x = 1.0;
  3530. }
  3531. else {
  3532. this._xAxis.normalize();
  3533. }
  3534. // Y axis
  3535. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3536. this._yAxis.normalize();
  3537. // Eye angles
  3538. var ex = -Vector3.Dot(this._xAxis, eye);
  3539. var ey = -Vector3.Dot(this._yAxis, eye);
  3540. var ez = -Vector3.Dot(this._zAxis, eye);
  3541. 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);
  3542. };
  3543. /**
  3544. * 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.
  3545. */
  3546. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3547. var matrix = Matrix.Zero();
  3548. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3549. return matrix;
  3550. };
  3551. /**
  3552. * 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.
  3553. */
  3554. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3555. var n = znear;
  3556. var f = zfar;
  3557. var a = 2.0 / width;
  3558. var b = 2.0 / height;
  3559. var c = 2.0 / (f - n);
  3560. var d = -(f + n) / (f - n);
  3561. 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);
  3562. };
  3563. /**
  3564. * 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.
  3565. */
  3566. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3567. var matrix = Matrix.Zero();
  3568. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3569. return matrix;
  3570. };
  3571. /**
  3572. * 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.
  3573. */
  3574. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3575. var n = znear;
  3576. var f = zfar;
  3577. var a = 2.0 / (right - left);
  3578. var b = 2.0 / (top - bottom);
  3579. var c = 2.0 / (f - n);
  3580. var d = -(f + n) / (f - n);
  3581. var i0 = (left + right) / (left - right);
  3582. var i1 = (top + bottom) / (bottom - top);
  3583. 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);
  3584. };
  3585. /**
  3586. * 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.
  3587. */
  3588. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3589. var matrix = Matrix.Zero();
  3590. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3591. return matrix;
  3592. };
  3593. /**
  3594. * 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.
  3595. */
  3596. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3597. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3598. result.m[10] *= -1.0;
  3599. };
  3600. /**
  3601. * 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.
  3602. */
  3603. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3604. var matrix = Matrix.Zero();
  3605. var n = znear;
  3606. var f = zfar;
  3607. var a = 2.0 * n / width;
  3608. var b = 2.0 * n / height;
  3609. var c = (f + n) / (f - n);
  3610. var d = -2.0 * f * n / (f - n);
  3611. 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);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * 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.
  3616. */
  3617. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3618. var matrix = Matrix.Zero();
  3619. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3620. return matrix;
  3621. };
  3622. /**
  3623. * 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.
  3624. */
  3625. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3626. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3627. var n = znear;
  3628. var f = zfar;
  3629. var t = 1.0 / (Math.tan(fov * 0.5));
  3630. var a = isVerticalFovFixed ? (t / aspect) : t;
  3631. var b = isVerticalFovFixed ? t : (t * aspect);
  3632. var c = (f + n) / (f - n);
  3633. var d = -2.0 * f * n / (f - n);
  3634. 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);
  3635. };
  3636. /**
  3637. * 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.
  3638. */
  3639. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3640. var matrix = Matrix.Zero();
  3641. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3642. return matrix;
  3643. };
  3644. /**
  3645. * 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.
  3646. */
  3647. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3648. //alternatively this could be expressed as:
  3649. // m = PerspectiveFovLHToRef
  3650. // m[10] *= -1.0;
  3651. // m[11] *= -1.0;
  3652. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3653. var n = znear;
  3654. var f = zfar;
  3655. var t = 1.0 / (Math.tan(fov * 0.5));
  3656. var a = isVerticalFovFixed ? (t / aspect) : t;
  3657. var b = isVerticalFovFixed ? t : (t * aspect);
  3658. var c = -(f + n) / (f - n);
  3659. var d = -2 * f * n / (f - n);
  3660. 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);
  3661. };
  3662. /**
  3663. * 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.
  3664. */
  3665. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3666. if (rightHanded === void 0) { rightHanded = false; }
  3667. var rightHandedFactor = rightHanded ? -1 : 1;
  3668. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3669. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3670. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3671. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3672. var xScale = 2.0 / (leftTan + rightTan);
  3673. var yScale = 2.0 / (upTan + downTan);
  3674. result.m[0] = xScale;
  3675. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3676. result.m[5] = yScale;
  3677. result.m[6] = result.m[7] = 0.0;
  3678. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3679. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3680. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3681. result.m[10] = -zfar / (znear - zfar);
  3682. result.m[11] = 1.0 * rightHandedFactor;
  3683. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3684. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3685. // result.m[14] = (znear * zfar) / (znear - zfar);
  3686. result._markAsUpdated();
  3687. };
  3688. /**
  3689. * Returns the final transformation matrix : world * view * projection * viewport
  3690. */
  3691. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3692. var cw = viewport.width;
  3693. var ch = viewport.height;
  3694. var cx = viewport.x;
  3695. var cy = viewport.y;
  3696. 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);
  3697. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3698. };
  3699. /**
  3700. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3701. */
  3702. Matrix.GetAsMatrix2x2 = function (matrix) {
  3703. return new Float32Array([
  3704. matrix.m[0], matrix.m[1],
  3705. matrix.m[4], matrix.m[5]
  3706. ]);
  3707. };
  3708. /**
  3709. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3710. */
  3711. Matrix.GetAsMatrix3x3 = function (matrix) {
  3712. return new Float32Array([
  3713. matrix.m[0], matrix.m[1], matrix.m[2],
  3714. matrix.m[4], matrix.m[5], matrix.m[6],
  3715. matrix.m[8], matrix.m[9], matrix.m[10]
  3716. ]);
  3717. };
  3718. /**
  3719. * Compute the transpose of the passed Matrix.
  3720. * Returns a new Matrix.
  3721. */
  3722. Matrix.Transpose = function (matrix) {
  3723. var result = new Matrix();
  3724. result.m[0] = matrix.m[0];
  3725. result.m[1] = matrix.m[4];
  3726. result.m[2] = matrix.m[8];
  3727. result.m[3] = matrix.m[12];
  3728. result.m[4] = matrix.m[1];
  3729. result.m[5] = matrix.m[5];
  3730. result.m[6] = matrix.m[9];
  3731. result.m[7] = matrix.m[13];
  3732. result.m[8] = matrix.m[2];
  3733. result.m[9] = matrix.m[6];
  3734. result.m[10] = matrix.m[10];
  3735. result.m[11] = matrix.m[14];
  3736. result.m[12] = matrix.m[3];
  3737. result.m[13] = matrix.m[7];
  3738. result.m[14] = matrix.m[11];
  3739. result.m[15] = matrix.m[15];
  3740. return result;
  3741. };
  3742. /**
  3743. * Returns a new Matrix as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.Reflection = function (plane) {
  3746. var matrix = new Matrix();
  3747. Matrix.ReflectionToRef(plane, matrix);
  3748. return matrix;
  3749. };
  3750. /**
  3751. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3752. */
  3753. Matrix.ReflectionToRef = function (plane, result) {
  3754. plane.normalize();
  3755. var x = plane.normal.x;
  3756. var y = plane.normal.y;
  3757. var z = plane.normal.z;
  3758. var temp = -2 * x;
  3759. var temp2 = -2 * y;
  3760. var temp3 = -2 * z;
  3761. result.m[0] = (temp * x) + 1;
  3762. result.m[1] = temp2 * x;
  3763. result.m[2] = temp3 * x;
  3764. result.m[3] = 0.0;
  3765. result.m[4] = temp * y;
  3766. result.m[5] = (temp2 * y) + 1;
  3767. result.m[6] = temp3 * y;
  3768. result.m[7] = 0.0;
  3769. result.m[8] = temp * z;
  3770. result.m[9] = temp2 * z;
  3771. result.m[10] = (temp3 * z) + 1;
  3772. result.m[11] = 0.0;
  3773. result.m[12] = temp * plane.d;
  3774. result.m[13] = temp2 * plane.d;
  3775. result.m[14] = temp3 * plane.d;
  3776. result.m[15] = 1.0;
  3777. result._markAsUpdated();
  3778. };
  3779. /**
  3780. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3781. */
  3782. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3783. result.m[0] = xaxis.x;
  3784. result.m[1] = xaxis.y;
  3785. result.m[2] = xaxis.z;
  3786. result.m[3] = 0.0;
  3787. result.m[4] = yaxis.x;
  3788. result.m[5] = yaxis.y;
  3789. result.m[6] = yaxis.z;
  3790. result.m[7] = 0.0;
  3791. result.m[8] = zaxis.x;
  3792. result.m[9] = zaxis.y;
  3793. result.m[10] = zaxis.z;
  3794. result.m[11] = 0.0;
  3795. result.m[12] = 0.0;
  3796. result.m[13] = 0.0;
  3797. result.m[14] = 0.0;
  3798. result.m[15] = 1.0;
  3799. result._markAsUpdated();
  3800. };
  3801. /**
  3802. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3803. */
  3804. Matrix.FromQuaternionToRef = function (quat, result) {
  3805. var xx = quat.x * quat.x;
  3806. var yy = quat.y * quat.y;
  3807. var zz = quat.z * quat.z;
  3808. var xy = quat.x * quat.y;
  3809. var zw = quat.z * quat.w;
  3810. var zx = quat.z * quat.x;
  3811. var yw = quat.y * quat.w;
  3812. var yz = quat.y * quat.z;
  3813. var xw = quat.x * quat.w;
  3814. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3815. result.m[1] = 2.0 * (xy + zw);
  3816. result.m[2] = 2.0 * (zx - yw);
  3817. result.m[3] = 0.0;
  3818. result.m[4] = 2.0 * (xy - zw);
  3819. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3820. result.m[6] = 2.0 * (yz + xw);
  3821. result.m[7] = 0.0;
  3822. result.m[8] = 2.0 * (zx + yw);
  3823. result.m[9] = 2.0 * (yz - xw);
  3824. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3825. result.m[11] = 0.0;
  3826. result.m[12] = 0.0;
  3827. result.m[13] = 0.0;
  3828. result.m[14] = 0.0;
  3829. result.m[15] = 1.0;
  3830. result._markAsUpdated();
  3831. };
  3832. Matrix._tempQuaternion = new Quaternion();
  3833. Matrix._xAxis = Vector3.Zero();
  3834. Matrix._yAxis = Vector3.Zero();
  3835. Matrix._zAxis = Vector3.Zero();
  3836. Matrix._updateFlagSeed = 0;
  3837. return Matrix;
  3838. }());
  3839. BABYLON.Matrix = Matrix;
  3840. var Plane = (function () {
  3841. /**
  3842. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3843. */
  3844. function Plane(a, b, c, d) {
  3845. this.normal = new Vector3(a, b, c);
  3846. this.d = d;
  3847. }
  3848. /**
  3849. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3850. */
  3851. Plane.prototype.asArray = function () {
  3852. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3853. };
  3854. // Methods
  3855. /**
  3856. * Returns a new plane copied from the current Plane.
  3857. */
  3858. Plane.prototype.clone = function () {
  3859. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3860. };
  3861. /**
  3862. * Returns the string "Plane".
  3863. */
  3864. Plane.prototype.getClassName = function () {
  3865. return "Plane";
  3866. };
  3867. /**
  3868. * Returns the Plane hash code.
  3869. */
  3870. Plane.prototype.getHashCode = function () {
  3871. var hash = this.normal.getHashCode();
  3872. hash = (hash * 397) ^ (this.d || 0);
  3873. return hash;
  3874. };
  3875. /**
  3876. * Normalize the current Plane in place.
  3877. * Returns the updated Plane.
  3878. */
  3879. Plane.prototype.normalize = function () {
  3880. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3881. var magnitude = 0.0;
  3882. if (norm !== 0) {
  3883. magnitude = 1.0 / norm;
  3884. }
  3885. this.normal.x *= magnitude;
  3886. this.normal.y *= magnitude;
  3887. this.normal.z *= magnitude;
  3888. this.d *= magnitude;
  3889. return this;
  3890. };
  3891. /**
  3892. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3893. */
  3894. Plane.prototype.transform = function (transformation) {
  3895. var transposedMatrix = Matrix.Transpose(transformation);
  3896. var x = this.normal.x;
  3897. var y = this.normal.y;
  3898. var z = this.normal.z;
  3899. var d = this.d;
  3900. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3901. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3902. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3903. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3904. return new Plane(normalX, normalY, normalZ, finalD);
  3905. };
  3906. /**
  3907. * Returns the dot product (float) of the point coordinates and the plane normal.
  3908. */
  3909. Plane.prototype.dotCoordinate = function (point) {
  3910. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3911. };
  3912. /**
  3913. * Updates the current Plane from the plane defined by the three passed points.
  3914. * Returns the updated Plane.
  3915. */
  3916. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3917. var x1 = point2.x - point1.x;
  3918. var y1 = point2.y - point1.y;
  3919. var z1 = point2.z - point1.z;
  3920. var x2 = point3.x - point1.x;
  3921. var y2 = point3.y - point1.y;
  3922. var z2 = point3.z - point1.z;
  3923. var yz = (y1 * z2) - (z1 * y2);
  3924. var xz = (z1 * x2) - (x1 * z2);
  3925. var xy = (x1 * y2) - (y1 * x2);
  3926. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3927. var invPyth;
  3928. if (pyth !== 0) {
  3929. invPyth = 1.0 / pyth;
  3930. }
  3931. else {
  3932. invPyth = 0.0;
  3933. }
  3934. this.normal.x = yz * invPyth;
  3935. this.normal.y = xz * invPyth;
  3936. this.normal.z = xy * invPyth;
  3937. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3938. return this;
  3939. };
  3940. /**
  3941. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3942. */
  3943. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3944. var dot = Vector3.Dot(this.normal, direction);
  3945. return (dot <= epsilon);
  3946. };
  3947. /**
  3948. * Returns the signed distance (float) from the passed point to the Plane.
  3949. */
  3950. Plane.prototype.signedDistanceTo = function (point) {
  3951. return Vector3.Dot(point, this.normal) + this.d;
  3952. };
  3953. // Statics
  3954. /**
  3955. * Returns a new Plane from the passed array.
  3956. */
  3957. Plane.FromArray = function (array) {
  3958. return new Plane(array[0], array[1], array[2], array[3]);
  3959. };
  3960. /**
  3961. * Returns a new Plane defined by the three passed points.
  3962. */
  3963. Plane.FromPoints = function (point1, point2, point3) {
  3964. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3965. result.copyFromPoints(point1, point2, point3);
  3966. return result;
  3967. };
  3968. /**
  3969. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3970. * Note : the vector "normal" is updated because normalized.
  3971. */
  3972. Plane.FromPositionAndNormal = function (origin, normal) {
  3973. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3974. normal.normalize();
  3975. result.normal = normal;
  3976. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3977. return result;
  3978. };
  3979. /**
  3980. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3981. */
  3982. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3983. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3984. return Vector3.Dot(point, normal) + d;
  3985. };
  3986. return Plane;
  3987. }());
  3988. BABYLON.Plane = Plane;
  3989. var Viewport = (function () {
  3990. /**
  3991. * Creates a Viewport object located at (x, y) and sized (width, height).
  3992. */
  3993. function Viewport(x, y, width, height) {
  3994. this.x = x;
  3995. this.y = y;
  3996. this.width = width;
  3997. this.height = height;
  3998. }
  3999. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4000. if (renderWidthOrEngine._gl) {
  4001. var engine = renderWidthOrEngine;
  4002. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4003. }
  4004. var renderWidth = renderWidthOrEngine;
  4005. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4006. };
  4007. /**
  4008. * Returns a new Viewport copied from the current one.
  4009. */
  4010. Viewport.prototype.clone = function () {
  4011. return new Viewport(this.x, this.y, this.width, this.height);
  4012. };
  4013. return Viewport;
  4014. }());
  4015. BABYLON.Viewport = Viewport;
  4016. var Frustum = (function () {
  4017. function Frustum() {
  4018. }
  4019. /**
  4020. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4021. */
  4022. Frustum.GetPlanes = function (transform) {
  4023. var frustumPlanes = [];
  4024. for (var index = 0; index < 6; index++) {
  4025. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4026. }
  4027. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4028. return frustumPlanes;
  4029. };
  4030. /**
  4031. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4032. */
  4033. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4034. // Near
  4035. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4036. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4037. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4038. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4039. frustumPlanes[0].normalize();
  4040. // Far
  4041. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4042. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4043. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4044. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4045. frustumPlanes[1].normalize();
  4046. // Left
  4047. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4048. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4049. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4050. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4051. frustumPlanes[2].normalize();
  4052. // Right
  4053. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4054. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4055. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4056. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4057. frustumPlanes[3].normalize();
  4058. // Top
  4059. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4060. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4061. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4062. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4063. frustumPlanes[4].normalize();
  4064. // Bottom
  4065. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4066. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4067. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4068. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4069. frustumPlanes[5].normalize();
  4070. };
  4071. return Frustum;
  4072. }());
  4073. BABYLON.Frustum = Frustum;
  4074. var Space;
  4075. (function (Space) {
  4076. Space[Space["LOCAL"] = 0] = "LOCAL";
  4077. Space[Space["WORLD"] = 1] = "WORLD";
  4078. Space[Space["BONE"] = 2] = "BONE";
  4079. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4080. var Axis = (function () {
  4081. function Axis() {
  4082. }
  4083. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4084. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4085. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4086. return Axis;
  4087. }());
  4088. BABYLON.Axis = Axis;
  4089. ;
  4090. var BezierCurve = (function () {
  4091. function BezierCurve() {
  4092. }
  4093. /**
  4094. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4095. */
  4096. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4097. // Extract X (which is equal to time here)
  4098. var f0 = 1 - 3 * x2 + 3 * x1;
  4099. var f1 = 3 * x2 - 6 * x1;
  4100. var f2 = 3 * x1;
  4101. var refinedT = t;
  4102. for (var i = 0; i < 5; i++) {
  4103. var refinedT2 = refinedT * refinedT;
  4104. var refinedT3 = refinedT2 * refinedT;
  4105. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4106. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4107. refinedT -= (x - t) * slope;
  4108. refinedT = Math.min(1, Math.max(0, refinedT));
  4109. }
  4110. // Resolve cubic bezier for the given x
  4111. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4112. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4113. Math.pow(refinedT, 3);
  4114. };
  4115. return BezierCurve;
  4116. }());
  4117. BABYLON.BezierCurve = BezierCurve;
  4118. var Orientation;
  4119. (function (Orientation) {
  4120. Orientation[Orientation["CW"] = 0] = "CW";
  4121. Orientation[Orientation["CCW"] = 1] = "CCW";
  4122. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4123. var Angle = (function () {
  4124. /**
  4125. * Creates an Angle object of "radians" radians (float).
  4126. */
  4127. function Angle(radians) {
  4128. var _this = this;
  4129. /**
  4130. * Returns the Angle value in degrees (float).
  4131. */
  4132. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4133. /**
  4134. * Returns the Angle value in radians (float).
  4135. */
  4136. this.radians = function () { return _this._radians; };
  4137. this._radians = radians;
  4138. if (this._radians < 0.0)
  4139. this._radians += (2.0 * Math.PI);
  4140. }
  4141. /**
  4142. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4143. */
  4144. Angle.BetweenTwoPoints = function (a, b) {
  4145. var delta = b.subtract(a);
  4146. var theta = Math.atan2(delta.y, delta.x);
  4147. return new Angle(theta);
  4148. };
  4149. /**
  4150. * Returns a new Angle object from the passed float in radians.
  4151. */
  4152. Angle.FromRadians = function (radians) {
  4153. return new Angle(radians);
  4154. };
  4155. /**
  4156. * Returns a new Angle object from the passed float in degrees.
  4157. */
  4158. Angle.FromDegrees = function (degrees) {
  4159. return new Angle(degrees * Math.PI / 180.0);
  4160. };
  4161. return Angle;
  4162. }());
  4163. BABYLON.Angle = Angle;
  4164. var Arc2 = (function () {
  4165. /**
  4166. * Creates an Arc object from the three passed points : start, middle and end.
  4167. */
  4168. function Arc2(startPoint, midPoint, endPoint) {
  4169. this.startPoint = startPoint;
  4170. this.midPoint = midPoint;
  4171. this.endPoint = endPoint;
  4172. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4173. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4174. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4175. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4176. 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);
  4177. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4178. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4179. var a1 = this.startAngle.degrees();
  4180. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4181. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4182. // angles correction
  4183. if (a2 - a1 > +180.0)
  4184. a2 -= 360.0;
  4185. if (a2 - a1 < -180.0)
  4186. a2 += 360.0;
  4187. if (a3 - a2 > +180.0)
  4188. a3 -= 360.0;
  4189. if (a3 - a2 < -180.0)
  4190. a3 += 360.0;
  4191. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4192. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4193. }
  4194. return Arc2;
  4195. }());
  4196. BABYLON.Arc2 = Arc2;
  4197. var Path2 = (function () {
  4198. /**
  4199. * Creates a Path2 object from the starting 2D coordinates x and y.
  4200. */
  4201. function Path2(x, y) {
  4202. this._points = new Array();
  4203. this._length = 0.0;
  4204. this.closed = false;
  4205. this._points.push(new Vector2(x, y));
  4206. }
  4207. /**
  4208. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4209. * Returns the updated Path2.
  4210. */
  4211. Path2.prototype.addLineTo = function (x, y) {
  4212. if (closed) {
  4213. //Tools.Error("cannot add lines to closed paths");
  4214. return this;
  4215. }
  4216. var newPoint = new Vector2(x, y);
  4217. var previousPoint = this._points[this._points.length - 1];
  4218. this._points.push(newPoint);
  4219. this._length += newPoint.subtract(previousPoint).length();
  4220. return this;
  4221. };
  4222. /**
  4223. * 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.
  4224. * Returns the updated Path2.
  4225. */
  4226. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4227. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4228. if (closed) {
  4229. //Tools.Error("cannot add arcs to closed paths");
  4230. return this;
  4231. }
  4232. var startPoint = this._points[this._points.length - 1];
  4233. var midPoint = new Vector2(midX, midY);
  4234. var endPoint = new Vector2(endX, endY);
  4235. var arc = new Arc2(startPoint, midPoint, endPoint);
  4236. var increment = arc.angle.radians() / numberOfSegments;
  4237. if (arc.orientation === Orientation.CW)
  4238. increment *= -1;
  4239. var currentAngle = arc.startAngle.radians() + increment;
  4240. for (var i = 0; i < numberOfSegments; i++) {
  4241. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4242. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4243. this.addLineTo(x, y);
  4244. currentAngle += increment;
  4245. }
  4246. return this;
  4247. };
  4248. /**
  4249. * Closes the Path2.
  4250. * Returns the Path2.
  4251. */
  4252. Path2.prototype.close = function () {
  4253. this.closed = true;
  4254. return this;
  4255. };
  4256. /**
  4257. * Returns the Path2 total length (float).
  4258. */
  4259. Path2.prototype.length = function () {
  4260. var result = this._length;
  4261. if (!this.closed) {
  4262. var lastPoint = this._points[this._points.length - 1];
  4263. var firstPoint = this._points[0];
  4264. result += (firstPoint.subtract(lastPoint).length());
  4265. }
  4266. return result;
  4267. };
  4268. /**
  4269. * Returns the Path2 internal array of points.
  4270. */
  4271. Path2.prototype.getPoints = function () {
  4272. return this._points;
  4273. };
  4274. /**
  4275. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4276. */
  4277. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4278. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4279. //Tools.Error("normalized length position should be between 0 and 1.");
  4280. return Vector2.Zero();
  4281. }
  4282. var lengthPosition = normalizedLengthPosition * this.length();
  4283. var previousOffset = 0;
  4284. for (var i = 0; i < this._points.length; i++) {
  4285. var j = (i + 1) % this._points.length;
  4286. var a = this._points[i];
  4287. var b = this._points[j];
  4288. var bToA = b.subtract(a);
  4289. var nextOffset = (bToA.length() + previousOffset);
  4290. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4291. var dir = bToA.normalize();
  4292. var localOffset = lengthPosition - previousOffset;
  4293. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4294. }
  4295. previousOffset = nextOffset;
  4296. }
  4297. //Tools.Error("internal error");
  4298. return Vector2.Zero();
  4299. };
  4300. /**
  4301. * Returns a new Path2 starting at the coordinates (x, y).
  4302. */
  4303. Path2.StartingAt = function (x, y) {
  4304. return new Path2(x, y);
  4305. };
  4306. return Path2;
  4307. }());
  4308. BABYLON.Path2 = Path2;
  4309. var Path3D = (function () {
  4310. /**
  4311. * new Path3D(path, normal, raw)
  4312. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4313. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4314. * path : an array of Vector3, the curve axis of the Path3D
  4315. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4316. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4317. */
  4318. function Path3D(path, firstNormal, raw) {
  4319. this.path = path;
  4320. this._curve = new Array();
  4321. this._distances = new Array();
  4322. this._tangents = new Array();
  4323. this._normals = new Array();
  4324. this._binormals = new Array();
  4325. for (var p = 0; p < path.length; p++) {
  4326. this._curve[p] = path[p].clone(); // hard copy
  4327. }
  4328. this._raw = raw || false;
  4329. this._compute(firstNormal);
  4330. }
  4331. /**
  4332. * Returns the Path3D array of successive Vector3 designing its curve.
  4333. */
  4334. Path3D.prototype.getCurve = function () {
  4335. return this._curve;
  4336. };
  4337. /**
  4338. * Returns an array populated with tangent vectors on each Path3D curve point.
  4339. */
  4340. Path3D.prototype.getTangents = function () {
  4341. return this._tangents;
  4342. };
  4343. /**
  4344. * Returns an array populated with normal vectors on each Path3D curve point.
  4345. */
  4346. Path3D.prototype.getNormals = function () {
  4347. return this._normals;
  4348. };
  4349. /**
  4350. * Returns an array populated with binormal vectors on each Path3D curve point.
  4351. */
  4352. Path3D.prototype.getBinormals = function () {
  4353. return this._binormals;
  4354. };
  4355. /**
  4356. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4357. */
  4358. Path3D.prototype.getDistances = function () {
  4359. return this._distances;
  4360. };
  4361. /**
  4362. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4363. * Returns the same object updated.
  4364. */
  4365. Path3D.prototype.update = function (path, firstNormal) {
  4366. for (var p = 0; p < path.length; p++) {
  4367. this._curve[p].x = path[p].x;
  4368. this._curve[p].y = path[p].y;
  4369. this._curve[p].z = path[p].z;
  4370. }
  4371. this._compute(firstNormal);
  4372. return this;
  4373. };
  4374. // private function compute() : computes tangents, normals and binormals
  4375. Path3D.prototype._compute = function (firstNormal) {
  4376. var l = this._curve.length;
  4377. // first and last tangents
  4378. this._tangents[0] = this._getFirstNonNullVector(0);
  4379. if (!this._raw) {
  4380. this._tangents[0].normalize();
  4381. }
  4382. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4383. if (!this._raw) {
  4384. this._tangents[l - 1].normalize();
  4385. }
  4386. // normals and binormals at first point : arbitrary vector with _normalVector()
  4387. var tg0 = this._tangents[0];
  4388. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4389. this._normals[0] = pp0;
  4390. if (!this._raw) {
  4391. this._normals[0].normalize();
  4392. }
  4393. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4394. if (!this._raw) {
  4395. this._binormals[0].normalize();
  4396. }
  4397. this._distances[0] = 0.0;
  4398. // normals and binormals : next points
  4399. var prev; // previous vector (segment)
  4400. var cur; // current vector (segment)
  4401. var curTang; // current tangent
  4402. // previous normal
  4403. var prevBinor; // previous binormal
  4404. for (var i = 1; i < l; i++) {
  4405. // tangents
  4406. prev = this._getLastNonNullVector(i);
  4407. if (i < l - 1) {
  4408. cur = this._getFirstNonNullVector(i);
  4409. this._tangents[i] = prev.add(cur);
  4410. this._tangents[i].normalize();
  4411. }
  4412. this._distances[i] = this._distances[i - 1] + prev.length();
  4413. // normals and binormals
  4414. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4415. curTang = this._tangents[i];
  4416. prevBinor = this._binormals[i - 1];
  4417. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4418. if (!this._raw) {
  4419. this._normals[i].normalize();
  4420. }
  4421. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4422. if (!this._raw) {
  4423. this._binormals[i].normalize();
  4424. }
  4425. }
  4426. };
  4427. // private function getFirstNonNullVector(index)
  4428. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4429. Path3D.prototype._getFirstNonNullVector = function (index) {
  4430. var i = 1;
  4431. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4432. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4433. i++;
  4434. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4435. }
  4436. return nNVector;
  4437. };
  4438. // private function getLastNonNullVector(index)
  4439. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4440. Path3D.prototype._getLastNonNullVector = function (index) {
  4441. var i = 1;
  4442. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4443. while (nLVector.length() === 0 && index > i + 1) {
  4444. i++;
  4445. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4446. }
  4447. return nLVector;
  4448. };
  4449. // private function normalVector(v0, vt, va) :
  4450. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4451. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4452. Path3D.prototype._normalVector = function (v0, vt, va) {
  4453. var normal0;
  4454. var tgl = vt.length();
  4455. if (tgl === 0.0) {
  4456. tgl = 1.0;
  4457. }
  4458. if (va === undefined || va === null) {
  4459. var point;
  4460. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4461. point = new Vector3(0.0, -1.0, 0.0);
  4462. }
  4463. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4464. point = new Vector3(1.0, 0.0, 0.0);
  4465. }
  4466. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4467. point = new Vector3(0.0, 0.0, 1.0);
  4468. }
  4469. normal0 = Vector3.Cross(vt, point);
  4470. }
  4471. else {
  4472. normal0 = Vector3.Cross(vt, va);
  4473. Vector3.CrossToRef(normal0, vt, normal0);
  4474. }
  4475. normal0.normalize();
  4476. return normal0;
  4477. };
  4478. return Path3D;
  4479. }());
  4480. BABYLON.Path3D = Path3D;
  4481. var Curve3 = (function () {
  4482. /**
  4483. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4484. * A Curve3 is designed from a series of successive Vector3.
  4485. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4486. */
  4487. function Curve3(points) {
  4488. this._length = 0.0;
  4489. this._points = points;
  4490. this._length = this._computeLength(points);
  4491. }
  4492. /**
  4493. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4494. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4495. * @param v1 (Vector3) the control point
  4496. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4497. * @param nbPoints (integer) the wanted number of points in the curve
  4498. */
  4499. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4500. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4501. var bez = new Array();
  4502. var equation = function (t, val0, val1, val2) {
  4503. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4504. return res;
  4505. };
  4506. for (var i = 0; i <= nbPoints; i++) {
  4507. 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)));
  4508. }
  4509. return new Curve3(bez);
  4510. };
  4511. /**
  4512. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4513. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4514. * @param v1 (Vector3) the first control point
  4515. * @param v2 (Vector3) the second control point
  4516. * @param v3 (Vector3) the end point of the Cubic Bezier
  4517. * @param nbPoints (integer) the wanted number of points in the curve
  4518. */
  4519. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4520. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4521. var bez = new Array();
  4522. var equation = function (t, val0, val1, val2, val3) {
  4523. 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;
  4524. return res;
  4525. };
  4526. for (var i = 0; i <= nbPoints; i++) {
  4527. 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)));
  4528. }
  4529. return new Curve3(bez);
  4530. };
  4531. /**
  4532. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4533. * @param p1 (Vector3) the origin point of the Hermite Spline
  4534. * @param t1 (Vector3) the tangent vector at the origin point
  4535. * @param p2 (Vector3) the end point of the Hermite Spline
  4536. * @param t2 (Vector3) the tangent vector at the end point
  4537. * @param nbPoints (integer) the wanted number of points in the curve
  4538. */
  4539. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4540. var hermite = new Array();
  4541. var step = 1.0 / nbPoints;
  4542. for (var i = 0; i <= nbPoints; i++) {
  4543. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4544. }
  4545. return new Curve3(hermite);
  4546. };
  4547. /**
  4548. * Returns a Curve3 object along a CatmullRom Spline curve :
  4549. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4550. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4551. */
  4552. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4553. var totalPoints = new Array();
  4554. totalPoints.push(points[0].clone());
  4555. Array.prototype.push.apply(totalPoints, points);
  4556. totalPoints.push(points[points.length - 1].clone());
  4557. var catmullRom = new Array();
  4558. var step = 1.0 / nbPoints;
  4559. for (var i = 0; i < totalPoints.length - 3; i++) {
  4560. var amount = 0.0;
  4561. for (var c = 0; c < nbPoints; c++) {
  4562. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4563. amount += step;
  4564. }
  4565. }
  4566. i--;
  4567. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4568. return new Curve3(catmullRom);
  4569. };
  4570. /**
  4571. * Returns the Curve3 stored array of successive Vector3
  4572. */
  4573. Curve3.prototype.getPoints = function () {
  4574. return this._points;
  4575. };
  4576. /**
  4577. * Returns the computed length (float) of the curve.
  4578. */
  4579. Curve3.prototype.length = function () {
  4580. return this._length;
  4581. };
  4582. /**
  4583. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4584. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4585. * curveA and curveB keep unchanged.
  4586. */
  4587. Curve3.prototype.continue = function (curve) {
  4588. var lastPoint = this._points[this._points.length - 1];
  4589. var continuedPoints = this._points.slice();
  4590. var curvePoints = curve.getPoints();
  4591. for (var i = 1; i < curvePoints.length; i++) {
  4592. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4593. }
  4594. var continuedCurve = new Curve3(continuedPoints);
  4595. return continuedCurve;
  4596. };
  4597. Curve3.prototype._computeLength = function (path) {
  4598. var l = 0;
  4599. for (var i = 1; i < path.length; i++) {
  4600. l += (path[i].subtract(path[i - 1])).length();
  4601. }
  4602. return l;
  4603. };
  4604. return Curve3;
  4605. }());
  4606. BABYLON.Curve3 = Curve3;
  4607. // Vertex formats
  4608. var PositionNormalVertex = (function () {
  4609. function PositionNormalVertex(position, normal) {
  4610. if (position === void 0) { position = Vector3.Zero(); }
  4611. if (normal === void 0) { normal = Vector3.Up(); }
  4612. this.position = position;
  4613. this.normal = normal;
  4614. }
  4615. PositionNormalVertex.prototype.clone = function () {
  4616. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4617. };
  4618. return PositionNormalVertex;
  4619. }());
  4620. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4621. var PositionNormalTextureVertex = (function () {
  4622. function PositionNormalTextureVertex(position, normal, uv) {
  4623. if (position === void 0) { position = Vector3.Zero(); }
  4624. if (normal === void 0) { normal = Vector3.Up(); }
  4625. if (uv === void 0) { uv = Vector2.Zero(); }
  4626. this.position = position;
  4627. this.normal = normal;
  4628. this.uv = uv;
  4629. }
  4630. PositionNormalTextureVertex.prototype.clone = function () {
  4631. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4632. };
  4633. return PositionNormalTextureVertex;
  4634. }());
  4635. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4636. // Temporary pre-allocated objects for engine internal use
  4637. // usage in any internal function :
  4638. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4639. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4640. var Tmp = (function () {
  4641. function Tmp() {
  4642. }
  4643. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4644. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4645. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4646. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4647. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4648. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4649. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4650. Matrix.Zero(), Matrix.Zero(),
  4651. Matrix.Zero(), Matrix.Zero(),
  4652. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4653. return Tmp;
  4654. }());
  4655. BABYLON.Tmp = Tmp;
  4656. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4657. var MathTmp = (function () {
  4658. function MathTmp() {
  4659. }
  4660. MathTmp.Vector3 = [Vector3.Zero()];
  4661. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4662. MathTmp.Quaternion = [Quaternion.Zero()];
  4663. return MathTmp;
  4664. }());
  4665. })(BABYLON || (BABYLON = {}));
  4666. //# sourceMappingURL=babylon.math.js.map
  4667. var BABYLON;
  4668. (function (BABYLON) {
  4669. var Scalar = (function () {
  4670. function Scalar() {
  4671. }
  4672. /**
  4673. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4674. */
  4675. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4676. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4677. var num = a - b;
  4678. return -epsilon <= num && num <= epsilon;
  4679. };
  4680. /**
  4681. * Returns a string : the upper case translation of the number i to hexadecimal.
  4682. */
  4683. Scalar.ToHex = function (i) {
  4684. var str = i.toString(16);
  4685. if (i <= 15) {
  4686. return ("0" + str).toUpperCase();
  4687. }
  4688. return str.toUpperCase();
  4689. };
  4690. /**
  4691. * Returns -1 if value is negative and +1 is value is positive.
  4692. * Returns the value itself if it's equal to zero.
  4693. */
  4694. Scalar.Sign = function (value) {
  4695. value = +value; // convert to a number
  4696. if (value === 0 || isNaN(value))
  4697. return value;
  4698. return value > 0 ? 1 : -1;
  4699. };
  4700. /**
  4701. * Returns the value itself if it's between min and max.
  4702. * Returns min if the value is lower than min.
  4703. * Returns max if the value is greater than max.
  4704. */
  4705. Scalar.Clamp = function (value, min, max) {
  4706. if (min === void 0) { min = 0; }
  4707. if (max === void 0) { max = 1; }
  4708. return Math.min(max, Math.max(min, value));
  4709. };
  4710. /**
  4711. * Returns the log2 of value.
  4712. */
  4713. Scalar.Log2 = function (value) {
  4714. return Math.log(value) * Math.LOG2E;
  4715. };
  4716. /**
  4717. * Loops the value, so that it is never larger than length and never smaller than 0.
  4718. *
  4719. * This is similar to the modulo operator but it works with floating point numbers.
  4720. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4721. * With t = 5 and length = 2.5, the result would be 0.0.
  4722. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4723. */
  4724. Scalar.Repeat = function (value, length) {
  4725. return value - Math.floor(value / length) * length;
  4726. };
  4727. /**
  4728. * Normalize the value between 0.0 and 1.0 using min and max values
  4729. */
  4730. Scalar.Normalize = function (value, min, max) {
  4731. return (value - min) / (max - min);
  4732. };
  4733. /**
  4734. * Denormalize the value from 0.0 and 1.0 using min and max values
  4735. */
  4736. Scalar.Denormalize = function (normalized, min, max) {
  4737. return (normalized * (max - min) + min);
  4738. };
  4739. /**
  4740. * Calculates the shortest difference between two given angles given in degrees.
  4741. */
  4742. Scalar.DeltaAngle = function (current, target) {
  4743. var num = Scalar.Repeat(target - current, 360.0);
  4744. if (num > 180.0) {
  4745. num -= 360.0;
  4746. }
  4747. return num;
  4748. };
  4749. /**
  4750. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4751. *
  4752. * The returned value will move back and forth between 0 and length
  4753. */
  4754. Scalar.PingPong = function (tx, length) {
  4755. var t = Scalar.Repeat(tx, length * 2.0);
  4756. return length - Math.abs(t - length);
  4757. };
  4758. /**
  4759. * Interpolates between min and max with smoothing at the limits.
  4760. *
  4761. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4762. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4763. */
  4764. Scalar.SmoothStep = function (from, to, tx) {
  4765. var t = Scalar.Clamp(tx);
  4766. t = -2.0 * t * t * t + 3.0 * t * t;
  4767. return to * t + from * (1.0 - t);
  4768. };
  4769. /**
  4770. * Moves a value current towards target.
  4771. *
  4772. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4773. * Negative values of maxDelta pushes the value away from target.
  4774. */
  4775. Scalar.MoveTowards = function (current, target, maxDelta) {
  4776. var result = 0;
  4777. if (Math.abs(target - current) <= maxDelta) {
  4778. result = target;
  4779. }
  4780. else {
  4781. result = current + Scalar.Sign(target - current) * maxDelta;
  4782. }
  4783. return result;
  4784. };
  4785. /**
  4786. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4787. *
  4788. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4789. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4790. */
  4791. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4792. var num = Scalar.DeltaAngle(current, target);
  4793. var result = 0;
  4794. if (-maxDelta < num && num < maxDelta) {
  4795. result = target;
  4796. }
  4797. else {
  4798. target = current + num;
  4799. result = Scalar.MoveTowards(current, target, maxDelta);
  4800. }
  4801. return result;
  4802. };
  4803. /**
  4804. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4805. */
  4806. Scalar.Lerp = function (start, end, amount) {
  4807. return start + ((end - start) * amount);
  4808. };
  4809. /**
  4810. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4811. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4812. */
  4813. Scalar.LerpAngle = function (start, end, amount) {
  4814. var num = Scalar.Repeat(end - start, 360.0);
  4815. if (num > 180.0) {
  4816. num -= 360.0;
  4817. }
  4818. return start + num * Scalar.Clamp(amount);
  4819. };
  4820. /**
  4821. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4822. */
  4823. Scalar.InverseLerp = function (a, b, value) {
  4824. var result = 0;
  4825. if (a != b) {
  4826. result = Scalar.Clamp((value - a) / (b - a));
  4827. }
  4828. else {
  4829. result = 0.0;
  4830. }
  4831. return result;
  4832. };
  4833. /**
  4834. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4835. */
  4836. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4837. var squared = amount * amount;
  4838. var cubed = amount * squared;
  4839. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4840. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4841. var part3 = (cubed - (2.0 * squared)) + amount;
  4842. var part4 = cubed - squared;
  4843. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4844. };
  4845. /**
  4846. * Returns a random float number between and min and max values
  4847. */
  4848. Scalar.RandomRange = function (min, max) {
  4849. if (min === max)
  4850. return min;
  4851. return ((Math.random() * (max - min)) + min);
  4852. };
  4853. /**
  4854. * This function returns percentage of a number in a given range.
  4855. *
  4856. * RangeToPercent(40,20,60) will return 0.5 (50%)
  4857. * RangeToPercent(34,0,100) will return 0.34 (34%)
  4858. */
  4859. Scalar.RangeToPercent = function (number, min, max) {
  4860. return ((number - min) / (max - min));
  4861. };
  4862. /**
  4863. * This function returns number that corresponds to the percentage in a given range.
  4864. *
  4865. * PercentToRange(0.34,0,100) will return 34.
  4866. */
  4867. Scalar.PercentToRange = function (percent, min, max) {
  4868. return ((max - min) * percent + min);
  4869. };
  4870. return Scalar;
  4871. }());
  4872. BABYLON.Scalar = Scalar;
  4873. })(BABYLON || (BABYLON = {}));
  4874. //# sourceMappingURL=babylon.math.scalar.js.map
  4875. //# sourceMappingURL=babylon.mixins.js.map
  4876. var BABYLON;
  4877. (function (BABYLON) {
  4878. var __decoratorInitialStore = {};
  4879. var __mergedStore = {};
  4880. var _copySource = function (creationFunction, source, instanciate) {
  4881. var destination = creationFunction();
  4882. // Tags
  4883. if (BABYLON.Tags) {
  4884. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4885. }
  4886. var classStore = getMergedStore(destination);
  4887. // Properties
  4888. for (var property in classStore) {
  4889. var propertyDescriptor = classStore[property];
  4890. var sourceProperty = source[property];
  4891. var propertyType = propertyDescriptor.type;
  4892. if (sourceProperty !== undefined && sourceProperty !== null) {
  4893. switch (propertyType) {
  4894. case 0: // Value
  4895. case 6:// Mesh reference
  4896. destination[property] = sourceProperty;
  4897. break;
  4898. case 1: // Texture
  4899. case 2: // Color3
  4900. case 3: // FresnelParameters
  4901. case 4: // Vector2
  4902. case 5: // Vector3
  4903. case 7:// Color Curves
  4904. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  4905. break;
  4906. }
  4907. }
  4908. }
  4909. return destination;
  4910. };
  4911. function getDirectStore(target) {
  4912. var classKey = target.getClassName();
  4913. if (!__decoratorInitialStore[classKey]) {
  4914. __decoratorInitialStore[classKey] = {};
  4915. }
  4916. return __decoratorInitialStore[classKey];
  4917. }
  4918. /**
  4919. * Return the list of properties flagged as serializable
  4920. * @param target: host object
  4921. */
  4922. function getMergedStore(target) {
  4923. var classKey = target.getClassName();
  4924. if (__mergedStore[classKey]) {
  4925. return __mergedStore[classKey];
  4926. }
  4927. __mergedStore[classKey] = {};
  4928. var store = __mergedStore[classKey];
  4929. var currentTarget = target;
  4930. var currentKey = classKey;
  4931. while (currentKey) {
  4932. var initialStore = __decoratorInitialStore[currentKey];
  4933. for (var property in initialStore) {
  4934. store[property] = initialStore[property];
  4935. }
  4936. var parent_1 = void 0;
  4937. var done = false;
  4938. do {
  4939. parent_1 = Object.getPrototypeOf(currentTarget);
  4940. if (!parent_1.getClassName) {
  4941. done = true;
  4942. break;
  4943. }
  4944. if (parent_1.getClassName() !== currentKey) {
  4945. break;
  4946. }
  4947. currentTarget = parent_1;
  4948. } while (parent_1);
  4949. if (done) {
  4950. break;
  4951. }
  4952. currentKey = parent_1.getClassName();
  4953. currentTarget = parent_1;
  4954. }
  4955. return store;
  4956. }
  4957. function generateSerializableMember(type, sourceName) {
  4958. return function (target, propertyKey) {
  4959. var classStore = getDirectStore(target);
  4960. if (!classStore[propertyKey]) {
  4961. classStore[propertyKey] = { type: type, sourceName: sourceName };
  4962. }
  4963. };
  4964. }
  4965. function generateExpandMember(setCallback, targetKey) {
  4966. return function (target, propertyKey) {
  4967. var key = targetKey || ("_" + propertyKey);
  4968. Object.defineProperty(target, propertyKey, {
  4969. get: function () {
  4970. return this[key];
  4971. },
  4972. set: function (value) {
  4973. if (this[key] === value) {
  4974. return;
  4975. }
  4976. this[key] = value;
  4977. target[setCallback].apply(this);
  4978. },
  4979. enumerable: true,
  4980. configurable: true
  4981. });
  4982. };
  4983. }
  4984. function expandToProperty(callback, targetKey) {
  4985. return generateExpandMember(callback, targetKey);
  4986. }
  4987. BABYLON.expandToProperty = expandToProperty;
  4988. function serialize(sourceName) {
  4989. return generateSerializableMember(0, sourceName); // value member
  4990. }
  4991. BABYLON.serialize = serialize;
  4992. function serializeAsTexture(sourceName) {
  4993. return generateSerializableMember(1, sourceName); // texture member
  4994. }
  4995. BABYLON.serializeAsTexture = serializeAsTexture;
  4996. function serializeAsColor3(sourceName) {
  4997. return generateSerializableMember(2, sourceName); // color3 member
  4998. }
  4999. BABYLON.serializeAsColor3 = serializeAsColor3;
  5000. function serializeAsFresnelParameters(sourceName) {
  5001. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5002. }
  5003. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5004. function serializeAsVector2(sourceName) {
  5005. return generateSerializableMember(4, sourceName); // vector2 member
  5006. }
  5007. BABYLON.serializeAsVector2 = serializeAsVector2;
  5008. function serializeAsVector3(sourceName) {
  5009. return generateSerializableMember(5, sourceName); // vector3 member
  5010. }
  5011. BABYLON.serializeAsVector3 = serializeAsVector3;
  5012. function serializeAsMeshReference(sourceName) {
  5013. return generateSerializableMember(6, sourceName); // mesh reference member
  5014. }
  5015. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5016. function serializeAsColorCurves(sourceName) {
  5017. return generateSerializableMember(7, sourceName); // color curves
  5018. }
  5019. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5020. function serializeAsColor4(sourceName) {
  5021. return generateSerializableMember(8, sourceName); // color 4
  5022. }
  5023. BABYLON.serializeAsColor4 = serializeAsColor4;
  5024. function serializeAsImageProcessingConfiguration(sourceName) {
  5025. return generateSerializableMember(9, sourceName); // image processing
  5026. }
  5027. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5028. var SerializationHelper = (function () {
  5029. function SerializationHelper() {
  5030. }
  5031. SerializationHelper.Serialize = function (entity, serializationObject) {
  5032. if (!serializationObject) {
  5033. serializationObject = {};
  5034. }
  5035. // Tags
  5036. if (BABYLON.Tags) {
  5037. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5038. }
  5039. var serializedProperties = getMergedStore(entity);
  5040. // Properties
  5041. for (var property in serializedProperties) {
  5042. var propertyDescriptor = serializedProperties[property];
  5043. var targetPropertyName = propertyDescriptor.sourceName || property;
  5044. var propertyType = propertyDescriptor.type;
  5045. var sourceProperty = entity[property];
  5046. if (sourceProperty !== undefined && sourceProperty !== null) {
  5047. switch (propertyType) {
  5048. case 0:// Value
  5049. serializationObject[targetPropertyName] = sourceProperty;
  5050. break;
  5051. case 1:// Texture
  5052. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5053. break;
  5054. case 2:// Color3
  5055. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5056. break;
  5057. case 3:// FresnelParameters
  5058. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5059. break;
  5060. case 4:// Vector2
  5061. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5062. break;
  5063. case 5:// Vector3
  5064. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5065. break;
  5066. case 6:// Mesh reference
  5067. serializationObject[targetPropertyName] = sourceProperty.id;
  5068. break;
  5069. case 7:// Color Curves
  5070. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5071. break;
  5072. case 8:// Color 4
  5073. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5074. break;
  5075. case 9:// Image Processing
  5076. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5077. break;
  5078. }
  5079. }
  5080. }
  5081. return serializationObject;
  5082. };
  5083. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5084. var destination = creationFunction();
  5085. // Tags
  5086. if (BABYLON.Tags) {
  5087. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5088. }
  5089. var classStore = getMergedStore(destination);
  5090. // Properties
  5091. for (var property in classStore) {
  5092. var propertyDescriptor = classStore[property];
  5093. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5094. var propertyType = propertyDescriptor.type;
  5095. if (sourceProperty !== undefined && sourceProperty !== null) {
  5096. switch (propertyType) {
  5097. case 0:// Value
  5098. destination[property] = sourceProperty;
  5099. break;
  5100. case 1:// Texture
  5101. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5102. break;
  5103. case 2:// Color3
  5104. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5105. break;
  5106. case 3:// FresnelParameters
  5107. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5108. break;
  5109. case 4:// Vector2
  5110. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5111. break;
  5112. case 5:// Vector3
  5113. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5114. break;
  5115. case 6:// Mesh reference
  5116. destination[property] = scene.getLastMeshByID(sourceProperty);
  5117. break;
  5118. case 7:// Color Curves
  5119. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5120. break;
  5121. case 8:// Color 4
  5122. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5123. break;
  5124. case 9:// Image Processing
  5125. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5126. break;
  5127. }
  5128. }
  5129. }
  5130. return destination;
  5131. };
  5132. SerializationHelper.Clone = function (creationFunction, source) {
  5133. return _copySource(creationFunction, source, false);
  5134. };
  5135. SerializationHelper.Instanciate = function (creationFunction, source) {
  5136. return _copySource(creationFunction, source, true);
  5137. };
  5138. return SerializationHelper;
  5139. }());
  5140. BABYLON.SerializationHelper = SerializationHelper;
  5141. })(BABYLON || (BABYLON = {}));
  5142. //# sourceMappingURL=babylon.decorators.js.map
  5143. var BABYLON;
  5144. (function (BABYLON) {
  5145. /**
  5146. * A class serves as a medium between the observable and its observers
  5147. */
  5148. var EventState = (function () {
  5149. /**
  5150. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5151. */
  5152. function EventState(mask, skipNextObservers) {
  5153. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5154. this.initalize(mask, skipNextObservers);
  5155. }
  5156. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5157. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5158. this.mask = mask;
  5159. this.skipNextObservers = skipNextObservers;
  5160. return this;
  5161. };
  5162. return EventState;
  5163. }());
  5164. BABYLON.EventState = EventState;
  5165. /**
  5166. * Represent an Observer registered to a given Observable object.
  5167. */
  5168. var Observer = (function () {
  5169. function Observer(callback, mask) {
  5170. this.callback = callback;
  5171. this.mask = mask;
  5172. }
  5173. return Observer;
  5174. }());
  5175. BABYLON.Observer = Observer;
  5176. /**
  5177. * The Observable class is a simple implementation of the Observable pattern.
  5178. * 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.
  5179. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5180. * 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).
  5181. * 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.
  5182. */
  5183. var Observable = (function () {
  5184. function Observable() {
  5185. this._observers = new Array();
  5186. this._eventState = new EventState(0);
  5187. }
  5188. /**
  5189. * Create a new Observer with the specified callback
  5190. * @param callback the callback that will be executed for that Observer
  5191. * @param mask the mask used to filter observers
  5192. * @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.
  5193. */
  5194. Observable.prototype.add = function (callback, mask, insertFirst) {
  5195. if (mask === void 0) { mask = -1; }
  5196. if (insertFirst === void 0) { insertFirst = false; }
  5197. if (!callback) {
  5198. return null;
  5199. }
  5200. var observer = new Observer(callback, mask);
  5201. if (insertFirst) {
  5202. this._observers.unshift(observer);
  5203. }
  5204. else {
  5205. this._observers.push(observer);
  5206. }
  5207. return observer;
  5208. };
  5209. /**
  5210. * Remove an Observer from the Observable object
  5211. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5212. */
  5213. Observable.prototype.remove = function (observer) {
  5214. var index = this._observers.indexOf(observer);
  5215. if (index !== -1) {
  5216. this._observers.splice(index, 1);
  5217. return true;
  5218. }
  5219. return false;
  5220. };
  5221. /**
  5222. * Remove a callback from the Observable object
  5223. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5224. */
  5225. Observable.prototype.removeCallback = function (callback) {
  5226. for (var index = 0; index < this._observers.length; index++) {
  5227. if (this._observers[index].callback === callback) {
  5228. this._observers.splice(index, 1);
  5229. return true;
  5230. }
  5231. }
  5232. return false;
  5233. };
  5234. /**
  5235. * Notify all Observers by calling their respective callback with the given data
  5236. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5237. * @param eventData
  5238. * @param mask
  5239. */
  5240. Observable.prototype.notifyObservers = function (eventData, mask) {
  5241. if (mask === void 0) { mask = -1; }
  5242. var state = this._eventState;
  5243. state.mask = mask;
  5244. state.skipNextObservers = false;
  5245. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5246. var obs = _a[_i];
  5247. if (obs.mask & mask) {
  5248. obs.callback(eventData, state);
  5249. }
  5250. if (state.skipNextObservers) {
  5251. return false;
  5252. }
  5253. }
  5254. return true;
  5255. };
  5256. /**
  5257. * return true is the Observable has at least one Observer registered
  5258. */
  5259. Observable.prototype.hasObservers = function () {
  5260. return this._observers.length > 0;
  5261. };
  5262. /**
  5263. * Clear the list of observers
  5264. */
  5265. Observable.prototype.clear = function () {
  5266. this._observers = new Array();
  5267. };
  5268. /**
  5269. * Clone the current observable
  5270. */
  5271. Observable.prototype.clone = function () {
  5272. var result = new Observable();
  5273. result._observers = this._observers.slice(0);
  5274. return result;
  5275. };
  5276. /**
  5277. * Does this observable handles observer registered with a given mask
  5278. * @param {number} trigger - the mask to be tested
  5279. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5280. **/
  5281. Observable.prototype.hasSpecificMask = function (mask) {
  5282. if (mask === void 0) { mask = -1; }
  5283. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5284. var obs = _a[_i];
  5285. if (obs.mask & mask && obs.mask === mask) {
  5286. return true;
  5287. }
  5288. }
  5289. return false;
  5290. };
  5291. return Observable;
  5292. }());
  5293. BABYLON.Observable = Observable;
  5294. })(BABYLON || (BABYLON = {}));
  5295. //# sourceMappingURL=babylon.observable.js.map
  5296. var BABYLON;
  5297. (function (BABYLON) {
  5298. var SmartArray = (function () {
  5299. function SmartArray(capacity) {
  5300. this.length = 0;
  5301. this._duplicateId = 0;
  5302. this.data = new Array(capacity);
  5303. this._id = SmartArray._GlobalId++;
  5304. }
  5305. SmartArray.prototype.push = function (value) {
  5306. this.data[this.length++] = value;
  5307. if (this.length > this.data.length) {
  5308. this.data.length *= 2;
  5309. }
  5310. if (!value.__smartArrayFlags) {
  5311. value.__smartArrayFlags = {};
  5312. }
  5313. value.__smartArrayFlags[this._id] = this._duplicateId;
  5314. };
  5315. SmartArray.prototype.forEach = function (func) {
  5316. for (var index = 0; index < this.length; index++) {
  5317. func(this.data[index]);
  5318. }
  5319. };
  5320. SmartArray.prototype.pushNoDuplicate = function (value) {
  5321. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5322. return false;
  5323. }
  5324. this.push(value);
  5325. return true;
  5326. };
  5327. SmartArray.prototype.sort = function (compareFn) {
  5328. this.data.sort(compareFn);
  5329. };
  5330. SmartArray.prototype.reset = function () {
  5331. this.length = 0;
  5332. this._duplicateId++;
  5333. };
  5334. SmartArray.prototype.dispose = function () {
  5335. this.reset();
  5336. if (this.data) {
  5337. this.data.length = 0;
  5338. this.data = null;
  5339. }
  5340. };
  5341. SmartArray.prototype.concat = function (array) {
  5342. if (array.length === 0) {
  5343. return;
  5344. }
  5345. if (this.length + array.length > this.data.length) {
  5346. this.data.length = (this.length + array.length) * 2;
  5347. }
  5348. for (var index = 0; index < array.length; index++) {
  5349. this.data[this.length++] = (array.data || array)[index];
  5350. }
  5351. };
  5352. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5353. if (array.length === 0) {
  5354. return;
  5355. }
  5356. if (this.length + array.length > this.data.length) {
  5357. this.data.length = (this.length + array.length) * 2;
  5358. }
  5359. for (var index = 0; index < array.length; index++) {
  5360. var item = (array.data || array)[index];
  5361. this.pushNoDuplicate(item);
  5362. }
  5363. };
  5364. SmartArray.prototype.indexOf = function (value) {
  5365. var position = this.data.indexOf(value);
  5366. if (position >= this.length) {
  5367. return -1;
  5368. }
  5369. return position;
  5370. };
  5371. SmartArray.prototype.contains = function (value) {
  5372. return this.data.indexOf(value) !== -1;
  5373. };
  5374. // Statics
  5375. SmartArray._GlobalId = 0;
  5376. return SmartArray;
  5377. }());
  5378. BABYLON.SmartArray = SmartArray;
  5379. })(BABYLON || (BABYLON = {}));
  5380. //# sourceMappingURL=babylon.smartArray.js.map
  5381. var BABYLON;
  5382. (function (BABYLON) {
  5383. // Screenshots
  5384. var screenshotCanvas;
  5385. var cloneValue = function (source, destinationObject) {
  5386. if (!source)
  5387. return null;
  5388. if (source instanceof BABYLON.Mesh) {
  5389. return null;
  5390. }
  5391. if (source instanceof BABYLON.SubMesh) {
  5392. return source.clone(destinationObject);
  5393. }
  5394. else if (source.clone) {
  5395. return source.clone();
  5396. }
  5397. return null;
  5398. };
  5399. var Tools = (function () {
  5400. function Tools() {
  5401. }
  5402. ;
  5403. /**
  5404. * Interpolates between a and b via alpha
  5405. * @param a The lower value (returned when alpha = 0)
  5406. * @param b The upper value (returned when alpha = 1)
  5407. * @param alpha The interpolation-factor
  5408. * @return The mixed value
  5409. */
  5410. Tools.Mix = function (a, b, alpha) {
  5411. return a * (1 - alpha) + b * alpha;
  5412. };
  5413. Tools.Instantiate = function (className) {
  5414. var arr = className.split(".");
  5415. var fn = (window || this);
  5416. for (var i = 0, len = arr.length; i < len; i++) {
  5417. fn = fn[arr[i]];
  5418. }
  5419. if (typeof fn !== "function") {
  5420. return null;
  5421. }
  5422. return fn;
  5423. };
  5424. Tools.SetImmediate = function (action) {
  5425. if (window.setImmediate) {
  5426. window.setImmediate(action);
  5427. }
  5428. else {
  5429. setTimeout(action, 1);
  5430. }
  5431. };
  5432. Tools.IsExponentOfTwo = function (value) {
  5433. var count = 1;
  5434. do {
  5435. count *= 2;
  5436. } while (count < value);
  5437. return count === value;
  5438. };
  5439. /**
  5440. * Find the next highest power of two.
  5441. * @param x Number to start search from.
  5442. * @return Next highest power of two.
  5443. */
  5444. Tools.CeilingPOT = function (x) {
  5445. x--;
  5446. x |= x >> 1;
  5447. x |= x >> 2;
  5448. x |= x >> 4;
  5449. x |= x >> 8;
  5450. x |= x >> 16;
  5451. x++;
  5452. return x;
  5453. };
  5454. /**
  5455. * Find the next lowest power of two.
  5456. * @param x Number to start search from.
  5457. * @return Next lowest power of two.
  5458. */
  5459. Tools.FloorPOT = function (x) {
  5460. x = x | (x >> 1);
  5461. x = x | (x >> 2);
  5462. x = x | (x >> 4);
  5463. x = x | (x >> 8);
  5464. x = x | (x >> 16);
  5465. return x - (x >> 1);
  5466. };
  5467. /**
  5468. * Find the nearest power of two.
  5469. * @param x Number to start search from.
  5470. * @return Next nearest power of two.
  5471. */
  5472. Tools.NearestPOT = function (x) {
  5473. var c = Tools.CeilingPOT(x);
  5474. var f = Tools.FloorPOT(x);
  5475. return (c - x) > (x - f) ? f : c;
  5476. };
  5477. Tools.GetExponentOfTwo = function (value, max, mode) {
  5478. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5479. var pot;
  5480. switch (mode) {
  5481. case BABYLON.Engine.SCALEMODE_FLOOR:
  5482. pot = Tools.FloorPOT(value);
  5483. break;
  5484. case BABYLON.Engine.SCALEMODE_NEAREST:
  5485. pot = Tools.NearestPOT(value);
  5486. break;
  5487. case BABYLON.Engine.SCALEMODE_CEILING:
  5488. pot = Tools.CeilingPOT(value);
  5489. break;
  5490. }
  5491. return Math.min(pot, max);
  5492. };
  5493. Tools.GetFilename = function (path) {
  5494. var index = path.lastIndexOf("/");
  5495. if (index < 0)
  5496. return path;
  5497. return path.substring(index + 1);
  5498. };
  5499. Tools.GetDOMTextContent = function (element) {
  5500. var result = "";
  5501. var child = element.firstChild;
  5502. while (child) {
  5503. if (child.nodeType === 3) {
  5504. result += child.textContent;
  5505. }
  5506. child = child.nextSibling;
  5507. }
  5508. return result;
  5509. };
  5510. Tools.ToDegrees = function (angle) {
  5511. return angle * 180 / Math.PI;
  5512. };
  5513. Tools.ToRadians = function (angle) {
  5514. return angle * Math.PI / 180;
  5515. };
  5516. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5517. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5518. var output = "";
  5519. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5520. var i = 0;
  5521. var bytes = new Uint8Array(buffer);
  5522. while (i < bytes.length) {
  5523. chr1 = bytes[i++];
  5524. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5525. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5526. enc1 = chr1 >> 2;
  5527. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5528. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5529. enc4 = chr3 & 63;
  5530. if (isNaN(chr2)) {
  5531. enc3 = enc4 = 64;
  5532. }
  5533. else if (isNaN(chr3)) {
  5534. enc4 = 64;
  5535. }
  5536. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5537. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5538. }
  5539. return "data:image/png;base64," + output;
  5540. };
  5541. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5542. if (bias === void 0) { bias = null; }
  5543. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5544. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5545. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5546. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5547. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5548. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5549. }
  5550. if (bias) {
  5551. minimum.x -= minimum.x * bias.x + bias.y;
  5552. minimum.y -= minimum.y * bias.x + bias.y;
  5553. minimum.z -= minimum.z * bias.x + bias.y;
  5554. maximum.x += maximum.x * bias.x + bias.y;
  5555. maximum.y += maximum.y * bias.x + bias.y;
  5556. maximum.z += maximum.z * bias.x + bias.y;
  5557. }
  5558. return {
  5559. minimum: minimum,
  5560. maximum: maximum
  5561. };
  5562. };
  5563. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5564. if (bias === void 0) { bias = null; }
  5565. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5566. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5567. if (!stride) {
  5568. stride = 3;
  5569. }
  5570. for (var index = start; index < start + count; index++) {
  5571. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5572. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5573. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5574. }
  5575. if (bias) {
  5576. minimum.x -= minimum.x * bias.x + bias.y;
  5577. minimum.y -= minimum.y * bias.x + bias.y;
  5578. minimum.z -= minimum.z * bias.x + bias.y;
  5579. maximum.x += maximum.x * bias.x + bias.y;
  5580. maximum.y += maximum.y * bias.x + bias.y;
  5581. maximum.z += maximum.z * bias.x + bias.y;
  5582. }
  5583. return {
  5584. minimum: minimum,
  5585. maximum: maximum
  5586. };
  5587. };
  5588. Tools.Vector2ArrayFeeder = function (array) {
  5589. return function (index) {
  5590. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5591. var length = isFloatArray ? array.length / 2 : array.length;
  5592. if (index >= length) {
  5593. return null;
  5594. }
  5595. if (isFloatArray) {
  5596. var fa = array;
  5597. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5598. }
  5599. var a = array;
  5600. return a[index];
  5601. };
  5602. };
  5603. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5604. if (bias === void 0) { bias = null; }
  5605. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5606. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5607. var i = 0;
  5608. var cur = feeder(i++);
  5609. while (cur) {
  5610. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5611. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5612. cur = feeder(i++);
  5613. }
  5614. if (bias) {
  5615. minimum.x -= minimum.x * bias.x + bias.y;
  5616. minimum.y -= minimum.y * bias.x + bias.y;
  5617. maximum.x += maximum.x * bias.x + bias.y;
  5618. maximum.y += maximum.y * bias.x + bias.y;
  5619. }
  5620. return {
  5621. minimum: minimum,
  5622. maximum: maximum
  5623. };
  5624. };
  5625. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5626. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5627. return undefined;
  5628. return Array.isArray(obj) ? obj : [obj];
  5629. };
  5630. // Misc.
  5631. Tools.GetPointerPrefix = function () {
  5632. var eventPrefix = "pointer";
  5633. // Check if pointer events are supported
  5634. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5635. eventPrefix = "mouse";
  5636. }
  5637. return eventPrefix;
  5638. };
  5639. /**
  5640. * @param func - the function to be called
  5641. * @param requester - the object that will request the next frame. Falls back to window.
  5642. */
  5643. Tools.QueueNewFrame = function (func, requester) {
  5644. if (requester === void 0) { requester = window; }
  5645. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5646. /*if(requester.isPresenting) {
  5647. return;
  5648. } else*/ if (requester.requestAnimationFrame)
  5649. requester.requestAnimationFrame(func);
  5650. else if (requester.msRequestAnimationFrame)
  5651. requester.msRequestAnimationFrame(func);
  5652. else if (requester.webkitRequestAnimationFrame)
  5653. requester.webkitRequestAnimationFrame(func);
  5654. else if (requester.mozRequestAnimationFrame)
  5655. requester.mozRequestAnimationFrame(func);
  5656. else if (requester.oRequestAnimationFrame)
  5657. requester.oRequestAnimationFrame(func);
  5658. else {
  5659. window.setTimeout(func, 16);
  5660. }
  5661. };
  5662. Tools.RequestFullscreen = function (element) {
  5663. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5664. if (!requestFunction)
  5665. return;
  5666. requestFunction.call(element);
  5667. };
  5668. Tools.ExitFullscreen = function () {
  5669. if (document.exitFullscreen) {
  5670. document.exitFullscreen();
  5671. }
  5672. else if (document.mozCancelFullScreen) {
  5673. document.mozCancelFullScreen();
  5674. }
  5675. else if (document.webkitCancelFullScreen) {
  5676. document.webkitCancelFullScreen();
  5677. }
  5678. else if (document.msCancelFullScreen) {
  5679. document.msCancelFullScreen();
  5680. }
  5681. };
  5682. Tools.SetCorsBehavior = function (url, img) {
  5683. if (Tools.CorsBehavior) {
  5684. switch (typeof (Tools.CorsBehavior)) {
  5685. case "function":
  5686. var result = Tools.CorsBehavior(url);
  5687. if (result) {
  5688. img.crossOrigin = result;
  5689. }
  5690. break;
  5691. case "string":
  5692. default:
  5693. img.crossOrigin = Tools.CorsBehavior;
  5694. break;
  5695. }
  5696. }
  5697. };
  5698. // External files
  5699. Tools.CleanUrl = function (url) {
  5700. url = url.replace(/#/mg, "%23");
  5701. return url;
  5702. };
  5703. Tools.LoadImage = function (url, onload, onerror, database) {
  5704. if (url instanceof ArrayBuffer) {
  5705. url = Tools.EncodeArrayBufferTobase64(url);
  5706. }
  5707. url = Tools.CleanUrl(url);
  5708. var img = new Image();
  5709. if (url.substr(0, 5) !== "data:") {
  5710. Tools.SetCorsBehavior(url, img);
  5711. }
  5712. img.onload = function () {
  5713. onload(img);
  5714. };
  5715. img.onerror = function (err) {
  5716. Tools.Error("Error while trying to load image: " + url);
  5717. if (Tools.UseFallbackTexture) {
  5718. img.src = Tools.fallbackTexture;
  5719. onload(img);
  5720. }
  5721. else {
  5722. onerror();
  5723. }
  5724. };
  5725. var noIndexedDB = function () {
  5726. img.src = url;
  5727. };
  5728. var loadFromIndexedDB = function () {
  5729. database.loadImageFromDB(url, img);
  5730. };
  5731. //ANY database to do!
  5732. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5733. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5734. }
  5735. else {
  5736. if (url.indexOf("file:") !== 0) {
  5737. noIndexedDB();
  5738. }
  5739. else {
  5740. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5741. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5742. try {
  5743. var blobURL;
  5744. try {
  5745. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5746. }
  5747. catch (ex) {
  5748. // Chrome doesn't support oneTimeOnly parameter
  5749. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5750. }
  5751. img.src = blobURL;
  5752. }
  5753. catch (e) {
  5754. img.src = null;
  5755. }
  5756. }
  5757. else {
  5758. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5759. img.src = Tools.fallbackTexture;
  5760. }
  5761. }
  5762. }
  5763. return img;
  5764. };
  5765. //ANY
  5766. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5767. url = Tools.CleanUrl(url);
  5768. var noIndexedDB = function () {
  5769. var request = new XMLHttpRequest();
  5770. var loadUrl = Tools.BaseUrl + url;
  5771. request.open('GET', loadUrl, true);
  5772. if (useArrayBuffer) {
  5773. request.responseType = "arraybuffer";
  5774. }
  5775. request.onprogress = progressCallBack;
  5776. request.onreadystatechange = function () {
  5777. // In case of undefined state in some browsers.
  5778. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5779. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5780. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5781. callback(!useArrayBuffer ? request.responseText : request.response);
  5782. }
  5783. else {
  5784. if (onError) {
  5785. onError(request);
  5786. }
  5787. else {
  5788. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5789. }
  5790. }
  5791. }
  5792. };
  5793. request.send(null);
  5794. };
  5795. var loadFromIndexedDB = function () {
  5796. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5797. };
  5798. if (url.indexOf("file:") !== -1) {
  5799. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5800. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5801. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5802. }
  5803. else {
  5804. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5805. }
  5806. }
  5807. else {
  5808. // Caching all files
  5809. if (database && database.enableSceneOffline) {
  5810. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5811. }
  5812. else {
  5813. noIndexedDB();
  5814. }
  5815. }
  5816. };
  5817. /**
  5818. * Load a script (identified by an url). When the url returns, the
  5819. * content of this file is added into a new script element, attached to the DOM (body element)
  5820. */
  5821. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5822. var head = document.getElementsByTagName('head')[0];
  5823. var script = document.createElement('script');
  5824. script.type = 'text/javascript';
  5825. script.src = scriptUrl;
  5826. var self = this;
  5827. script.onload = function () {
  5828. if (onSuccess) {
  5829. onSuccess();
  5830. }
  5831. };
  5832. script.onerror = function () {
  5833. if (onError) {
  5834. onError();
  5835. }
  5836. };
  5837. head.appendChild(script);
  5838. };
  5839. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5840. var reader = new FileReader();
  5841. reader.onload = function (e) {
  5842. //target doesn't have result from ts 1.3
  5843. callback(e.target['result']);
  5844. };
  5845. reader.onprogress = progressCallback;
  5846. reader.readAsDataURL(fileToLoad);
  5847. };
  5848. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5849. var reader = new FileReader();
  5850. reader.onerror = function (e) {
  5851. Tools.Log("Error while reading file: " + fileToLoad.name);
  5852. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5853. };
  5854. reader.onload = function (e) {
  5855. //target doesn't have result from ts 1.3
  5856. callback(e.target['result']);
  5857. };
  5858. reader.onprogress = progressCallBack;
  5859. if (!useArrayBuffer) {
  5860. // Asynchronous read
  5861. reader.readAsText(fileToLoad);
  5862. }
  5863. else {
  5864. reader.readAsArrayBuffer(fileToLoad);
  5865. }
  5866. };
  5867. //returns a downloadable url to a file content.
  5868. Tools.FileAsURL = function (content) {
  5869. var fileBlob = new Blob([content]);
  5870. var url = window.URL || window.webkitURL;
  5871. var link = url.createObjectURL(fileBlob);
  5872. return link;
  5873. };
  5874. // Misc.
  5875. Tools.Format = function (value, decimals) {
  5876. if (decimals === void 0) { decimals = 2; }
  5877. return value.toFixed(decimals);
  5878. };
  5879. Tools.CheckExtends = function (v, min, max) {
  5880. if (v.x < min.x)
  5881. min.x = v.x;
  5882. if (v.y < min.y)
  5883. min.y = v.y;
  5884. if (v.z < min.z)
  5885. min.z = v.z;
  5886. if (v.x > max.x)
  5887. max.x = v.x;
  5888. if (v.y > max.y)
  5889. max.y = v.y;
  5890. if (v.z > max.z)
  5891. max.z = v.z;
  5892. };
  5893. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5894. for (var prop in source) {
  5895. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5896. continue;
  5897. }
  5898. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5899. continue;
  5900. }
  5901. var sourceValue = source[prop];
  5902. var typeOfSourceValue = typeof sourceValue;
  5903. if (typeOfSourceValue === "function") {
  5904. continue;
  5905. }
  5906. if (typeOfSourceValue === "object") {
  5907. if (sourceValue instanceof Array) {
  5908. destination[prop] = [];
  5909. if (sourceValue.length > 0) {
  5910. if (typeof sourceValue[0] == "object") {
  5911. for (var index = 0; index < sourceValue.length; index++) {
  5912. var clonedValue = cloneValue(sourceValue[index], destination);
  5913. if (destination[prop].indexOf(clonedValue) === -1) {
  5914. destination[prop].push(clonedValue);
  5915. }
  5916. }
  5917. }
  5918. else {
  5919. destination[prop] = sourceValue.slice(0);
  5920. }
  5921. }
  5922. }
  5923. else {
  5924. destination[prop] = cloneValue(sourceValue, destination);
  5925. }
  5926. }
  5927. else {
  5928. destination[prop] = sourceValue;
  5929. }
  5930. }
  5931. };
  5932. Tools.IsEmpty = function (obj) {
  5933. for (var i in obj) {
  5934. return false;
  5935. }
  5936. return true;
  5937. };
  5938. Tools.RegisterTopRootEvents = function (events) {
  5939. for (var index = 0; index < events.length; index++) {
  5940. var event = events[index];
  5941. window.addEventListener(event.name, event.handler, false);
  5942. try {
  5943. if (window.parent) {
  5944. window.parent.addEventListener(event.name, event.handler, false);
  5945. }
  5946. }
  5947. catch (e) {
  5948. // Silently fails...
  5949. }
  5950. }
  5951. };
  5952. Tools.UnregisterTopRootEvents = function (events) {
  5953. for (var index = 0; index < events.length; index++) {
  5954. var event = events[index];
  5955. window.removeEventListener(event.name, event.handler);
  5956. try {
  5957. if (window.parent) {
  5958. window.parent.removeEventListener(event.name, event.handler);
  5959. }
  5960. }
  5961. catch (e) {
  5962. // Silently fails...
  5963. }
  5964. }
  5965. };
  5966. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5967. if (mimeType === void 0) { mimeType = "image/png"; }
  5968. // Read the contents of the framebuffer
  5969. var numberOfChannelsByLine = width * 4;
  5970. var halfHeight = height / 2;
  5971. //Reading datas from WebGL
  5972. var data = engine.readPixels(0, 0, width, height);
  5973. //To flip image on Y axis.
  5974. for (var i = 0; i < halfHeight; i++) {
  5975. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5976. var currentCell = j + i * numberOfChannelsByLine;
  5977. var targetLine = height - i - 1;
  5978. var targetCell = j + targetLine * numberOfChannelsByLine;
  5979. var temp = data[currentCell];
  5980. data[currentCell] = data[targetCell];
  5981. data[targetCell] = temp;
  5982. }
  5983. }
  5984. // Create a 2D canvas to store the result
  5985. if (!screenshotCanvas) {
  5986. screenshotCanvas = document.createElement('canvas');
  5987. }
  5988. screenshotCanvas.width = width;
  5989. screenshotCanvas.height = height;
  5990. var context = screenshotCanvas.getContext('2d');
  5991. // Copy the pixels to a 2D canvas
  5992. var imageData = context.createImageData(width, height);
  5993. var castData = (imageData.data);
  5994. castData.set(data);
  5995. context.putImageData(imageData, 0, 0);
  5996. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5997. };
  5998. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5999. if (mimeType === void 0) { mimeType = "image/png"; }
  6000. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6001. if (successCallback) {
  6002. successCallback(base64Image);
  6003. }
  6004. else {
  6005. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6006. if (("download" in document.createElement("a"))) {
  6007. var a = window.document.createElement("a");
  6008. a.href = base64Image;
  6009. var date = new Date();
  6010. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6011. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6012. window.document.body.appendChild(a);
  6013. a.addEventListener("click", function () {
  6014. a.parentElement.removeChild(a);
  6015. });
  6016. a.click();
  6017. //Or opening a new tab with the image if it is not possible to automatically start download.
  6018. }
  6019. else {
  6020. var newWindow = window.open("");
  6021. var img = newWindow.document.createElement("img");
  6022. img.src = base64Image;
  6023. newWindow.document.body.appendChild(img);
  6024. }
  6025. }
  6026. };
  6027. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6028. if (mimeType === void 0) { mimeType = "image/png"; }
  6029. var width;
  6030. var height;
  6031. // If a precision value is specified
  6032. if (size.precision) {
  6033. width = Math.round(engine.getRenderWidth() * size.precision);
  6034. height = Math.round(width / engine.getAspectRatio(camera));
  6035. }
  6036. else if (size.width && size.height) {
  6037. width = size.width;
  6038. height = size.height;
  6039. }
  6040. else if (size.width && !size.height) {
  6041. width = size.width;
  6042. height = Math.round(width / engine.getAspectRatio(camera));
  6043. }
  6044. else if (size.height && !size.width) {
  6045. height = size.height;
  6046. width = Math.round(height * engine.getAspectRatio(camera));
  6047. }
  6048. else if (!isNaN(size)) {
  6049. height = size;
  6050. width = size;
  6051. }
  6052. else {
  6053. Tools.Error("Invalid 'size' parameter !");
  6054. return;
  6055. }
  6056. if (!screenshotCanvas) {
  6057. screenshotCanvas = document.createElement('canvas');
  6058. }
  6059. screenshotCanvas.width = width;
  6060. screenshotCanvas.height = height;
  6061. var renderContext = screenshotCanvas.getContext("2d");
  6062. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6063. var newWidth = width;
  6064. var newHeight = newWidth / ratio;
  6065. if (newHeight > height) {
  6066. newHeight = height;
  6067. newWidth = newHeight * ratio;
  6068. }
  6069. var offsetX = Math.max(0, width - newWidth) / 2;
  6070. var offsetY = Math.max(0, height - newHeight) / 2;
  6071. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6072. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6073. };
  6074. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6075. if (mimeType === void 0) { mimeType = "image/png"; }
  6076. if (samples === void 0) { samples = 1; }
  6077. var width;
  6078. var height;
  6079. //If a precision value is specified
  6080. if (size.precision) {
  6081. width = Math.round(engine.getRenderWidth() * size.precision);
  6082. height = Math.round(width / engine.getAspectRatio(camera));
  6083. size = { width: width, height: height };
  6084. }
  6085. else if (size.width && size.height) {
  6086. width = size.width;
  6087. height = size.height;
  6088. }
  6089. else if (size.width && !size.height) {
  6090. width = size.width;
  6091. height = Math.round(width / engine.getAspectRatio(camera));
  6092. size = { width: width, height: height };
  6093. }
  6094. else if (size.height && !size.width) {
  6095. height = size.height;
  6096. width = Math.round(height * engine.getAspectRatio(camera));
  6097. size = { width: width, height: height };
  6098. }
  6099. else if (!isNaN(size)) {
  6100. height = size;
  6101. width = size;
  6102. }
  6103. else {
  6104. Tools.Error("Invalid 'size' parameter !");
  6105. return;
  6106. }
  6107. var scene = camera.getScene();
  6108. var previousCamera = null;
  6109. if (scene.activeCamera !== camera) {
  6110. previousCamera = scene.activeCamera;
  6111. scene.activeCamera = camera;
  6112. }
  6113. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6114. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6115. texture.renderList = null;
  6116. texture.samples = samples;
  6117. texture.onAfterRenderObservable.add(function () {
  6118. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6119. });
  6120. scene.incrementRenderId();
  6121. scene.resetCachedMaterial();
  6122. texture.render(true);
  6123. texture.dispose();
  6124. if (previousCamera) {
  6125. scene.activeCamera = previousCamera;
  6126. }
  6127. camera.getProjectionMatrix(true); // Force cache refresh;
  6128. };
  6129. // XHR response validator for local file scenario
  6130. Tools.ValidateXHRData = function (xhr, dataType) {
  6131. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6132. if (dataType === void 0) { dataType = 7; }
  6133. try {
  6134. if (dataType & 1) {
  6135. if (xhr.responseText && xhr.responseText.length > 0) {
  6136. return true;
  6137. }
  6138. else if (dataType === 1) {
  6139. return false;
  6140. }
  6141. }
  6142. if (dataType & 2) {
  6143. // Check header width and height since there is no "TGA" magic number
  6144. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6145. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6146. return true;
  6147. }
  6148. else if (dataType === 2) {
  6149. return false;
  6150. }
  6151. }
  6152. if (dataType & 4) {
  6153. // Check for the "DDS" magic number
  6154. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6155. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6156. return true;
  6157. }
  6158. else {
  6159. return false;
  6160. }
  6161. }
  6162. }
  6163. catch (e) {
  6164. // Global protection
  6165. }
  6166. return false;
  6167. };
  6168. /**
  6169. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6170. * Be aware Math.random() could cause collisions, but:
  6171. * "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"
  6172. */
  6173. Tools.RandomId = function () {
  6174. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6175. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6176. return v.toString(16);
  6177. });
  6178. };
  6179. Object.defineProperty(Tools, "NoneLogLevel", {
  6180. get: function () {
  6181. return Tools._NoneLogLevel;
  6182. },
  6183. enumerable: true,
  6184. configurable: true
  6185. });
  6186. Object.defineProperty(Tools, "MessageLogLevel", {
  6187. get: function () {
  6188. return Tools._MessageLogLevel;
  6189. },
  6190. enumerable: true,
  6191. configurable: true
  6192. });
  6193. Object.defineProperty(Tools, "WarningLogLevel", {
  6194. get: function () {
  6195. return Tools._WarningLogLevel;
  6196. },
  6197. enumerable: true,
  6198. configurable: true
  6199. });
  6200. Object.defineProperty(Tools, "ErrorLogLevel", {
  6201. get: function () {
  6202. return Tools._ErrorLogLevel;
  6203. },
  6204. enumerable: true,
  6205. configurable: true
  6206. });
  6207. Object.defineProperty(Tools, "AllLogLevel", {
  6208. get: function () {
  6209. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6210. },
  6211. enumerable: true,
  6212. configurable: true
  6213. });
  6214. Tools._AddLogEntry = function (entry) {
  6215. Tools._LogCache = entry + Tools._LogCache;
  6216. if (Tools.OnNewCacheEntry) {
  6217. Tools.OnNewCacheEntry(entry);
  6218. }
  6219. };
  6220. Tools._FormatMessage = function (message) {
  6221. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6222. var date = new Date();
  6223. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6224. };
  6225. Tools._LogDisabled = function (message) {
  6226. // nothing to do
  6227. };
  6228. Tools._LogEnabled = function (message) {
  6229. var formattedMessage = Tools._FormatMessage(message);
  6230. console.log("BJS - " + formattedMessage);
  6231. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6232. Tools._AddLogEntry(entry);
  6233. };
  6234. Tools._WarnDisabled = function (message) {
  6235. // nothing to do
  6236. };
  6237. Tools._WarnEnabled = function (message) {
  6238. var formattedMessage = Tools._FormatMessage(message);
  6239. console.warn("BJS - " + formattedMessage);
  6240. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6241. Tools._AddLogEntry(entry);
  6242. };
  6243. Tools._ErrorDisabled = function (message) {
  6244. // nothing to do
  6245. };
  6246. Tools._ErrorEnabled = function (message) {
  6247. Tools.errorsCount++;
  6248. var formattedMessage = Tools._FormatMessage(message);
  6249. console.error("BJS - " + formattedMessage);
  6250. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6251. Tools._AddLogEntry(entry);
  6252. };
  6253. Object.defineProperty(Tools, "LogCache", {
  6254. get: function () {
  6255. return Tools._LogCache;
  6256. },
  6257. enumerable: true,
  6258. configurable: true
  6259. });
  6260. Tools.ClearLogCache = function () {
  6261. Tools._LogCache = "";
  6262. Tools.errorsCount = 0;
  6263. };
  6264. Object.defineProperty(Tools, "LogLevels", {
  6265. set: function (level) {
  6266. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6267. Tools.Log = Tools._LogEnabled;
  6268. }
  6269. else {
  6270. Tools.Log = Tools._LogDisabled;
  6271. }
  6272. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6273. Tools.Warn = Tools._WarnEnabled;
  6274. }
  6275. else {
  6276. Tools.Warn = Tools._WarnDisabled;
  6277. }
  6278. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6279. Tools.Error = Tools._ErrorEnabled;
  6280. }
  6281. else {
  6282. Tools.Error = Tools._ErrorDisabled;
  6283. }
  6284. },
  6285. enumerable: true,
  6286. configurable: true
  6287. });
  6288. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6289. get: function () {
  6290. return Tools._PerformanceNoneLogLevel;
  6291. },
  6292. enumerable: true,
  6293. configurable: true
  6294. });
  6295. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6296. get: function () {
  6297. return Tools._PerformanceUserMarkLogLevel;
  6298. },
  6299. enumerable: true,
  6300. configurable: true
  6301. });
  6302. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6303. get: function () {
  6304. return Tools._PerformanceConsoleLogLevel;
  6305. },
  6306. enumerable: true,
  6307. configurable: true
  6308. });
  6309. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6310. set: function (level) {
  6311. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6312. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6313. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6314. return;
  6315. }
  6316. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6317. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6318. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6319. return;
  6320. }
  6321. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6322. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6323. },
  6324. enumerable: true,
  6325. configurable: true
  6326. });
  6327. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6328. };
  6329. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6330. };
  6331. Tools._StartUserMark = function (counterName, condition) {
  6332. if (condition === void 0) { condition = true; }
  6333. if (!condition || !Tools._performance.mark) {
  6334. return;
  6335. }
  6336. Tools._performance.mark(counterName + "-Begin");
  6337. };
  6338. Tools._EndUserMark = function (counterName, condition) {
  6339. if (condition === void 0) { condition = true; }
  6340. if (!condition || !Tools._performance.mark) {
  6341. return;
  6342. }
  6343. Tools._performance.mark(counterName + "-End");
  6344. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6345. };
  6346. Tools._StartPerformanceConsole = function (counterName, condition) {
  6347. if (condition === void 0) { condition = true; }
  6348. if (!condition) {
  6349. return;
  6350. }
  6351. Tools._StartUserMark(counterName, condition);
  6352. if (console.time) {
  6353. console.time(counterName);
  6354. }
  6355. };
  6356. Tools._EndPerformanceConsole = function (counterName, condition) {
  6357. if (condition === void 0) { condition = true; }
  6358. if (!condition) {
  6359. return;
  6360. }
  6361. Tools._EndUserMark(counterName, condition);
  6362. if (console.time) {
  6363. console.timeEnd(counterName);
  6364. }
  6365. };
  6366. Object.defineProperty(Tools, "Now", {
  6367. get: function () {
  6368. if (window.performance && window.performance.now) {
  6369. return window.performance.now();
  6370. }
  6371. return new Date().getTime();
  6372. },
  6373. enumerable: true,
  6374. configurable: true
  6375. });
  6376. /**
  6377. * This method will return the name of the class used to create the instance of the given object.
  6378. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6379. * @param object the object to get the class name from
  6380. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6381. */
  6382. Tools.GetClassName = function (object, isType) {
  6383. if (isType === void 0) { isType = false; }
  6384. var name = null;
  6385. if (!isType && object.getClassName) {
  6386. name = object.getClassName();
  6387. }
  6388. else {
  6389. if (object instanceof Object) {
  6390. var classObj = isType ? object : Object.getPrototypeOf(object);
  6391. name = classObj.constructor["__bjsclassName__"];
  6392. }
  6393. if (!name) {
  6394. name = typeof object;
  6395. }
  6396. }
  6397. return name;
  6398. };
  6399. Tools.first = function (array, predicate) {
  6400. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6401. var el = array_1[_i];
  6402. if (predicate(el)) {
  6403. return el;
  6404. }
  6405. }
  6406. };
  6407. /**
  6408. * This method will return the name of the full name of the class, including its owning module (if any).
  6409. * 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).
  6410. * @param object the object to get the class name from
  6411. * @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.
  6412. */
  6413. Tools.getFullClassName = function (object, isType) {
  6414. if (isType === void 0) { isType = false; }
  6415. var className = null;
  6416. var moduleName = null;
  6417. if (!isType && object.getClassName) {
  6418. className = object.getClassName();
  6419. }
  6420. else {
  6421. if (object instanceof Object) {
  6422. var classObj = isType ? object : Object.getPrototypeOf(object);
  6423. className = classObj.constructor["__bjsclassName__"];
  6424. moduleName = classObj.constructor["__bjsmoduleName__"];
  6425. }
  6426. if (!className) {
  6427. className = typeof object;
  6428. }
  6429. }
  6430. if (!className) {
  6431. return null;
  6432. }
  6433. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6434. };
  6435. /**
  6436. * 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.
  6437. * @param array
  6438. */
  6439. Tools.arrayOrStringFeeder = function (array) {
  6440. return function (index) {
  6441. if (index >= array.length) {
  6442. return null;
  6443. }
  6444. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6445. if (val && val.getHashCode) {
  6446. val = val.getHashCode();
  6447. }
  6448. if (typeof val === "string") {
  6449. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6450. }
  6451. return val;
  6452. };
  6453. };
  6454. /**
  6455. * Compute the hashCode of a stream of number
  6456. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6457. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6458. * @return the hash code computed
  6459. */
  6460. Tools.hashCodeFromStream = function (feeder) {
  6461. // Based from here: http://stackoverflow.com/a/7616484/802124
  6462. var hash = 0;
  6463. var index = 0;
  6464. var chr = feeder(index++);
  6465. while (chr != null) {
  6466. hash = ((hash << 5) - hash) + chr;
  6467. hash |= 0; // Convert to 32bit integer
  6468. chr = feeder(index++);
  6469. }
  6470. return hash;
  6471. };
  6472. Tools.BaseUrl = "";
  6473. Tools.CorsBehavior = "anonymous";
  6474. Tools.UseFallbackTexture = true;
  6475. // Used in case of a texture loading problem
  6476. 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";
  6477. // Logs
  6478. Tools._NoneLogLevel = 0;
  6479. Tools._MessageLogLevel = 1;
  6480. Tools._WarningLogLevel = 2;
  6481. Tools._ErrorLogLevel = 4;
  6482. Tools._LogCache = "";
  6483. Tools.errorsCount = 0;
  6484. Tools.Log = Tools._LogEnabled;
  6485. Tools.Warn = Tools._WarnEnabled;
  6486. Tools.Error = Tools._ErrorEnabled;
  6487. // Performances
  6488. Tools._PerformanceNoneLogLevel = 0;
  6489. Tools._PerformanceUserMarkLogLevel = 1;
  6490. Tools._PerformanceConsoleLogLevel = 2;
  6491. Tools._performance = window.performance;
  6492. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6493. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6494. return Tools;
  6495. }());
  6496. BABYLON.Tools = Tools;
  6497. /**
  6498. * This class is used to track a performance counter which is number based.
  6499. * The user has access to many properties which give statistics of different nature
  6500. *
  6501. * The implementer can track two kinds of Performance Counter: time and count
  6502. * 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.
  6503. * 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.
  6504. */
  6505. var PerfCounter = (function () {
  6506. function PerfCounter() {
  6507. this._startMonitoringTime = 0;
  6508. this._min = 0;
  6509. this._max = 0;
  6510. this._average = 0;
  6511. this._lastSecAverage = 0;
  6512. this._current = 0;
  6513. this._totalValueCount = 0;
  6514. this._totalAccumulated = 0;
  6515. this._lastSecAccumulated = 0;
  6516. this._lastSecTime = 0;
  6517. this._lastSecValueCount = 0;
  6518. }
  6519. Object.defineProperty(PerfCounter.prototype, "min", {
  6520. /**
  6521. * Returns the smallest value ever
  6522. */
  6523. get: function () {
  6524. return this._min;
  6525. },
  6526. enumerable: true,
  6527. configurable: true
  6528. });
  6529. Object.defineProperty(PerfCounter.prototype, "max", {
  6530. /**
  6531. * Returns the biggest value ever
  6532. */
  6533. get: function () {
  6534. return this._max;
  6535. },
  6536. enumerable: true,
  6537. configurable: true
  6538. });
  6539. Object.defineProperty(PerfCounter.prototype, "average", {
  6540. /**
  6541. * Returns the average value since the performance counter is running
  6542. */
  6543. get: function () {
  6544. return this._average;
  6545. },
  6546. enumerable: true,
  6547. configurable: true
  6548. });
  6549. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6550. /**
  6551. * Returns the average value of the last second the counter was monitored
  6552. */
  6553. get: function () {
  6554. return this._lastSecAverage;
  6555. },
  6556. enumerable: true,
  6557. configurable: true
  6558. });
  6559. Object.defineProperty(PerfCounter.prototype, "current", {
  6560. /**
  6561. * Returns the current value
  6562. */
  6563. get: function () {
  6564. return this._current;
  6565. },
  6566. enumerable: true,
  6567. configurable: true
  6568. });
  6569. Object.defineProperty(PerfCounter.prototype, "total", {
  6570. get: function () {
  6571. return this._totalAccumulated;
  6572. },
  6573. enumerable: true,
  6574. configurable: true
  6575. });
  6576. /**
  6577. * Call this method to start monitoring a new frame.
  6578. * 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.
  6579. */
  6580. PerfCounter.prototype.fetchNewFrame = function () {
  6581. this._totalValueCount++;
  6582. this._current = 0;
  6583. this._lastSecValueCount++;
  6584. };
  6585. /**
  6586. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6587. * @param newCount the count value to add to the monitored count
  6588. * @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.
  6589. */
  6590. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6591. if (!PerfCounter.Enabled) {
  6592. return;
  6593. }
  6594. this._current += newCount;
  6595. if (fetchResult) {
  6596. this._fetchResult();
  6597. }
  6598. };
  6599. /**
  6600. * Start monitoring this performance counter
  6601. */
  6602. PerfCounter.prototype.beginMonitoring = function () {
  6603. if (!PerfCounter.Enabled) {
  6604. return;
  6605. }
  6606. this._startMonitoringTime = Tools.Now;
  6607. };
  6608. /**
  6609. * Compute the time lapsed since the previous beginMonitoring() call.
  6610. * @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
  6611. */
  6612. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6613. if (newFrame === void 0) { newFrame = true; }
  6614. if (!PerfCounter.Enabled) {
  6615. return;
  6616. }
  6617. if (newFrame) {
  6618. this.fetchNewFrame();
  6619. }
  6620. var currentTime = Tools.Now;
  6621. this._current = currentTime - this._startMonitoringTime;
  6622. if (newFrame) {
  6623. this._fetchResult();
  6624. }
  6625. };
  6626. PerfCounter.prototype._fetchResult = function () {
  6627. this._totalAccumulated += this._current;
  6628. this._lastSecAccumulated += this._current;
  6629. // Min/Max update
  6630. this._min = Math.min(this._min, this._current);
  6631. this._max = Math.max(this._max, this._current);
  6632. this._average = this._totalAccumulated / this._totalValueCount;
  6633. // Reset last sec?
  6634. var now = Tools.Now;
  6635. if ((now - this._lastSecTime) > 1000) {
  6636. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6637. this._lastSecTime = now;
  6638. this._lastSecAccumulated = 0;
  6639. this._lastSecValueCount = 0;
  6640. }
  6641. };
  6642. PerfCounter.Enabled = true;
  6643. return PerfCounter;
  6644. }());
  6645. BABYLON.PerfCounter = PerfCounter;
  6646. /**
  6647. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6648. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6649. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6650. * @param name The name of the class, case should be preserved
  6651. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6652. */
  6653. function className(name, module) {
  6654. return function (target) {
  6655. target["__bjsclassName__"] = name;
  6656. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6657. };
  6658. }
  6659. BABYLON.className = className;
  6660. /**
  6661. * An implementation of a loop for asynchronous functions.
  6662. */
  6663. var AsyncLoop = (function () {
  6664. /**
  6665. * Constroctor.
  6666. * @param iterations the number of iterations.
  6667. * @param _fn the function to run each iteration
  6668. * @param _successCallback the callback that will be called upon succesful execution
  6669. * @param offset starting offset.
  6670. */
  6671. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6672. if (offset === void 0) { offset = 0; }
  6673. this.iterations = iterations;
  6674. this._fn = _fn;
  6675. this._successCallback = _successCallback;
  6676. this.index = offset - 1;
  6677. this._done = false;
  6678. }
  6679. /**
  6680. * Execute the next iteration. Must be called after the last iteration was finished.
  6681. */
  6682. AsyncLoop.prototype.executeNext = function () {
  6683. if (!this._done) {
  6684. if (this.index + 1 < this.iterations) {
  6685. ++this.index;
  6686. this._fn(this);
  6687. }
  6688. else {
  6689. this.breakLoop();
  6690. }
  6691. }
  6692. };
  6693. /**
  6694. * Break the loop and run the success callback.
  6695. */
  6696. AsyncLoop.prototype.breakLoop = function () {
  6697. this._done = true;
  6698. this._successCallback();
  6699. };
  6700. /**
  6701. * Helper function
  6702. */
  6703. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6704. if (offset === void 0) { offset = 0; }
  6705. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6706. loop.executeNext();
  6707. return loop;
  6708. };
  6709. /**
  6710. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6711. * @param iterations total number of iterations
  6712. * @param syncedIterations number of synchronous iterations in each async iteration.
  6713. * @param fn the function to call each iteration.
  6714. * @param callback a success call back that will be called when iterating stops.
  6715. * @param breakFunction a break condition (optional)
  6716. * @param timeout timeout settings for the setTimeout function. default - 0.
  6717. * @constructor
  6718. */
  6719. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6720. if (timeout === void 0) { timeout = 0; }
  6721. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6722. if (breakFunction && breakFunction())
  6723. loop.breakLoop();
  6724. else {
  6725. setTimeout(function () {
  6726. for (var i = 0; i < syncedIterations; ++i) {
  6727. var iteration = (loop.index * syncedIterations) + i;
  6728. if (iteration >= iterations)
  6729. break;
  6730. fn(iteration);
  6731. if (breakFunction && breakFunction()) {
  6732. loop.breakLoop();
  6733. break;
  6734. }
  6735. }
  6736. loop.executeNext();
  6737. }, timeout);
  6738. }
  6739. }, callback);
  6740. };
  6741. return AsyncLoop;
  6742. }());
  6743. BABYLON.AsyncLoop = AsyncLoop;
  6744. })(BABYLON || (BABYLON = {}));
  6745. //# sourceMappingURL=babylon.tools.js.map
  6746. var BABYLON;
  6747. (function (BABYLON) {
  6748. var Internals;
  6749. (function (Internals) {
  6750. var _AlphaState = (function () {
  6751. /**
  6752. * Initializes the state.
  6753. */
  6754. function _AlphaState() {
  6755. this._isAlphaBlendDirty = false;
  6756. this._isBlendFunctionParametersDirty = false;
  6757. this._isBlendEquationParametersDirty = false;
  6758. this._isBlendConstantsDirty = false;
  6759. this._alphaBlend = false;
  6760. this._blendFunctionParameters = new Array(4);
  6761. this._blendEquationParameters = new Array(2);
  6762. this._blendConstants = new Array(4);
  6763. this.reset();
  6764. }
  6765. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6766. get: function () {
  6767. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6768. },
  6769. enumerable: true,
  6770. configurable: true
  6771. });
  6772. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6773. get: function () {
  6774. return this._alphaBlend;
  6775. },
  6776. set: function (value) {
  6777. if (this._alphaBlend === value) {
  6778. return;
  6779. }
  6780. this._alphaBlend = value;
  6781. this._isAlphaBlendDirty = true;
  6782. },
  6783. enumerable: true,
  6784. configurable: true
  6785. });
  6786. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6787. if (this._blendConstants[0] === r &&
  6788. this._blendConstants[1] === g &&
  6789. this._blendConstants[2] === b &&
  6790. this._blendConstants[3] === a) {
  6791. return;
  6792. }
  6793. this._blendConstants[0] = r;
  6794. this._blendConstants[1] = g;
  6795. this._blendConstants[2] = b;
  6796. this._blendConstants[3] = a;
  6797. this._isBlendConstantsDirty = true;
  6798. };
  6799. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6800. if (this._blendFunctionParameters[0] === value0 &&
  6801. this._blendFunctionParameters[1] === value1 &&
  6802. this._blendFunctionParameters[2] === value2 &&
  6803. this._blendFunctionParameters[3] === value3) {
  6804. return;
  6805. }
  6806. this._blendFunctionParameters[0] = value0;
  6807. this._blendFunctionParameters[1] = value1;
  6808. this._blendFunctionParameters[2] = value2;
  6809. this._blendFunctionParameters[3] = value3;
  6810. this._isBlendFunctionParametersDirty = true;
  6811. };
  6812. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6813. if (this._blendEquationParameters[0] === rgb &&
  6814. this._blendEquationParameters[1] === alpha) {
  6815. return;
  6816. }
  6817. this._blendEquationParameters[0] = rgb;
  6818. this._blendEquationParameters[1] = alpha;
  6819. this._isBlendEquationParametersDirty = true;
  6820. };
  6821. _AlphaState.prototype.reset = function () {
  6822. this._alphaBlend = false;
  6823. this._blendFunctionParameters[0] = null;
  6824. this._blendFunctionParameters[1] = null;
  6825. this._blendFunctionParameters[2] = null;
  6826. this._blendFunctionParameters[3] = null;
  6827. this._blendEquationParameters[0] = null;
  6828. this._blendEquationParameters[1] = null;
  6829. this._blendConstants[0] = null;
  6830. this._blendConstants[1] = null;
  6831. this._blendConstants[2] = null;
  6832. this._blendConstants[3] = null;
  6833. this._isAlphaBlendDirty = true;
  6834. this._isBlendFunctionParametersDirty = false;
  6835. this._isBlendEquationParametersDirty = false;
  6836. this._isBlendConstantsDirty = false;
  6837. };
  6838. _AlphaState.prototype.apply = function (gl) {
  6839. if (!this.isDirty) {
  6840. return;
  6841. }
  6842. // Alpha blend
  6843. if (this._isAlphaBlendDirty) {
  6844. if (this._alphaBlend) {
  6845. gl.enable(gl.BLEND);
  6846. }
  6847. else {
  6848. gl.disable(gl.BLEND);
  6849. }
  6850. this._isAlphaBlendDirty = false;
  6851. }
  6852. // Alpha function
  6853. if (this._isBlendFunctionParametersDirty) {
  6854. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6855. this._isBlendFunctionParametersDirty = false;
  6856. }
  6857. // Alpha equation
  6858. if (this._isBlendEquationParametersDirty) {
  6859. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6860. this._isBlendEquationParametersDirty = false;
  6861. }
  6862. // Constants
  6863. if (this._isBlendConstantsDirty) {
  6864. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6865. this._isBlendConstantsDirty = false;
  6866. }
  6867. };
  6868. return _AlphaState;
  6869. }());
  6870. Internals._AlphaState = _AlphaState;
  6871. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6872. })(BABYLON || (BABYLON = {}));
  6873. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6874. var BABYLON;
  6875. (function (BABYLON) {
  6876. var Internals;
  6877. (function (Internals) {
  6878. var _DepthCullingState = (function () {
  6879. /**
  6880. * Initializes the state.
  6881. */
  6882. function _DepthCullingState() {
  6883. this._isDepthTestDirty = false;
  6884. this._isDepthMaskDirty = false;
  6885. this._isDepthFuncDirty = false;
  6886. this._isCullFaceDirty = false;
  6887. this._isCullDirty = false;
  6888. this._isZOffsetDirty = false;
  6889. this.reset();
  6890. }
  6891. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6892. get: function () {
  6893. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6894. },
  6895. enumerable: true,
  6896. configurable: true
  6897. });
  6898. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6899. get: function () {
  6900. return this._zOffset;
  6901. },
  6902. set: function (value) {
  6903. if (this._zOffset === value) {
  6904. return;
  6905. }
  6906. this._zOffset = value;
  6907. this._isZOffsetDirty = true;
  6908. },
  6909. enumerable: true,
  6910. configurable: true
  6911. });
  6912. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6913. get: function () {
  6914. return this._cullFace;
  6915. },
  6916. set: function (value) {
  6917. if (this._cullFace === value) {
  6918. return;
  6919. }
  6920. this._cullFace = value;
  6921. this._isCullFaceDirty = true;
  6922. },
  6923. enumerable: true,
  6924. configurable: true
  6925. });
  6926. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6927. get: function () {
  6928. return this._cull;
  6929. },
  6930. set: function (value) {
  6931. if (this._cull === value) {
  6932. return;
  6933. }
  6934. this._cull = value;
  6935. this._isCullDirty = true;
  6936. },
  6937. enumerable: true,
  6938. configurable: true
  6939. });
  6940. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6941. get: function () {
  6942. return this._depthFunc;
  6943. },
  6944. set: function (value) {
  6945. if (this._depthFunc === value) {
  6946. return;
  6947. }
  6948. this._depthFunc = value;
  6949. this._isDepthFuncDirty = true;
  6950. },
  6951. enumerable: true,
  6952. configurable: true
  6953. });
  6954. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6955. get: function () {
  6956. return this._depthMask;
  6957. },
  6958. set: function (value) {
  6959. if (this._depthMask === value) {
  6960. return;
  6961. }
  6962. this._depthMask = value;
  6963. this._isDepthMaskDirty = true;
  6964. },
  6965. enumerable: true,
  6966. configurable: true
  6967. });
  6968. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6969. get: function () {
  6970. return this._depthTest;
  6971. },
  6972. set: function (value) {
  6973. if (this._depthTest === value) {
  6974. return;
  6975. }
  6976. this._depthTest = value;
  6977. this._isDepthTestDirty = true;
  6978. },
  6979. enumerable: true,
  6980. configurable: true
  6981. });
  6982. _DepthCullingState.prototype.reset = function () {
  6983. this._depthMask = true;
  6984. this._depthTest = true;
  6985. this._depthFunc = null;
  6986. this._cullFace = null;
  6987. this._cull = null;
  6988. this._zOffset = 0;
  6989. this._isDepthTestDirty = true;
  6990. this._isDepthMaskDirty = true;
  6991. this._isDepthFuncDirty = false;
  6992. this._isCullFaceDirty = false;
  6993. this._isCullDirty = false;
  6994. this._isZOffsetDirty = false;
  6995. };
  6996. _DepthCullingState.prototype.apply = function (gl) {
  6997. if (!this.isDirty) {
  6998. return;
  6999. }
  7000. // Cull
  7001. if (this._isCullDirty) {
  7002. if (this.cull) {
  7003. gl.enable(gl.CULL_FACE);
  7004. }
  7005. else {
  7006. gl.disable(gl.CULL_FACE);
  7007. }
  7008. this._isCullDirty = false;
  7009. }
  7010. // Cull face
  7011. if (this._isCullFaceDirty) {
  7012. gl.cullFace(this.cullFace);
  7013. this._isCullFaceDirty = false;
  7014. }
  7015. // Depth mask
  7016. if (this._isDepthMaskDirty) {
  7017. gl.depthMask(this.depthMask);
  7018. this._isDepthMaskDirty = false;
  7019. }
  7020. // Depth test
  7021. if (this._isDepthTestDirty) {
  7022. if (this.depthTest) {
  7023. gl.enable(gl.DEPTH_TEST);
  7024. }
  7025. else {
  7026. gl.disable(gl.DEPTH_TEST);
  7027. }
  7028. this._isDepthTestDirty = false;
  7029. }
  7030. // Depth func
  7031. if (this._isDepthFuncDirty) {
  7032. gl.depthFunc(this.depthFunc);
  7033. this._isDepthFuncDirty = false;
  7034. }
  7035. // zOffset
  7036. if (this._isZOffsetDirty) {
  7037. if (this.zOffset) {
  7038. gl.enable(gl.POLYGON_OFFSET_FILL);
  7039. gl.polygonOffset(this.zOffset, 0);
  7040. }
  7041. else {
  7042. gl.disable(gl.POLYGON_OFFSET_FILL);
  7043. }
  7044. this._isZOffsetDirty = false;
  7045. }
  7046. };
  7047. return _DepthCullingState;
  7048. }());
  7049. Internals._DepthCullingState = _DepthCullingState;
  7050. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7051. })(BABYLON || (BABYLON = {}));
  7052. //# sourceMappingURL=babylon.depthCullingState.js.map
  7053. var BABYLON;
  7054. (function (BABYLON) {
  7055. var Internals;
  7056. (function (Internals) {
  7057. var _StencilState = (function () {
  7058. function _StencilState() {
  7059. this._isStencilTestDirty = false;
  7060. this._isStencilMaskDirty = false;
  7061. this._isStencilFuncDirty = false;
  7062. this._isStencilOpDirty = false;
  7063. this.reset();
  7064. }
  7065. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7066. get: function () {
  7067. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7068. },
  7069. enumerable: true,
  7070. configurable: true
  7071. });
  7072. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7073. get: function () {
  7074. return this._stencilFunc;
  7075. },
  7076. set: function (value) {
  7077. if (this._stencilFunc === value) {
  7078. return;
  7079. }
  7080. this._stencilFunc = value;
  7081. this._isStencilFuncDirty = true;
  7082. },
  7083. enumerable: true,
  7084. configurable: true
  7085. });
  7086. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7087. get: function () {
  7088. return this._stencilFuncRef;
  7089. },
  7090. set: function (value) {
  7091. if (this._stencilFuncRef === value) {
  7092. return;
  7093. }
  7094. this._stencilFuncRef = value;
  7095. this._isStencilFuncDirty = true;
  7096. },
  7097. enumerable: true,
  7098. configurable: true
  7099. });
  7100. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7101. get: function () {
  7102. return this._stencilFuncMask;
  7103. },
  7104. set: function (value) {
  7105. if (this._stencilFuncMask === value) {
  7106. return;
  7107. }
  7108. this._stencilFuncMask = value;
  7109. this._isStencilFuncDirty = true;
  7110. },
  7111. enumerable: true,
  7112. configurable: true
  7113. });
  7114. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7115. get: function () {
  7116. return this._stencilOpStencilFail;
  7117. },
  7118. set: function (value) {
  7119. if (this._stencilOpStencilFail === value) {
  7120. return;
  7121. }
  7122. this._stencilOpStencilFail = value;
  7123. this._isStencilOpDirty = true;
  7124. },
  7125. enumerable: true,
  7126. configurable: true
  7127. });
  7128. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7129. get: function () {
  7130. return this._stencilOpDepthFail;
  7131. },
  7132. set: function (value) {
  7133. if (this._stencilOpDepthFail === value) {
  7134. return;
  7135. }
  7136. this._stencilOpDepthFail = value;
  7137. this._isStencilOpDirty = true;
  7138. },
  7139. enumerable: true,
  7140. configurable: true
  7141. });
  7142. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7143. get: function () {
  7144. return this._stencilOpStencilDepthPass;
  7145. },
  7146. set: function (value) {
  7147. if (this._stencilOpStencilDepthPass === value) {
  7148. return;
  7149. }
  7150. this._stencilOpStencilDepthPass = value;
  7151. this._isStencilOpDirty = true;
  7152. },
  7153. enumerable: true,
  7154. configurable: true
  7155. });
  7156. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7157. get: function () {
  7158. return this._stencilMask;
  7159. },
  7160. set: function (value) {
  7161. if (this._stencilMask === value) {
  7162. return;
  7163. }
  7164. this._stencilMask = value;
  7165. this._isStencilMaskDirty = true;
  7166. },
  7167. enumerable: true,
  7168. configurable: true
  7169. });
  7170. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7171. get: function () {
  7172. return this._stencilTest;
  7173. },
  7174. set: function (value) {
  7175. if (this._stencilTest === value) {
  7176. return;
  7177. }
  7178. this._stencilTest = value;
  7179. this._isStencilTestDirty = true;
  7180. },
  7181. enumerable: true,
  7182. configurable: true
  7183. });
  7184. _StencilState.prototype.reset = function () {
  7185. this._stencilTest = false;
  7186. this._stencilMask = 0xFF;
  7187. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7188. this._stencilFuncRef = 1;
  7189. this._stencilFuncMask = 0xFF;
  7190. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7191. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7192. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7193. this._isStencilTestDirty = true;
  7194. this._isStencilMaskDirty = true;
  7195. this._isStencilFuncDirty = true;
  7196. this._isStencilOpDirty = true;
  7197. };
  7198. _StencilState.prototype.apply = function (gl) {
  7199. if (!this.isDirty) {
  7200. return;
  7201. }
  7202. // Stencil test
  7203. if (this._isStencilTestDirty) {
  7204. if (this.stencilTest) {
  7205. gl.enable(gl.STENCIL_TEST);
  7206. }
  7207. else {
  7208. gl.disable(gl.STENCIL_TEST);
  7209. }
  7210. this._isStencilTestDirty = false;
  7211. }
  7212. // Stencil mask
  7213. if (this._isStencilMaskDirty) {
  7214. gl.stencilMask(this.stencilMask);
  7215. this._isStencilMaskDirty = false;
  7216. }
  7217. // Stencil func
  7218. if (this._isStencilFuncDirty) {
  7219. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7220. this._isStencilFuncDirty = false;
  7221. }
  7222. // Stencil op
  7223. if (this._isStencilOpDirty) {
  7224. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7225. this._isStencilOpDirty = false;
  7226. }
  7227. };
  7228. return _StencilState;
  7229. }());
  7230. Internals._StencilState = _StencilState;
  7231. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7232. })(BABYLON || (BABYLON = {}));
  7233. //# sourceMappingURL=babylon.stencilState.js.map
  7234. var BABYLON;
  7235. (function (BABYLON) {
  7236. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7237. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7238. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7239. gl.compileShader(shader);
  7240. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7241. throw new Error(gl.getShaderInfoLog(shader));
  7242. }
  7243. return shader;
  7244. };
  7245. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7246. var magFilter = gl.NEAREST;
  7247. var minFilter = gl.NEAREST;
  7248. switch (samplingMode) {
  7249. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7250. magFilter = gl.LINEAR;
  7251. if (generateMipMaps) {
  7252. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7253. }
  7254. else {
  7255. minFilter = gl.LINEAR;
  7256. }
  7257. break;
  7258. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7259. magFilter = gl.LINEAR;
  7260. if (generateMipMaps) {
  7261. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7262. }
  7263. else {
  7264. minFilter = gl.LINEAR;
  7265. }
  7266. break;
  7267. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7268. magFilter = gl.NEAREST;
  7269. if (generateMipMaps) {
  7270. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7271. }
  7272. else {
  7273. minFilter = gl.NEAREST;
  7274. }
  7275. break;
  7276. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7277. magFilter = gl.NEAREST;
  7278. if (generateMipMaps) {
  7279. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7280. }
  7281. else {
  7282. minFilter = gl.NEAREST;
  7283. }
  7284. break;
  7285. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7286. magFilter = gl.NEAREST;
  7287. if (generateMipMaps) {
  7288. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7289. }
  7290. else {
  7291. minFilter = gl.LINEAR;
  7292. }
  7293. break;
  7294. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7295. magFilter = gl.NEAREST;
  7296. if (generateMipMaps) {
  7297. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7298. }
  7299. else {
  7300. minFilter = gl.LINEAR;
  7301. }
  7302. break;
  7303. case BABYLON.Texture.NEAREST_LINEAR:
  7304. magFilter = gl.NEAREST;
  7305. minFilter = gl.LINEAR;
  7306. break;
  7307. case BABYLON.Texture.NEAREST_NEAREST:
  7308. magFilter = gl.NEAREST;
  7309. minFilter = gl.NEAREST;
  7310. break;
  7311. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7312. magFilter = gl.LINEAR;
  7313. if (generateMipMaps) {
  7314. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7315. }
  7316. else {
  7317. minFilter = gl.NEAREST;
  7318. }
  7319. break;
  7320. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7321. magFilter = gl.LINEAR;
  7322. if (generateMipMaps) {
  7323. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7324. }
  7325. else {
  7326. minFilter = gl.NEAREST;
  7327. }
  7328. break;
  7329. case BABYLON.Texture.LINEAR_LINEAR:
  7330. magFilter = gl.LINEAR;
  7331. minFilter = gl.LINEAR;
  7332. break;
  7333. case BABYLON.Texture.LINEAR_NEAREST:
  7334. magFilter = gl.LINEAR;
  7335. minFilter = gl.NEAREST;
  7336. break;
  7337. }
  7338. return {
  7339. min: minFilter,
  7340. mag: magFilter
  7341. };
  7342. };
  7343. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7344. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7345. var img;
  7346. var onload = function () {
  7347. loadedImages[index] = img;
  7348. loadedImages._internalCount++;
  7349. scene._removePendingData(img);
  7350. if (loadedImages._internalCount === 6) {
  7351. onfinish(loadedImages);
  7352. }
  7353. };
  7354. var onerror = function () {
  7355. scene._removePendingData(img);
  7356. if (onErrorCallBack) {
  7357. onErrorCallBack();
  7358. }
  7359. };
  7360. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7361. scene._addPendingData(img);
  7362. };
  7363. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7364. if (onError === void 0) { onError = null; }
  7365. var loadedImages = [];
  7366. loadedImages._internalCount = 0;
  7367. for (var index = 0; index < 6; index++) {
  7368. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7369. }
  7370. };
  7371. var BufferPointer = (function () {
  7372. function BufferPointer() {
  7373. }
  7374. return BufferPointer;
  7375. }());
  7376. var InstancingAttributeInfo = (function () {
  7377. function InstancingAttributeInfo() {
  7378. }
  7379. return InstancingAttributeInfo;
  7380. }());
  7381. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7382. /**
  7383. * Regroup several parameters relative to the browser in use
  7384. */
  7385. var EngineCapabilities = (function () {
  7386. function EngineCapabilities() {
  7387. }
  7388. return EngineCapabilities;
  7389. }());
  7390. BABYLON.EngineCapabilities = EngineCapabilities;
  7391. /**
  7392. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7393. */
  7394. var Engine = (function () {
  7395. /**
  7396. * @constructor
  7397. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7398. * @param {boolean} [antialias] - enable antialias
  7399. * @param options - further options to be sent to the getContext function
  7400. */
  7401. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7402. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7403. var _this = this;
  7404. // Public members
  7405. this.forcePOTTextures = false;
  7406. this.isFullscreen = false;
  7407. this.isPointerLock = false;
  7408. this.cullBackFaces = true;
  7409. this.renderEvenInBackground = true;
  7410. this.preventCacheWipeBetweenFrames = false;
  7411. // To enable/disable IDB support and avoid XHR on .manifest
  7412. this.enableOfflineSupport = false;
  7413. this.scenes = new Array();
  7414. // Observables
  7415. /**
  7416. * Observable event triggered each time the rendering canvas is resized
  7417. */
  7418. this.onResizeObservable = new BABYLON.Observable();
  7419. /**
  7420. * Observable event triggered each time the canvas lost focus
  7421. */
  7422. this.onCanvasBlurObservable = new BABYLON.Observable();
  7423. this._windowIsBackground = false;
  7424. this._webGLVersion = 1.0;
  7425. this._badOS = false;
  7426. this._badDesktopOS = false;
  7427. this._drawCalls = new BABYLON.PerfCounter();
  7428. this._renderingQueueLaunched = false;
  7429. this._activeRenderLoops = [];
  7430. // Deterministic lockstepMaxSteps
  7431. this._deterministicLockstep = false;
  7432. this._lockstepMaxSteps = 4;
  7433. // FPS
  7434. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7435. this._fps = 60;
  7436. this._deltaTime = 0;
  7437. // States
  7438. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7439. this._stencilState = new BABYLON.Internals._StencilState();
  7440. this._alphaState = new BABYLON.Internals._AlphaState();
  7441. this._alphaMode = Engine.ALPHA_DISABLE;
  7442. // Cache
  7443. this._loadedTexturesCache = new Array();
  7444. this._maxTextureChannels = 16;
  7445. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7446. this._compiledEffects = {};
  7447. this._vertexAttribArraysEnabled = [];
  7448. this._uintIndicesCurrentlySet = false;
  7449. this._currentBoundBuffer = new Array();
  7450. this._currentBufferPointers = new Array();
  7451. this._currentInstanceLocations = new Array();
  7452. this._currentInstanceBuffers = new Array();
  7453. this._vaoRecordInProgress = false;
  7454. this._mustWipeVertexAttributes = false;
  7455. // Hardware supported Compressed Textures
  7456. this._texturesSupported = new Array();
  7457. this._onVRFullScreenTriggered = function () {
  7458. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7459. //get the old size before we change
  7460. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7461. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7462. //get the width and height, change the render size
  7463. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7464. var width, height;
  7465. _this.setHardwareScalingLevel(1);
  7466. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7467. }
  7468. else {
  7469. //When the specs are implemented, need to uncomment this.
  7470. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7471. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7472. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7473. _this._vrDisplayEnabled = undefined;
  7474. }
  7475. };
  7476. var canvas;
  7477. Engine.Instances.push(this);
  7478. options = options || {};
  7479. if (canvasOrContext.getContext) {
  7480. canvas = canvasOrContext;
  7481. this._renderingCanvas = canvas;
  7482. if (antialias != null) {
  7483. options.antialias = antialias;
  7484. }
  7485. if (options.deterministicLockstep === undefined) {
  7486. options.deterministicLockstep = false;
  7487. }
  7488. if (options.lockstepMaxSteps === undefined) {
  7489. options.lockstepMaxSteps = 4;
  7490. }
  7491. if (options.preserveDrawingBuffer === undefined) {
  7492. options.preserveDrawingBuffer = false;
  7493. }
  7494. if (options.audioEngine === undefined) {
  7495. options.audioEngine = true;
  7496. }
  7497. if (options.stencil === undefined) {
  7498. options.stencil = true;
  7499. }
  7500. this._deterministicLockstep = options.deterministicLockstep;
  7501. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7502. // GL
  7503. if (!options.disableWebGL2Support) {
  7504. try {
  7505. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7506. if (this._gl) {
  7507. this._webGLVersion = 2.0;
  7508. }
  7509. }
  7510. catch (e) {
  7511. // Do nothing
  7512. }
  7513. }
  7514. if (!this._gl) {
  7515. if (!canvas) {
  7516. throw new Error("The provided canvas is null or undefined.");
  7517. }
  7518. try {
  7519. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7520. }
  7521. catch (e) {
  7522. throw new Error("WebGL not supported");
  7523. }
  7524. }
  7525. if (!this._gl) {
  7526. throw new Error("WebGL not supported");
  7527. }
  7528. this._onBlur = function () {
  7529. _this._performanceMonitor.disable();
  7530. _this._windowIsBackground = true;
  7531. };
  7532. this._onFocus = function () {
  7533. _this._performanceMonitor.enable();
  7534. _this._windowIsBackground = false;
  7535. };
  7536. this._onCanvasBlur = function () {
  7537. _this.onCanvasBlurObservable.notifyObservers(_this);
  7538. };
  7539. window.addEventListener("blur", this._onBlur);
  7540. window.addEventListener("focus", this._onFocus);
  7541. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7542. }
  7543. else {
  7544. this._gl = canvasOrContext;
  7545. this._renderingCanvas = this._gl.canvas;
  7546. if (this._gl.renderbufferStorageMultisample) {
  7547. this._webGLVersion = 2.0;
  7548. }
  7549. options.stencil = this._gl.getContextAttributes().stencil;
  7550. }
  7551. // Viewport
  7552. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7553. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7554. this.resize();
  7555. // Caps
  7556. this._isStencilEnable = options.stencil;
  7557. this._caps = new EngineCapabilities();
  7558. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7559. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7560. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7561. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7562. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7563. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7564. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7565. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7566. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7567. // Infos
  7568. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7569. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7570. if (rendererInfo != null) {
  7571. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7572. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7573. }
  7574. if (!this._glVendor) {
  7575. this._glVendor = "Unknown vendor";
  7576. }
  7577. if (!this._glRenderer) {
  7578. this._glRenderer = "Unknown renderer";
  7579. }
  7580. // Constants
  7581. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  7582. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  7583. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  7584. this._gl.DEPTH24_STENCIL8 = 35056;
  7585. // Extensions
  7586. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7587. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7588. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7589. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7590. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7591. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7592. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7593. 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');
  7594. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7595. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7596. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7597. this._caps.highPrecisionShaderSupported = true;
  7598. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7599. // Checks if some of the format renders first to allow the use of webgl inspector.
  7600. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7601. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7602. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7603. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7604. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7605. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7606. if (this._webGLVersion > 1) {
  7607. this._gl.HALF_FLOAT_OES = 0x140B;
  7608. }
  7609. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7610. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7611. // Vertex array object
  7612. if (this._webGLVersion > 1) {
  7613. this._caps.vertexArrayObject = true;
  7614. }
  7615. else {
  7616. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7617. if (vertexArrayObjectExtension != null) {
  7618. this._caps.vertexArrayObject = true;
  7619. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7620. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7621. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7622. }
  7623. else {
  7624. this._caps.vertexArrayObject = false;
  7625. }
  7626. }
  7627. // Instances count
  7628. if (this._webGLVersion > 1) {
  7629. this._caps.instancedArrays = true;
  7630. }
  7631. else {
  7632. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7633. if (instanceExtension != null) {
  7634. this._caps.instancedArrays = true;
  7635. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7636. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7637. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7638. }
  7639. else {
  7640. this._caps.instancedArrays = false;
  7641. }
  7642. }
  7643. // Intelligently add supported compressed formats in order to check for.
  7644. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7645. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7646. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7647. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7648. if (this._caps.astc)
  7649. this.texturesSupported.push('-astc.ktx');
  7650. if (this._caps.s3tc)
  7651. this.texturesSupported.push('-dxt.ktx');
  7652. if (this._caps.pvrtc)
  7653. this.texturesSupported.push('-pvrtc.ktx');
  7654. if (this._caps.etc2)
  7655. this.texturesSupported.push('-etc2.ktx');
  7656. if (this._caps.etc1)
  7657. this.texturesSupported.push('-etc1.ktx');
  7658. if (this._gl.getShaderPrecisionFormat) {
  7659. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7660. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7661. }
  7662. // Depth buffer
  7663. this.setDepthBuffer(true);
  7664. this.setDepthFunctionToLessOrEqual();
  7665. this.setDepthWrite(true);
  7666. if (canvas) {
  7667. // Fullscreen
  7668. this._onFullscreenChange = function () {
  7669. if (document.fullscreen !== undefined) {
  7670. _this.isFullscreen = document.fullscreen;
  7671. }
  7672. else if (document.mozFullScreen !== undefined) {
  7673. _this.isFullscreen = document.mozFullScreen;
  7674. }
  7675. else if (document.webkitIsFullScreen !== undefined) {
  7676. _this.isFullscreen = document.webkitIsFullScreen;
  7677. }
  7678. else if (document.msIsFullScreen !== undefined) {
  7679. _this.isFullscreen = document.msIsFullScreen;
  7680. }
  7681. // Pointer lock
  7682. if (_this.isFullscreen && _this._pointerLockRequested) {
  7683. canvas.requestPointerLock = canvas.requestPointerLock ||
  7684. canvas.msRequestPointerLock ||
  7685. canvas.mozRequestPointerLock ||
  7686. canvas.webkitRequestPointerLock;
  7687. if (canvas.requestPointerLock) {
  7688. canvas.requestPointerLock();
  7689. }
  7690. }
  7691. };
  7692. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7693. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7694. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7695. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7696. // Pointer lock
  7697. this._onPointerLockChange = function () {
  7698. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7699. document.webkitPointerLockElement === canvas ||
  7700. document.msPointerLockElement === canvas ||
  7701. document.pointerLockElement === canvas);
  7702. };
  7703. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7704. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7705. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7706. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7707. }
  7708. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7709. Engine.audioEngine = new BABYLON.AudioEngine();
  7710. }
  7711. // Prepare buffer pointers
  7712. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7713. this._currentBufferPointers[i] = new BufferPointer();
  7714. }
  7715. // Load WebVR Devices
  7716. if (options.autoEnableWebVR) {
  7717. this.initWebVR();
  7718. }
  7719. // Detect if we are running on a faulty buggy OS.
  7720. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7721. // Detect if we are running on a faulty buggy desktop OS.
  7722. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7723. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7724. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7725. }
  7726. Object.defineProperty(Engine, "LastCreatedEngine", {
  7727. get: function () {
  7728. if (Engine.Instances.length === 0) {
  7729. return null;
  7730. }
  7731. return Engine.Instances[Engine.Instances.length - 1];
  7732. },
  7733. enumerable: true,
  7734. configurable: true
  7735. });
  7736. Object.defineProperty(Engine, "LastCreatedScene", {
  7737. get: function () {
  7738. var lastCreatedEngine = Engine.LastCreatedEngine;
  7739. if (!lastCreatedEngine) {
  7740. return null;
  7741. }
  7742. if (lastCreatedEngine.scenes.length === 0) {
  7743. return null;
  7744. }
  7745. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7746. },
  7747. enumerable: true,
  7748. configurable: true
  7749. });
  7750. /**
  7751. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7752. */
  7753. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7754. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7755. var engine = Engine.Instances[engineIndex];
  7756. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7757. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7758. }
  7759. }
  7760. };
  7761. Object.defineProperty(Engine, "NEVER", {
  7762. get: function () {
  7763. return Engine._NEVER;
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. Object.defineProperty(Engine, "ALWAYS", {
  7769. get: function () {
  7770. return Engine._ALWAYS;
  7771. },
  7772. enumerable: true,
  7773. configurable: true
  7774. });
  7775. Object.defineProperty(Engine, "LESS", {
  7776. get: function () {
  7777. return Engine._LESS;
  7778. },
  7779. enumerable: true,
  7780. configurable: true
  7781. });
  7782. Object.defineProperty(Engine, "EQUAL", {
  7783. get: function () {
  7784. return Engine._EQUAL;
  7785. },
  7786. enumerable: true,
  7787. configurable: true
  7788. });
  7789. Object.defineProperty(Engine, "LEQUAL", {
  7790. get: function () {
  7791. return Engine._LEQUAL;
  7792. },
  7793. enumerable: true,
  7794. configurable: true
  7795. });
  7796. Object.defineProperty(Engine, "GREATER", {
  7797. get: function () {
  7798. return Engine._GREATER;
  7799. },
  7800. enumerable: true,
  7801. configurable: true
  7802. });
  7803. Object.defineProperty(Engine, "GEQUAL", {
  7804. get: function () {
  7805. return Engine._GEQUAL;
  7806. },
  7807. enumerable: true,
  7808. configurable: true
  7809. });
  7810. Object.defineProperty(Engine, "NOTEQUAL", {
  7811. get: function () {
  7812. return Engine._NOTEQUAL;
  7813. },
  7814. enumerable: true,
  7815. configurable: true
  7816. });
  7817. Object.defineProperty(Engine, "KEEP", {
  7818. get: function () {
  7819. return Engine._KEEP;
  7820. },
  7821. enumerable: true,
  7822. configurable: true
  7823. });
  7824. Object.defineProperty(Engine, "REPLACE", {
  7825. get: function () {
  7826. return Engine._REPLACE;
  7827. },
  7828. enumerable: true,
  7829. configurable: true
  7830. });
  7831. Object.defineProperty(Engine, "INCR", {
  7832. get: function () {
  7833. return Engine._INCR;
  7834. },
  7835. enumerable: true,
  7836. configurable: true
  7837. });
  7838. Object.defineProperty(Engine, "DECR", {
  7839. get: function () {
  7840. return Engine._DECR;
  7841. },
  7842. enumerable: true,
  7843. configurable: true
  7844. });
  7845. Object.defineProperty(Engine, "INVERT", {
  7846. get: function () {
  7847. return Engine._INVERT;
  7848. },
  7849. enumerable: true,
  7850. configurable: true
  7851. });
  7852. Object.defineProperty(Engine, "INCR_WRAP", {
  7853. get: function () {
  7854. return Engine._INCR_WRAP;
  7855. },
  7856. enumerable: true,
  7857. configurable: true
  7858. });
  7859. Object.defineProperty(Engine, "DECR_WRAP", {
  7860. get: function () {
  7861. return Engine._DECR_WRAP;
  7862. },
  7863. enumerable: true,
  7864. configurable: true
  7865. });
  7866. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7867. get: function () {
  7868. return Engine._ALPHA_DISABLE;
  7869. },
  7870. enumerable: true,
  7871. configurable: true
  7872. });
  7873. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7874. get: function () {
  7875. return Engine._ALPHA_ONEONE;
  7876. },
  7877. enumerable: true,
  7878. configurable: true
  7879. });
  7880. Object.defineProperty(Engine, "ALPHA_ADD", {
  7881. get: function () {
  7882. return Engine._ALPHA_ADD;
  7883. },
  7884. enumerable: true,
  7885. configurable: true
  7886. });
  7887. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7888. get: function () {
  7889. return Engine._ALPHA_COMBINE;
  7890. },
  7891. enumerable: true,
  7892. configurable: true
  7893. });
  7894. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7895. get: function () {
  7896. return Engine._ALPHA_SUBTRACT;
  7897. },
  7898. enumerable: true,
  7899. configurable: true
  7900. });
  7901. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7902. get: function () {
  7903. return Engine._ALPHA_MULTIPLY;
  7904. },
  7905. enumerable: true,
  7906. configurable: true
  7907. });
  7908. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7909. get: function () {
  7910. return Engine._ALPHA_MAXIMIZED;
  7911. },
  7912. enumerable: true,
  7913. configurable: true
  7914. });
  7915. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7916. get: function () {
  7917. return Engine._ALPHA_PREMULTIPLIED;
  7918. },
  7919. enumerable: true,
  7920. configurable: true
  7921. });
  7922. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7923. get: function () {
  7924. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7925. },
  7926. enumerable: true,
  7927. configurable: true
  7928. });
  7929. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7930. get: function () {
  7931. return Engine._ALPHA_INTERPOLATE;
  7932. },
  7933. enumerable: true,
  7934. configurable: true
  7935. });
  7936. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7937. get: function () {
  7938. return Engine._ALPHA_SCREENMODE;
  7939. },
  7940. enumerable: true,
  7941. configurable: true
  7942. });
  7943. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7944. get: function () {
  7945. return Engine._DELAYLOADSTATE_NONE;
  7946. },
  7947. enumerable: true,
  7948. configurable: true
  7949. });
  7950. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7951. get: function () {
  7952. return Engine._DELAYLOADSTATE_LOADED;
  7953. },
  7954. enumerable: true,
  7955. configurable: true
  7956. });
  7957. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7958. get: function () {
  7959. return Engine._DELAYLOADSTATE_LOADING;
  7960. },
  7961. enumerable: true,
  7962. configurable: true
  7963. });
  7964. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7965. get: function () {
  7966. return Engine._DELAYLOADSTATE_NOTLOADED;
  7967. },
  7968. enumerable: true,
  7969. configurable: true
  7970. });
  7971. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7972. get: function () {
  7973. return Engine._TEXTUREFORMAT_ALPHA;
  7974. },
  7975. enumerable: true,
  7976. configurable: true
  7977. });
  7978. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7979. get: function () {
  7980. return Engine._TEXTUREFORMAT_LUMINANCE;
  7981. },
  7982. enumerable: true,
  7983. configurable: true
  7984. });
  7985. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7986. get: function () {
  7987. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7988. },
  7989. enumerable: true,
  7990. configurable: true
  7991. });
  7992. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7993. get: function () {
  7994. return Engine._TEXTUREFORMAT_RGB;
  7995. },
  7996. enumerable: true,
  7997. configurable: true
  7998. });
  7999. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8000. get: function () {
  8001. return Engine._TEXTUREFORMAT_RGBA;
  8002. },
  8003. enumerable: true,
  8004. configurable: true
  8005. });
  8006. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8007. get: function () {
  8008. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8009. },
  8010. enumerable: true,
  8011. configurable: true
  8012. });
  8013. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8014. get: function () {
  8015. return Engine._TEXTURETYPE_FLOAT;
  8016. },
  8017. enumerable: true,
  8018. configurable: true
  8019. });
  8020. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8021. get: function () {
  8022. return Engine._TEXTURETYPE_HALF_FLOAT;
  8023. },
  8024. enumerable: true,
  8025. configurable: true
  8026. });
  8027. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8028. get: function () {
  8029. return Engine._SCALEMODE_FLOOR;
  8030. },
  8031. enumerable: true,
  8032. configurable: true
  8033. });
  8034. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8035. get: function () {
  8036. return Engine._SCALEMODE_NEAREST;
  8037. },
  8038. enumerable: true,
  8039. configurable: true
  8040. });
  8041. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8042. get: function () {
  8043. return Engine._SCALEMODE_CEILING;
  8044. },
  8045. enumerable: true,
  8046. configurable: true
  8047. });
  8048. Object.defineProperty(Engine, "Version", {
  8049. get: function () {
  8050. return "3.1-alpha";
  8051. },
  8052. enumerable: true,
  8053. configurable: true
  8054. });
  8055. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8056. get: function () {
  8057. return this._webGLVersion < 2 || this.forcePOTTextures;
  8058. },
  8059. enumerable: true,
  8060. configurable: true
  8061. });
  8062. Object.defineProperty(Engine.prototype, "badOS", {
  8063. get: function () {
  8064. return this._badOS;
  8065. },
  8066. enumerable: true,
  8067. configurable: true
  8068. });
  8069. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8070. get: function () {
  8071. return this._badDesktopOS;
  8072. },
  8073. enumerable: true,
  8074. configurable: true
  8075. });
  8076. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8077. get: function () {
  8078. return this._performanceMonitor;
  8079. },
  8080. enumerable: true,
  8081. configurable: true
  8082. });
  8083. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8084. get: function () {
  8085. return this._texturesSupported;
  8086. },
  8087. enumerable: true,
  8088. configurable: true
  8089. });
  8090. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8091. get: function () {
  8092. return this._textureFormatInUse;
  8093. },
  8094. enumerable: true,
  8095. configurable: true
  8096. });
  8097. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8098. // Empty texture
  8099. get: function () {
  8100. if (!this._emptyTexture) {
  8101. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8102. }
  8103. return this._emptyTexture;
  8104. },
  8105. enumerable: true,
  8106. configurable: true
  8107. });
  8108. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8109. get: function () {
  8110. if (!this._emptyCubeTexture) {
  8111. var faceData = new Uint8Array(4);
  8112. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8113. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8114. }
  8115. return this._emptyCubeTexture;
  8116. },
  8117. enumerable: true,
  8118. configurable: true
  8119. });
  8120. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8121. get: function () {
  8122. return this._webGLVersion;
  8123. },
  8124. enumerable: true,
  8125. configurable: true
  8126. });
  8127. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8128. /**
  8129. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8130. */
  8131. get: function () {
  8132. return this._isStencilEnable;
  8133. },
  8134. enumerable: true,
  8135. configurable: true
  8136. });
  8137. Engine.prototype._prepareWorkingCanvas = function () {
  8138. if (this._workingCanvas) {
  8139. return;
  8140. }
  8141. this._workingCanvas = document.createElement("canvas");
  8142. this._workingContext = this._workingCanvas.getContext("2d");
  8143. };
  8144. Engine.prototype.resetTextureCache = function () {
  8145. for (var index = 0; index < this._maxTextureChannels; index++) {
  8146. this._activeTexturesCache[index] = null;
  8147. }
  8148. };
  8149. Engine.prototype.isDeterministicLockStep = function () {
  8150. return this._deterministicLockstep;
  8151. };
  8152. Engine.prototype.getLockstepMaxSteps = function () {
  8153. return this._lockstepMaxSteps;
  8154. };
  8155. Engine.prototype.getGlInfo = function () {
  8156. return {
  8157. vendor: this._glVendor,
  8158. renderer: this._glRenderer,
  8159. version: this._glVersion
  8160. };
  8161. };
  8162. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8163. if (useScreen === void 0) { useScreen = false; }
  8164. var viewport = camera.viewport;
  8165. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8166. };
  8167. Engine.prototype.getRenderWidth = function (useScreen) {
  8168. if (useScreen === void 0) { useScreen = false; }
  8169. if (!useScreen && this._currentRenderTarget) {
  8170. return this._currentRenderTarget._width;
  8171. }
  8172. return this._gl.drawingBufferWidth;
  8173. };
  8174. Engine.prototype.getRenderHeight = function (useScreen) {
  8175. if (useScreen === void 0) { useScreen = false; }
  8176. if (!useScreen && this._currentRenderTarget) {
  8177. return this._currentRenderTarget._height;
  8178. }
  8179. return this._gl.drawingBufferHeight;
  8180. };
  8181. Engine.prototype.getRenderingCanvas = function () {
  8182. return this._renderingCanvas;
  8183. };
  8184. Engine.prototype.getRenderingCanvasClientRect = function () {
  8185. return this._renderingCanvas.getBoundingClientRect();
  8186. };
  8187. Engine.prototype.setHardwareScalingLevel = function (level) {
  8188. this._hardwareScalingLevel = level;
  8189. this.resize();
  8190. };
  8191. Engine.prototype.getHardwareScalingLevel = function () {
  8192. return this._hardwareScalingLevel;
  8193. };
  8194. Engine.prototype.getLoadedTexturesCache = function () {
  8195. return this._loadedTexturesCache;
  8196. };
  8197. Engine.prototype.getCaps = function () {
  8198. return this._caps;
  8199. };
  8200. Object.defineProperty(Engine.prototype, "drawCalls", {
  8201. /** The number of draw calls submitted last frame */
  8202. get: function () {
  8203. return this._drawCalls.current;
  8204. },
  8205. enumerable: true,
  8206. configurable: true
  8207. });
  8208. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8209. get: function () {
  8210. return this._drawCalls;
  8211. },
  8212. enumerable: true,
  8213. configurable: true
  8214. });
  8215. Engine.prototype.getDepthFunction = function () {
  8216. return this._depthCullingState.depthFunc;
  8217. };
  8218. Engine.prototype.setDepthFunction = function (depthFunc) {
  8219. this._depthCullingState.depthFunc = depthFunc;
  8220. };
  8221. Engine.prototype.setDepthFunctionToGreater = function () {
  8222. this._depthCullingState.depthFunc = this._gl.GREATER;
  8223. };
  8224. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8225. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8226. };
  8227. Engine.prototype.setDepthFunctionToLess = function () {
  8228. this._depthCullingState.depthFunc = this._gl.LESS;
  8229. };
  8230. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8231. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8232. };
  8233. Engine.prototype.getStencilBuffer = function () {
  8234. return this._stencilState.stencilTest;
  8235. };
  8236. Engine.prototype.setStencilBuffer = function (enable) {
  8237. this._stencilState.stencilTest = enable;
  8238. };
  8239. Engine.prototype.getStencilMask = function () {
  8240. return this._stencilState.stencilMask;
  8241. };
  8242. Engine.prototype.setStencilMask = function (mask) {
  8243. this._stencilState.stencilMask = mask;
  8244. };
  8245. Engine.prototype.getStencilFunction = function () {
  8246. return this._stencilState.stencilFunc;
  8247. };
  8248. Engine.prototype.getStencilFunctionReference = function () {
  8249. return this._stencilState.stencilFuncRef;
  8250. };
  8251. Engine.prototype.getStencilFunctionMask = function () {
  8252. return this._stencilState.stencilFuncMask;
  8253. };
  8254. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8255. this._stencilState.stencilFunc = stencilFunc;
  8256. };
  8257. Engine.prototype.setStencilFunctionReference = function (reference) {
  8258. this._stencilState.stencilFuncRef = reference;
  8259. };
  8260. Engine.prototype.setStencilFunctionMask = function (mask) {
  8261. this._stencilState.stencilFuncMask = mask;
  8262. };
  8263. Engine.prototype.getStencilOperationFail = function () {
  8264. return this._stencilState.stencilOpStencilFail;
  8265. };
  8266. Engine.prototype.getStencilOperationDepthFail = function () {
  8267. return this._stencilState.stencilOpDepthFail;
  8268. };
  8269. Engine.prototype.getStencilOperationPass = function () {
  8270. return this._stencilState.stencilOpStencilDepthPass;
  8271. };
  8272. Engine.prototype.setStencilOperationFail = function (operation) {
  8273. this._stencilState.stencilOpStencilFail = operation;
  8274. };
  8275. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8276. this._stencilState.stencilOpDepthFail = operation;
  8277. };
  8278. Engine.prototype.setStencilOperationPass = function (operation) {
  8279. this._stencilState.stencilOpStencilDepthPass = operation;
  8280. };
  8281. Engine.prototype.setDitheringState = function (value) {
  8282. if (value) {
  8283. this._gl.enable(this._gl.DITHER);
  8284. }
  8285. else {
  8286. this._gl.disable(this._gl.DITHER);
  8287. }
  8288. };
  8289. /**
  8290. * stop executing a render loop function and remove it from the execution array
  8291. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8292. */
  8293. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8294. if (!renderFunction) {
  8295. this._activeRenderLoops = [];
  8296. return;
  8297. }
  8298. var index = this._activeRenderLoops.indexOf(renderFunction);
  8299. if (index >= 0) {
  8300. this._activeRenderLoops.splice(index, 1);
  8301. }
  8302. };
  8303. Engine.prototype._renderLoop = function () {
  8304. var shouldRender = true;
  8305. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8306. shouldRender = false;
  8307. }
  8308. if (shouldRender) {
  8309. // Start new frame
  8310. this.beginFrame();
  8311. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8312. var renderFunction = this._activeRenderLoops[index];
  8313. renderFunction();
  8314. }
  8315. // Present
  8316. this.endFrame();
  8317. }
  8318. if (this._activeRenderLoops.length > 0) {
  8319. // Register new frame
  8320. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8321. }
  8322. else {
  8323. this._renderingQueueLaunched = false;
  8324. }
  8325. };
  8326. /**
  8327. * Register and execute a render loop. The engine can have more than one render function.
  8328. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8329. * @example
  8330. * engine.runRenderLoop(function () {
  8331. * scene.render()
  8332. * })
  8333. */
  8334. Engine.prototype.runRenderLoop = function (renderFunction) {
  8335. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8336. return;
  8337. }
  8338. this._activeRenderLoops.push(renderFunction);
  8339. if (!this._renderingQueueLaunched) {
  8340. this._renderingQueueLaunched = true;
  8341. this._bindedRenderFunction = this._renderLoop.bind(this);
  8342. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8343. }
  8344. };
  8345. /**
  8346. * Toggle full screen mode.
  8347. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8348. * @param {any} options - an options object to be sent to the requestFullscreen function
  8349. */
  8350. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8351. if (this.isFullscreen) {
  8352. BABYLON.Tools.ExitFullscreen();
  8353. }
  8354. else {
  8355. this._pointerLockRequested = requestPointerLock;
  8356. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8357. }
  8358. };
  8359. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8360. if (stencil === void 0) { stencil = false; }
  8361. this.applyStates();
  8362. var mode = 0;
  8363. if (backBuffer && color) {
  8364. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8365. mode |= this._gl.COLOR_BUFFER_BIT;
  8366. }
  8367. if (depth) {
  8368. this._gl.clearDepth(1.0);
  8369. mode |= this._gl.DEPTH_BUFFER_BIT;
  8370. }
  8371. if (stencil) {
  8372. this._gl.clearStencil(0);
  8373. mode |= this._gl.STENCIL_BUFFER_BIT;
  8374. }
  8375. this._gl.clear(mode);
  8376. };
  8377. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8378. var gl = this._gl;
  8379. // Save state
  8380. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8381. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8382. // Change state
  8383. gl.enable(gl.SCISSOR_TEST);
  8384. gl.scissor(x, y, width, height);
  8385. // Clear
  8386. this.clear(clearColor, true, true, true);
  8387. // Restore state
  8388. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8389. if (curScissor === true) {
  8390. gl.enable(gl.SCISSOR_TEST);
  8391. }
  8392. else {
  8393. gl.disable(gl.SCISSOR_TEST);
  8394. }
  8395. };
  8396. /**
  8397. * Set the WebGL's viewport
  8398. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8399. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8400. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8401. */
  8402. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8403. var width = requiredWidth || this.getRenderWidth();
  8404. var height = requiredHeight || this.getRenderHeight();
  8405. var x = viewport.x || 0;
  8406. var y = viewport.y || 0;
  8407. this._cachedViewport = viewport;
  8408. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8409. };
  8410. /**
  8411. * Directly set the WebGL Viewport
  8412. * The x, y, width & height are directly passed to the WebGL call
  8413. * @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.
  8414. */
  8415. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8416. var currentViewport = this._cachedViewport;
  8417. this._cachedViewport = null;
  8418. this._gl.viewport(x, y, width, height);
  8419. return currentViewport;
  8420. };
  8421. Engine.prototype.beginFrame = function () {
  8422. this._measureFps();
  8423. };
  8424. Engine.prototype.endFrame = function () {
  8425. //force a flush in case we are using a bad OS.
  8426. if (this._badOS) {
  8427. this.flushFramebuffer();
  8428. }
  8429. //submit frame to the vr device, if enabled
  8430. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8431. this._vrDisplayEnabled.submitFrame();
  8432. }
  8433. };
  8434. /**
  8435. * resize the view according to the canvas' size.
  8436. * @example
  8437. * window.addEventListener("resize", function () {
  8438. * engine.resize();
  8439. * });
  8440. */
  8441. Engine.prototype.resize = function () {
  8442. // We're not resizing the size of the canvas while in VR mode & presenting
  8443. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8444. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8445. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8446. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8447. }
  8448. };
  8449. /**
  8450. * force a specific size of the canvas
  8451. * @param {number} width - the new canvas' width
  8452. * @param {number} height - the new canvas' height
  8453. */
  8454. Engine.prototype.setSize = function (width, height) {
  8455. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8456. return;
  8457. }
  8458. this._renderingCanvas.width = width;
  8459. this._renderingCanvas.height = height;
  8460. for (var index = 0; index < this.scenes.length; index++) {
  8461. var scene = this.scenes[index];
  8462. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8463. var cam = scene.cameras[camIndex];
  8464. cam._currentRenderId = 0;
  8465. }
  8466. }
  8467. if (this.onResizeObservable.hasObservers) {
  8468. this.onResizeObservable.notifyObservers(this);
  8469. }
  8470. };
  8471. //WebVR functions
  8472. Engine.prototype.isVRDevicePresent = function (callback) {
  8473. this.getVRDevice(null, function (device) {
  8474. callback(device !== null);
  8475. });
  8476. };
  8477. Engine.prototype.getVRDevice = function (name, callback) {
  8478. if (!this.vrDisplaysPromise) {
  8479. callback(null);
  8480. return;
  8481. }
  8482. this.vrDisplaysPromise.then(function (devices) {
  8483. if (devices.length > 0) {
  8484. if (name) {
  8485. var found = devices.some(function (device) {
  8486. if (device.displayName === name) {
  8487. callback(device);
  8488. return true;
  8489. }
  8490. else {
  8491. return false;
  8492. }
  8493. });
  8494. if (!found) {
  8495. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8496. callback(devices[0]);
  8497. }
  8498. }
  8499. else {
  8500. //choose the first one
  8501. callback(devices[0]);
  8502. }
  8503. }
  8504. else {
  8505. BABYLON.Tools.Error("No WebVR devices found!");
  8506. callback(null);
  8507. }
  8508. });
  8509. };
  8510. Engine.prototype.initWebVR = function () {
  8511. if (!this.vrDisplaysPromise) {
  8512. this._getVRDisplays();
  8513. }
  8514. };
  8515. Engine.prototype.enableVR = function (vrDevice) {
  8516. this._vrDisplayEnabled = vrDevice;
  8517. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8518. };
  8519. Engine.prototype.disableVR = function () {
  8520. if (this._vrDisplayEnabled) {
  8521. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8522. }
  8523. };
  8524. Engine.prototype._getVRDisplays = function () {
  8525. var _this = this;
  8526. var getWebVRDevices = function (devices) {
  8527. var size = devices.length;
  8528. var i = 0;
  8529. _this._vrDisplays = devices.filter(function (device) {
  8530. return devices[i] instanceof VRDisplay;
  8531. });
  8532. return _this._vrDisplays;
  8533. };
  8534. //using a key due to typescript
  8535. if (navigator.getVRDisplays) {
  8536. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8537. }
  8538. };
  8539. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8540. if (this._currentRenderTarget) {
  8541. this.unBindFramebuffer(this._currentRenderTarget);
  8542. }
  8543. this._currentRenderTarget = texture;
  8544. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8545. var gl = this._gl;
  8546. if (texture.isCube) {
  8547. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8548. }
  8549. if (this._cachedViewport && !forceFullscreenViewport) {
  8550. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8551. }
  8552. else {
  8553. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8554. }
  8555. this.wipeCaches();
  8556. };
  8557. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8558. if (this._currentFramebuffer !== framebuffer) {
  8559. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8560. this._currentFramebuffer = framebuffer;
  8561. }
  8562. };
  8563. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8564. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8565. this._currentRenderTarget = null;
  8566. // If MSAA, we need to bitblt back to main texture
  8567. var gl = this._gl;
  8568. if (texture._MSAAFramebuffer) {
  8569. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8570. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8571. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8572. }
  8573. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8574. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8575. gl.generateMipmap(gl.TEXTURE_2D);
  8576. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8577. }
  8578. if (onBeforeUnbind) {
  8579. if (texture._MSAAFramebuffer) {
  8580. // Bind the correct framebuffer
  8581. this.bindUnboundFramebuffer(texture._framebuffer);
  8582. }
  8583. onBeforeUnbind();
  8584. }
  8585. this.bindUnboundFramebuffer(null);
  8586. };
  8587. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8588. if (texture.generateMipMaps) {
  8589. var gl = this._gl;
  8590. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8591. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8592. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8593. }
  8594. };
  8595. Engine.prototype.flushFramebuffer = function () {
  8596. this._gl.flush();
  8597. };
  8598. Engine.prototype.restoreDefaultFramebuffer = function () {
  8599. if (this._currentRenderTarget) {
  8600. this.unBindFramebuffer(this._currentRenderTarget);
  8601. }
  8602. else {
  8603. this.bindUnboundFramebuffer(null);
  8604. }
  8605. if (this._cachedViewport) {
  8606. this.setViewport(this._cachedViewport);
  8607. }
  8608. this.wipeCaches();
  8609. };
  8610. // UBOs
  8611. Engine.prototype.createUniformBuffer = function (elements) {
  8612. var ubo = this._gl.createBuffer();
  8613. this.bindUniformBuffer(ubo);
  8614. if (elements instanceof Float32Array) {
  8615. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8616. }
  8617. else {
  8618. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8619. }
  8620. this.bindUniformBuffer(null);
  8621. ubo.references = 1;
  8622. return ubo;
  8623. };
  8624. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8625. var ubo = this._gl.createBuffer();
  8626. this.bindUniformBuffer(ubo);
  8627. if (elements instanceof Float32Array) {
  8628. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8629. }
  8630. else {
  8631. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8632. }
  8633. this.bindUniformBuffer(null);
  8634. ubo.references = 1;
  8635. return ubo;
  8636. };
  8637. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8638. this.bindUniformBuffer(uniformBuffer);
  8639. if (offset === undefined) {
  8640. offset = 0;
  8641. }
  8642. if (count === undefined) {
  8643. if (elements instanceof Float32Array) {
  8644. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8645. }
  8646. else {
  8647. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8648. }
  8649. }
  8650. else {
  8651. if (elements instanceof Float32Array) {
  8652. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8653. }
  8654. else {
  8655. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8656. }
  8657. }
  8658. this.bindUniformBuffer(null);
  8659. };
  8660. // VBOs
  8661. Engine.prototype._resetVertexBufferBinding = function () {
  8662. this.bindArrayBuffer(null);
  8663. this._cachedVertexBuffers = null;
  8664. };
  8665. Engine.prototype.createVertexBuffer = function (vertices) {
  8666. var vbo = this._gl.createBuffer();
  8667. this.bindArrayBuffer(vbo);
  8668. if (vertices instanceof Float32Array) {
  8669. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8670. }
  8671. else {
  8672. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8673. }
  8674. this._resetVertexBufferBinding();
  8675. vbo.references = 1;
  8676. return vbo;
  8677. };
  8678. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8679. var vbo = this._gl.createBuffer();
  8680. this.bindArrayBuffer(vbo);
  8681. if (vertices instanceof Float32Array) {
  8682. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8683. }
  8684. else {
  8685. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8686. }
  8687. this._resetVertexBufferBinding();
  8688. vbo.references = 1;
  8689. return vbo;
  8690. };
  8691. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8692. this.bindArrayBuffer(vertexBuffer);
  8693. if (offset === undefined) {
  8694. offset = 0;
  8695. }
  8696. if (count === undefined) {
  8697. if (vertices instanceof Float32Array) {
  8698. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8699. }
  8700. else {
  8701. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8702. }
  8703. }
  8704. else {
  8705. if (vertices instanceof Float32Array) {
  8706. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8707. }
  8708. else {
  8709. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8710. }
  8711. }
  8712. this._resetVertexBufferBinding();
  8713. };
  8714. Engine.prototype._resetIndexBufferBinding = function () {
  8715. this.bindIndexBuffer(null);
  8716. this._cachedIndexBuffer = null;
  8717. };
  8718. Engine.prototype.createIndexBuffer = function (indices) {
  8719. var vbo = this._gl.createBuffer();
  8720. this.bindIndexBuffer(vbo);
  8721. // Check for 32 bits indices
  8722. var arrayBuffer;
  8723. var need32Bits = false;
  8724. if (indices instanceof Uint16Array) {
  8725. arrayBuffer = indices;
  8726. }
  8727. else {
  8728. //check 32 bit support
  8729. if (this._caps.uintIndices) {
  8730. if (indices instanceof Uint32Array) {
  8731. arrayBuffer = indices;
  8732. need32Bits = true;
  8733. }
  8734. else {
  8735. //number[] or Int32Array, check if 32 bit is necessary
  8736. for (var index = 0; index < indices.length; index++) {
  8737. if (indices[index] > 65535) {
  8738. need32Bits = true;
  8739. break;
  8740. }
  8741. }
  8742. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8743. }
  8744. }
  8745. else {
  8746. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8747. arrayBuffer = new Uint16Array(indices);
  8748. }
  8749. }
  8750. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8751. this._resetIndexBufferBinding();
  8752. vbo.references = 1;
  8753. vbo.is32Bits = need32Bits;
  8754. return vbo;
  8755. };
  8756. Engine.prototype.bindArrayBuffer = function (buffer) {
  8757. if (!this._vaoRecordInProgress) {
  8758. this._unbindVertexArrayObject();
  8759. }
  8760. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8761. };
  8762. Engine.prototype.bindUniformBuffer = function (buffer) {
  8763. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8764. };
  8765. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8766. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8767. };
  8768. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8769. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8770. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8771. };
  8772. ;
  8773. Engine.prototype.bindIndexBuffer = function (buffer) {
  8774. if (!this._vaoRecordInProgress) {
  8775. this._unbindVertexArrayObject();
  8776. }
  8777. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8778. };
  8779. Engine.prototype.bindBuffer = function (buffer, target) {
  8780. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8781. this._gl.bindBuffer(target, buffer);
  8782. this._currentBoundBuffer[target] = buffer;
  8783. }
  8784. };
  8785. Engine.prototype.updateArrayBuffer = function (data) {
  8786. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8787. };
  8788. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8789. var pointer = this._currentBufferPointers[indx];
  8790. var changed = false;
  8791. if (!pointer.active) {
  8792. changed = true;
  8793. pointer.active = true;
  8794. pointer.index = indx;
  8795. pointer.size = size;
  8796. pointer.type = type;
  8797. pointer.normalized = normalized;
  8798. pointer.stride = stride;
  8799. pointer.offset = offset;
  8800. pointer.buffer = buffer;
  8801. }
  8802. else {
  8803. if (pointer.buffer !== buffer) {
  8804. pointer.buffer = buffer;
  8805. changed = true;
  8806. }
  8807. if (pointer.size !== size) {
  8808. pointer.size = size;
  8809. changed = true;
  8810. }
  8811. if (pointer.type !== type) {
  8812. pointer.type = type;
  8813. changed = true;
  8814. }
  8815. if (pointer.normalized !== normalized) {
  8816. pointer.normalized = normalized;
  8817. changed = true;
  8818. }
  8819. if (pointer.stride !== stride) {
  8820. pointer.stride = stride;
  8821. changed = true;
  8822. }
  8823. if (pointer.offset !== offset) {
  8824. pointer.offset = offset;
  8825. changed = true;
  8826. }
  8827. }
  8828. if (changed || this._vaoRecordInProgress) {
  8829. this.bindArrayBuffer(buffer);
  8830. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8831. }
  8832. };
  8833. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8834. if (indexBuffer == null) {
  8835. return;
  8836. }
  8837. if (this._cachedIndexBuffer !== indexBuffer) {
  8838. this._cachedIndexBuffer = indexBuffer;
  8839. this.bindIndexBuffer(indexBuffer);
  8840. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8841. }
  8842. };
  8843. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8844. var attributes = effect.getAttributesNames();
  8845. if (!this._vaoRecordInProgress) {
  8846. this._unbindVertexArrayObject();
  8847. }
  8848. this.unbindAllAttributes();
  8849. for (var index = 0; index < attributes.length; index++) {
  8850. var order = effect.getAttributeLocation(index);
  8851. if (order >= 0) {
  8852. var vertexBuffer = vertexBuffers[attributes[index]];
  8853. if (!vertexBuffer) {
  8854. continue;
  8855. }
  8856. this._gl.enableVertexAttribArray(order);
  8857. if (!this._vaoRecordInProgress) {
  8858. this._vertexAttribArraysEnabled[order] = true;
  8859. }
  8860. var buffer = vertexBuffer.getBuffer();
  8861. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8862. if (vertexBuffer.getIsInstanced()) {
  8863. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8864. if (!this._vaoRecordInProgress) {
  8865. this._currentInstanceLocations.push(order);
  8866. this._currentInstanceBuffers.push(buffer);
  8867. }
  8868. }
  8869. }
  8870. }
  8871. };
  8872. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8873. var vao = this._gl.createVertexArray();
  8874. this._vaoRecordInProgress = true;
  8875. this._gl.bindVertexArray(vao);
  8876. this._mustWipeVertexAttributes = true;
  8877. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8878. this.bindIndexBuffer(indexBuffer);
  8879. this._vaoRecordInProgress = false;
  8880. this._gl.bindVertexArray(null);
  8881. return vao;
  8882. };
  8883. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8884. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8885. this._cachedVertexArrayObject = vertexArrayObject;
  8886. this._gl.bindVertexArray(vertexArrayObject);
  8887. this._cachedVertexBuffers = null;
  8888. this._cachedIndexBuffer = null;
  8889. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8890. this._mustWipeVertexAttributes = true;
  8891. }
  8892. };
  8893. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8894. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8895. this._cachedVertexBuffers = vertexBuffer;
  8896. this._cachedEffectForVertexBuffers = effect;
  8897. var attributesCount = effect.getAttributesCount();
  8898. this._unbindVertexArrayObject();
  8899. this.unbindAllAttributes();
  8900. var offset = 0;
  8901. for (var index = 0; index < attributesCount; index++) {
  8902. if (index < vertexDeclaration.length) {
  8903. var order = effect.getAttributeLocation(index);
  8904. if (order >= 0) {
  8905. this._gl.enableVertexAttribArray(order);
  8906. this._vertexAttribArraysEnabled[order] = true;
  8907. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8908. }
  8909. offset += vertexDeclaration[index] * 4;
  8910. }
  8911. }
  8912. }
  8913. this._bindIndexBufferWithCache(indexBuffer);
  8914. };
  8915. Engine.prototype._unbindVertexArrayObject = function () {
  8916. if (!this._cachedVertexArrayObject) {
  8917. return;
  8918. }
  8919. this._cachedVertexArrayObject = null;
  8920. this._gl.bindVertexArray(null);
  8921. };
  8922. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8923. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8924. this._cachedVertexBuffers = vertexBuffers;
  8925. this._cachedEffectForVertexBuffers = effect;
  8926. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8927. }
  8928. this._bindIndexBufferWithCache(indexBuffer);
  8929. };
  8930. Engine.prototype.unbindInstanceAttributes = function () {
  8931. var boundBuffer;
  8932. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8933. var instancesBuffer = this._currentInstanceBuffers[i];
  8934. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8935. boundBuffer = instancesBuffer;
  8936. this.bindArrayBuffer(instancesBuffer);
  8937. }
  8938. var offsetLocation = this._currentInstanceLocations[i];
  8939. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8940. }
  8941. this._currentInstanceBuffers.length = 0;
  8942. this._currentInstanceLocations.length = 0;
  8943. };
  8944. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8945. this._gl.deleteVertexArray(vao);
  8946. };
  8947. Engine.prototype._releaseBuffer = function (buffer) {
  8948. buffer.references--;
  8949. if (buffer.references === 0) {
  8950. this._gl.deleteBuffer(buffer);
  8951. return true;
  8952. }
  8953. return false;
  8954. };
  8955. Engine.prototype.createInstancesBuffer = function (capacity) {
  8956. var buffer = this._gl.createBuffer();
  8957. buffer.capacity = capacity;
  8958. this.bindArrayBuffer(buffer);
  8959. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8960. return buffer;
  8961. };
  8962. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8963. this._gl.deleteBuffer(buffer);
  8964. };
  8965. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8966. this.bindArrayBuffer(instancesBuffer);
  8967. if (data) {
  8968. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8969. }
  8970. if (offsetLocations[0].index !== undefined) {
  8971. var stride = 0;
  8972. for (var i = 0; i < offsetLocations.length; i++) {
  8973. var ai = offsetLocations[i];
  8974. stride += ai.attributeSize * 4;
  8975. }
  8976. for (var i = 0; i < offsetLocations.length; i++) {
  8977. var ai = offsetLocations[i];
  8978. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8979. this._gl.enableVertexAttribArray(ai.index);
  8980. this._vertexAttribArraysEnabled[ai.index] = true;
  8981. }
  8982. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8983. this._gl.vertexAttribDivisor(ai.index, 1);
  8984. this._currentInstanceLocations.push(ai.index);
  8985. this._currentInstanceBuffers.push(instancesBuffer);
  8986. }
  8987. }
  8988. else {
  8989. for (var index = 0; index < 4; index++) {
  8990. var offsetLocation = offsetLocations[index];
  8991. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8992. this._gl.enableVertexAttribArray(offsetLocation);
  8993. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8994. }
  8995. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8996. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8997. this._currentInstanceLocations.push(offsetLocation);
  8998. this._currentInstanceBuffers.push(instancesBuffer);
  8999. }
  9000. }
  9001. };
  9002. Engine.prototype.applyStates = function () {
  9003. this._depthCullingState.apply(this._gl);
  9004. this._stencilState.apply(this._gl);
  9005. this._alphaState.apply(this._gl);
  9006. };
  9007. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9008. // Apply states
  9009. this.applyStates();
  9010. this._drawCalls.addCount(1, false);
  9011. // Render
  9012. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9013. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9014. if (instancesCount) {
  9015. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9016. return;
  9017. }
  9018. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9019. };
  9020. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9021. // Apply states
  9022. this.applyStates();
  9023. this._drawCalls.addCount(1, false);
  9024. if (instancesCount) {
  9025. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9026. return;
  9027. }
  9028. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9029. };
  9030. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9031. // Apply states
  9032. this.applyStates();
  9033. this._drawCalls.addCount(1, false);
  9034. if (instancesCount) {
  9035. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9036. return;
  9037. }
  9038. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9039. };
  9040. // Shaders
  9041. Engine.prototype._releaseEffect = function (effect) {
  9042. if (this._compiledEffects[effect._key]) {
  9043. delete this._compiledEffects[effect._key];
  9044. if (effect.getProgram()) {
  9045. this._gl.deleteProgram(effect.getProgram());
  9046. }
  9047. }
  9048. };
  9049. /**
  9050. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9051. * @param samplers An array of string used to represent textures
  9052. */
  9053. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9054. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9055. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9056. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9057. if (this._compiledEffects[name]) {
  9058. var compiledEffect = this._compiledEffects[name];
  9059. if (onCompiled && compiledEffect.isReady()) {
  9060. onCompiled(compiledEffect);
  9061. }
  9062. return compiledEffect;
  9063. }
  9064. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9065. effect._key = name;
  9066. this._compiledEffects[name] = effect;
  9067. return effect;
  9068. };
  9069. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9070. if (uniformsNames === void 0) { uniformsNames = []; }
  9071. if (samplers === void 0) { samplers = []; }
  9072. if (defines === void 0) { defines = ""; }
  9073. return this.createEffect({
  9074. vertex: "particles",
  9075. fragmentElement: fragmentName
  9076. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9077. };
  9078. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9079. context = context || this._gl;
  9080. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9081. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9082. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9083. var shaderProgram = context.createProgram();
  9084. context.attachShader(shaderProgram, vertexShader);
  9085. context.attachShader(shaderProgram, fragmentShader);
  9086. context.linkProgram(shaderProgram);
  9087. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9088. if (!linked) {
  9089. context.validateProgram(shaderProgram);
  9090. var error = context.getProgramInfoLog(shaderProgram);
  9091. if (error) {
  9092. throw new Error(error);
  9093. }
  9094. }
  9095. context.deleteShader(vertexShader);
  9096. context.deleteShader(fragmentShader);
  9097. return shaderProgram;
  9098. };
  9099. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9100. var results = [];
  9101. for (var index = 0; index < uniformsNames.length; index++) {
  9102. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9103. }
  9104. return results;
  9105. };
  9106. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9107. var results = [];
  9108. for (var index = 0; index < attributesNames.length; index++) {
  9109. try {
  9110. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9111. }
  9112. catch (e) {
  9113. results.push(-1);
  9114. }
  9115. }
  9116. return results;
  9117. };
  9118. Engine.prototype.enableEffect = function (effect) {
  9119. // Use program
  9120. this.setProgram(effect.getProgram());
  9121. this._currentEffect = effect;
  9122. if (effect.onBind) {
  9123. effect.onBind(effect);
  9124. }
  9125. effect.onBindObservable.notifyObservers(effect);
  9126. };
  9127. Engine.prototype.setIntArray = function (uniform, array) {
  9128. if (!uniform)
  9129. return;
  9130. this._gl.uniform1iv(uniform, array);
  9131. };
  9132. Engine.prototype.setIntArray2 = function (uniform, array) {
  9133. if (!uniform || array.length % 2 !== 0)
  9134. return;
  9135. this._gl.uniform2iv(uniform, array);
  9136. };
  9137. Engine.prototype.setIntArray3 = function (uniform, array) {
  9138. if (!uniform || array.length % 3 !== 0)
  9139. return;
  9140. this._gl.uniform3iv(uniform, array);
  9141. };
  9142. Engine.prototype.setIntArray4 = function (uniform, array) {
  9143. if (!uniform || array.length % 4 !== 0)
  9144. return;
  9145. this._gl.uniform4iv(uniform, array);
  9146. };
  9147. Engine.prototype.setFloatArray = function (uniform, array) {
  9148. if (!uniform)
  9149. return;
  9150. this._gl.uniform1fv(uniform, array);
  9151. };
  9152. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9153. if (!uniform || array.length % 2 !== 0)
  9154. return;
  9155. this._gl.uniform2fv(uniform, array);
  9156. };
  9157. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9158. if (!uniform || array.length % 3 !== 0)
  9159. return;
  9160. this._gl.uniform3fv(uniform, array);
  9161. };
  9162. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9163. if (!uniform || array.length % 4 !== 0)
  9164. return;
  9165. this._gl.uniform4fv(uniform, array);
  9166. };
  9167. Engine.prototype.setArray = function (uniform, array) {
  9168. if (!uniform)
  9169. return;
  9170. this._gl.uniform1fv(uniform, array);
  9171. };
  9172. Engine.prototype.setArray2 = function (uniform, array) {
  9173. if (!uniform || array.length % 2 !== 0)
  9174. return;
  9175. this._gl.uniform2fv(uniform, array);
  9176. };
  9177. Engine.prototype.setArray3 = function (uniform, array) {
  9178. if (!uniform || array.length % 3 !== 0)
  9179. return;
  9180. this._gl.uniform3fv(uniform, array);
  9181. };
  9182. Engine.prototype.setArray4 = function (uniform, array) {
  9183. if (!uniform || array.length % 4 !== 0)
  9184. return;
  9185. this._gl.uniform4fv(uniform, array);
  9186. };
  9187. Engine.prototype.setMatrices = function (uniform, matrices) {
  9188. if (!uniform)
  9189. return;
  9190. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9191. };
  9192. Engine.prototype.setMatrix = function (uniform, matrix) {
  9193. if (!uniform)
  9194. return;
  9195. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9196. };
  9197. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9198. if (!uniform)
  9199. return;
  9200. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9201. };
  9202. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9203. if (!uniform)
  9204. return;
  9205. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9206. };
  9207. Engine.prototype.setFloat = function (uniform, value) {
  9208. if (!uniform)
  9209. return;
  9210. this._gl.uniform1f(uniform, value);
  9211. };
  9212. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9213. if (!uniform)
  9214. return;
  9215. this._gl.uniform2f(uniform, x, y);
  9216. };
  9217. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9218. if (!uniform)
  9219. return;
  9220. this._gl.uniform3f(uniform, x, y, z);
  9221. };
  9222. Engine.prototype.setBool = function (uniform, bool) {
  9223. if (!uniform)
  9224. return;
  9225. this._gl.uniform1i(uniform, bool);
  9226. };
  9227. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9228. if (!uniform)
  9229. return;
  9230. this._gl.uniform4f(uniform, x, y, z, w);
  9231. };
  9232. Engine.prototype.setColor3 = function (uniform, color3) {
  9233. if (!uniform)
  9234. return;
  9235. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9236. };
  9237. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9238. if (!uniform)
  9239. return;
  9240. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9241. };
  9242. // States
  9243. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9244. if (zOffset === void 0) { zOffset = 0; }
  9245. if (reverseSide === void 0) { reverseSide = false; }
  9246. // Culling
  9247. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9248. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9249. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9250. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9251. if (culling) {
  9252. this._depthCullingState.cullFace = cullFace;
  9253. this._depthCullingState.cull = true;
  9254. }
  9255. else {
  9256. this._depthCullingState.cull = false;
  9257. }
  9258. }
  9259. // Z offset
  9260. this.setZOffset(zOffset);
  9261. };
  9262. Engine.prototype.setZOffset = function (value) {
  9263. this._depthCullingState.zOffset = value;
  9264. };
  9265. Engine.prototype.getZOffset = function () {
  9266. return this._depthCullingState.zOffset;
  9267. };
  9268. Engine.prototype.setDepthBuffer = function (enable) {
  9269. this._depthCullingState.depthTest = enable;
  9270. };
  9271. Engine.prototype.getDepthWrite = function () {
  9272. return this._depthCullingState.depthMask;
  9273. };
  9274. Engine.prototype.setDepthWrite = function (enable) {
  9275. this._depthCullingState.depthMask = enable;
  9276. };
  9277. Engine.prototype.setColorWrite = function (enable) {
  9278. this._gl.colorMask(enable, enable, enable, enable);
  9279. };
  9280. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9281. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9282. };
  9283. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9284. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9285. if (this._alphaMode === mode) {
  9286. return;
  9287. }
  9288. switch (mode) {
  9289. case Engine.ALPHA_DISABLE:
  9290. this._alphaState.alphaBlend = false;
  9291. break;
  9292. case Engine.ALPHA_PREMULTIPLIED:
  9293. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9294. this._alphaState.alphaBlend = true;
  9295. break;
  9296. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9297. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9298. this._alphaState.alphaBlend = true;
  9299. break;
  9300. case Engine.ALPHA_COMBINE:
  9301. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9302. this._alphaState.alphaBlend = true;
  9303. break;
  9304. case Engine.ALPHA_ONEONE:
  9305. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9306. this._alphaState.alphaBlend = true;
  9307. break;
  9308. case Engine.ALPHA_ADD:
  9309. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9310. this._alphaState.alphaBlend = true;
  9311. break;
  9312. case Engine.ALPHA_SUBTRACT:
  9313. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9314. this._alphaState.alphaBlend = true;
  9315. break;
  9316. case Engine.ALPHA_MULTIPLY:
  9317. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9318. this._alphaState.alphaBlend = true;
  9319. break;
  9320. case Engine.ALPHA_MAXIMIZED:
  9321. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9322. this._alphaState.alphaBlend = true;
  9323. break;
  9324. case Engine.ALPHA_INTERPOLATE:
  9325. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9326. this._alphaState.alphaBlend = true;
  9327. break;
  9328. case Engine.ALPHA_SCREENMODE:
  9329. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9330. this._alphaState.alphaBlend = true;
  9331. break;
  9332. }
  9333. if (!noDepthWriteChange) {
  9334. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9335. }
  9336. this._alphaMode = mode;
  9337. };
  9338. Engine.prototype.getAlphaMode = function () {
  9339. return this._alphaMode;
  9340. };
  9341. Engine.prototype.setAlphaTesting = function (enable) {
  9342. this._alphaTest = enable;
  9343. };
  9344. Engine.prototype.getAlphaTesting = function () {
  9345. return !!this._alphaTest;
  9346. };
  9347. // Textures
  9348. Engine.prototype.wipeCaches = function (bruteForce) {
  9349. if (this.preventCacheWipeBetweenFrames) {
  9350. return;
  9351. }
  9352. this.resetTextureCache();
  9353. this._currentEffect = null;
  9354. // 6/8/2017: deltakosh: Should not be required anymore.
  9355. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9356. if (bruteForce) {
  9357. this._currentProgram = null;
  9358. this._stencilState.reset();
  9359. this._depthCullingState.reset();
  9360. this.setDepthFunctionToLessOrEqual();
  9361. this._alphaState.reset();
  9362. }
  9363. this._cachedVertexBuffers = null;
  9364. this._cachedIndexBuffer = null;
  9365. this._cachedEffectForVertexBuffers = null;
  9366. this._unbindVertexArrayObject();
  9367. this.bindIndexBuffer(null);
  9368. this.bindArrayBuffer(null);
  9369. };
  9370. /**
  9371. * Set the compressed texture format to use, based on the formats you have, and the formats
  9372. * supported by the hardware / browser.
  9373. *
  9374. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9375. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9376. * to API arguments needed to compressed textures. This puts the burden on the container
  9377. * generator to house the arcane code for determining these for current & future formats.
  9378. *
  9379. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9380. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9381. *
  9382. * Note: The result of this call is not taken into account when a texture is base64.
  9383. *
  9384. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9385. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9386. *
  9387. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9388. * @returns The extension selected.
  9389. */
  9390. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9391. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9392. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9393. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9394. return this._textureFormatInUse = this._texturesSupported[i];
  9395. }
  9396. }
  9397. }
  9398. // actively set format to nothing, to allow this to be called more than once
  9399. // and possibly fail the 2nd time
  9400. return this._textureFormatInUse = null;
  9401. };
  9402. /**
  9403. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9404. * @param {string} urlArg- This contains one of the following:
  9405. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9406. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9407. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9408. *
  9409. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9410. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9411. * @param {Scene} scene- Needed for loading to the correct scene.
  9412. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9413. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9414. * @param {callback} onError- Optional callback to be called upon failure.
  9415. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9416. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9417. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9418. *
  9419. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9420. */
  9421. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9422. var _this = this;
  9423. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9424. if (onLoad === void 0) { onLoad = null; }
  9425. if (onError === void 0) { onError = null; }
  9426. if (buffer === void 0) { buffer = null; }
  9427. var texture = fallBack ? fallBack : this._gl.createTexture();
  9428. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9429. var fromData = url.substr(0, 5) === "data:";
  9430. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9431. // establish the file extension, if possible
  9432. var lastDot = url.lastIndexOf('.');
  9433. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9434. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9435. var isTGA = (extension === ".tga");
  9436. // determine if a ktx file should be substituted
  9437. var isKTX = false;
  9438. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9439. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9440. isKTX = true;
  9441. }
  9442. scene._addPendingData(texture);
  9443. texture.url = url;
  9444. texture.generateMipMaps = !noMipmap;
  9445. texture.references = 1;
  9446. texture.samplingMode = samplingMode;
  9447. texture.onLoadedCallbacks = [];
  9448. if (onLoad) {
  9449. texture.onLoadedCallbacks.push(onLoad);
  9450. }
  9451. if (!fallBack)
  9452. this._loadedTexturesCache.push(texture);
  9453. var onerror = function () {
  9454. scene._removePendingData(texture);
  9455. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9456. if (isKTX) {
  9457. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9458. }
  9459. else if (onError) {
  9460. onError();
  9461. }
  9462. };
  9463. var callback;
  9464. // processing for non-image formats
  9465. if (isKTX || isTGA || isDDS) {
  9466. if (isKTX) {
  9467. callback = function (data) {
  9468. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9469. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9470. ktx.uploadLevels(_this._gl, !noMipmap);
  9471. return false;
  9472. }, samplingMode);
  9473. };
  9474. }
  9475. else if (isTGA) {
  9476. callback = function (arrayBuffer) {
  9477. var data = new Uint8Array(arrayBuffer);
  9478. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9479. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9480. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9481. return false;
  9482. }, samplingMode);
  9483. };
  9484. }
  9485. else if (isDDS) {
  9486. callback = function (data) {
  9487. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9488. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9489. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9490. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 1);
  9491. return false;
  9492. }, samplingMode);
  9493. };
  9494. }
  9495. if (!buffer) {
  9496. BABYLON.Tools.LoadFile(url, function (data) {
  9497. callback(data);
  9498. }, null, scene.database, true, onerror);
  9499. }
  9500. else {
  9501. callback(buffer);
  9502. }
  9503. // image format processing
  9504. }
  9505. else {
  9506. var onload = function (img) {
  9507. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9508. var gl = _this._gl;
  9509. var isPot = (img.width === potWidth && img.height === potHeight);
  9510. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9511. if (isPot) {
  9512. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9513. return false;
  9514. }
  9515. // Using shaders to rescale because canvas.drawImage is lossy
  9516. var source = gl.createTexture();
  9517. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9518. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9519. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9520. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9521. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9522. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9523. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9524. _this._releaseTexture(source);
  9525. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9526. continuationCallback();
  9527. });
  9528. return true;
  9529. }, samplingMode);
  9530. };
  9531. if (!fromData || isBase64)
  9532. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9533. else if (buffer instanceof Array || typeof buffer === "string")
  9534. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9535. else
  9536. onload(buffer);
  9537. }
  9538. return texture;
  9539. };
  9540. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9541. var _this = this;
  9542. var rtt = this.createRenderTargetTexture({
  9543. width: destination._width,
  9544. height: destination._height,
  9545. }, {
  9546. generateMipMaps: false,
  9547. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9548. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9549. generateDepthBuffer: false,
  9550. generateStencilBuffer: false
  9551. });
  9552. if (!this._rescalePostProcess) {
  9553. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9554. }
  9555. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9556. _this._rescalePostProcess.onApply = function (effect) {
  9557. effect._bindTexture("textureSampler", source);
  9558. };
  9559. scene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9560. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9561. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination._width, destination._height, 0);
  9562. _this.unBindFramebuffer(rtt);
  9563. _this._releaseTexture(rtt);
  9564. if (onComplete) {
  9565. onComplete();
  9566. }
  9567. });
  9568. };
  9569. Engine.prototype._getInternalFormat = function (format) {
  9570. var internalFormat = this._gl.RGBA;
  9571. switch (format) {
  9572. case Engine.TEXTUREFORMAT_ALPHA:
  9573. internalFormat = this._gl.ALPHA;
  9574. break;
  9575. case Engine.TEXTUREFORMAT_LUMINANCE:
  9576. internalFormat = this._gl.LUMINANCE;
  9577. break;
  9578. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9579. internalFormat = this._gl.LUMINANCE_ALPHA;
  9580. break;
  9581. case Engine.TEXTUREFORMAT_RGB:
  9582. internalFormat = this._gl.RGB;
  9583. break;
  9584. case Engine.TEXTUREFORMAT_RGBA:
  9585. internalFormat = this._gl.RGBA;
  9586. break;
  9587. }
  9588. return internalFormat;
  9589. };
  9590. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9591. if (compression === void 0) { compression = null; }
  9592. var internalFormat = this._getInternalFormat(format);
  9593. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9594. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9595. if (texture._width % 4 !== 0) {
  9596. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9597. }
  9598. if (compression) {
  9599. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9600. }
  9601. else {
  9602. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9603. }
  9604. if (texture.generateMipMaps) {
  9605. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9606. }
  9607. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9608. this.resetTextureCache();
  9609. texture.isReady = true;
  9610. };
  9611. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9612. if (compression === void 0) { compression = null; }
  9613. var texture = this._gl.createTexture();
  9614. texture._baseWidth = width;
  9615. texture._baseHeight = height;
  9616. texture._width = width;
  9617. texture._height = height;
  9618. texture.references = 1;
  9619. this.updateRawTexture(texture, data, format, invertY, compression);
  9620. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9621. // Filters
  9622. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9623. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9624. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9625. if (generateMipMaps) {
  9626. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9627. }
  9628. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9629. texture.samplingMode = samplingMode;
  9630. this._loadedTexturesCache.push(texture);
  9631. return texture;
  9632. };
  9633. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9634. var texture = this._gl.createTexture();
  9635. texture._baseWidth = width;
  9636. texture._baseHeight = height;
  9637. if (generateMipMaps) {
  9638. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9639. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9640. }
  9641. this.resetTextureCache();
  9642. texture._width = width;
  9643. texture._height = height;
  9644. texture.isReady = false;
  9645. texture.generateMipMaps = generateMipMaps;
  9646. texture.references = 1;
  9647. texture.samplingMode = samplingMode;
  9648. this.updateTextureSamplingMode(samplingMode, texture);
  9649. this._loadedTexturesCache.push(texture);
  9650. return texture;
  9651. };
  9652. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9653. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9654. if (texture.isCube) {
  9655. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9656. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9657. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9658. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9659. }
  9660. else {
  9661. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9662. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9663. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9664. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9665. }
  9666. texture.samplingMode = samplingMode;
  9667. };
  9668. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9669. if (premulAlpha === void 0) { premulAlpha = false; }
  9670. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9671. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9672. if (premulAlpha) {
  9673. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9674. }
  9675. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9676. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9677. if (texture.generateMipMaps) {
  9678. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9679. }
  9680. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9681. if (premulAlpha) {
  9682. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9683. }
  9684. this.resetTextureCache();
  9685. texture.isReady = true;
  9686. };
  9687. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9688. if (texture._isDisabled) {
  9689. return;
  9690. }
  9691. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9692. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9693. try {
  9694. // Testing video texture support
  9695. if (this._videoTextureSupported === undefined) {
  9696. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9697. if (this._gl.getError() !== 0) {
  9698. this._videoTextureSupported = false;
  9699. }
  9700. else {
  9701. this._videoTextureSupported = true;
  9702. }
  9703. }
  9704. // Copy video through the current working canvas if video texture is not supported
  9705. if (!this._videoTextureSupported) {
  9706. if (!texture._workingCanvas) {
  9707. texture._workingCanvas = document.createElement("canvas");
  9708. texture._workingContext = texture._workingCanvas.getContext("2d");
  9709. texture._workingCanvas.width = texture._width;
  9710. texture._workingCanvas.height = texture._height;
  9711. }
  9712. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9713. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9714. }
  9715. else {
  9716. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9717. }
  9718. if (texture.generateMipMaps) {
  9719. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9720. }
  9721. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9722. this.resetTextureCache();
  9723. texture.isReady = true;
  9724. }
  9725. catch (ex) {
  9726. // Something unexpected
  9727. // Let's disable the texture
  9728. texture._isDisabled = true;
  9729. }
  9730. };
  9731. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9732. // old version had a "generateMipMaps" arg instead of options.
  9733. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9734. // in the same way, generateDepthBuffer is defaulted to true
  9735. var generateMipMaps = false;
  9736. var generateDepthBuffer = true;
  9737. var generateStencilBuffer = false;
  9738. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9739. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9740. if (options !== undefined) {
  9741. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9742. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9743. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9744. type = options.type === undefined ? type : options.type;
  9745. if (options.samplingMode !== undefined) {
  9746. samplingMode = options.samplingMode;
  9747. }
  9748. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9749. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9750. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9751. }
  9752. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9753. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9754. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9755. }
  9756. }
  9757. var gl = this._gl;
  9758. var texture = gl.createTexture();
  9759. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9760. var width = size.width || size;
  9761. var height = size.height || size;
  9762. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9763. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9764. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9765. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9766. }
  9767. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9768. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9769. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9770. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9771. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9772. // Create the framebuffer
  9773. var framebuffer = gl.createFramebuffer();
  9774. this.bindUnboundFramebuffer(framebuffer);
  9775. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9776. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9777. if (generateMipMaps) {
  9778. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9779. }
  9780. // Unbind
  9781. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9782. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9783. this.bindUnboundFramebuffer(null);
  9784. texture._framebuffer = framebuffer;
  9785. texture._baseWidth = width;
  9786. texture._baseHeight = height;
  9787. texture._width = width;
  9788. texture._height = height;
  9789. texture.isReady = true;
  9790. texture.samples = 1;
  9791. texture.generateMipMaps = generateMipMaps;
  9792. texture.references = 1;
  9793. texture.samplingMode = samplingMode;
  9794. texture.type = type;
  9795. texture._generateDepthBuffer = generateDepthBuffer;
  9796. texture._generateStencilBuffer = generateStencilBuffer;
  9797. this.resetTextureCache();
  9798. this._loadedTexturesCache.push(texture);
  9799. return texture;
  9800. };
  9801. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9802. var generateMipMaps = false;
  9803. var generateDepthBuffer = true;
  9804. var generateStencilBuffer = false;
  9805. var generateDepthTexture = false;
  9806. var textureCount = 1;
  9807. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9808. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9809. var types = [], samplingModes = [];
  9810. if (options !== undefined) {
  9811. generateMipMaps = options.generateMipMaps;
  9812. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9813. generateStencilBuffer = options.generateStencilBuffer;
  9814. generateDepthTexture = options.generateDepthTexture;
  9815. textureCount = options.textureCount || 1;
  9816. if (options.types) {
  9817. types = options.types;
  9818. }
  9819. if (options.samplingModes) {
  9820. samplingModes = options.samplingModes;
  9821. }
  9822. }
  9823. var gl = this._gl;
  9824. // Create the framebuffer
  9825. var framebuffer = gl.createFramebuffer();
  9826. this.bindUnboundFramebuffer(framebuffer);
  9827. var width = size.width || size;
  9828. var height = size.height || size;
  9829. var textures = [];
  9830. var attachments = [];
  9831. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9832. for (var i = 0; i < textureCount; i++) {
  9833. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9834. var type = types[i] || defaultType;
  9835. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9836. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9837. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9838. }
  9839. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9840. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9841. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9842. }
  9843. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9844. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9845. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9846. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9847. }
  9848. var texture = gl.createTexture();
  9849. var attachment = gl["COLOR_ATTACHMENT" + i];
  9850. textures.push(texture);
  9851. attachments.push(attachment);
  9852. gl.activeTexture(gl["TEXTURE" + i]);
  9853. gl.bindTexture(gl.TEXTURE_2D, texture);
  9854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9856. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9857. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9858. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9859. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9860. if (generateMipMaps) {
  9861. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9862. }
  9863. // Unbind
  9864. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9865. texture._framebuffer = framebuffer;
  9866. texture._depthStencilBuffer = depthStencilBuffer;
  9867. texture._baseWidth = width;
  9868. texture._baseHeight = height;
  9869. texture._width = width;
  9870. texture._height = height;
  9871. texture.isReady = true;
  9872. texture.samples = 1;
  9873. texture.generateMipMaps = generateMipMaps;
  9874. texture.references = 1;
  9875. texture.samplingMode = samplingMode;
  9876. texture.type = type;
  9877. texture._generateDepthBuffer = generateDepthBuffer;
  9878. texture._generateStencilBuffer = generateStencilBuffer;
  9879. this._loadedTexturesCache.push(texture);
  9880. }
  9881. if (generateDepthTexture) {
  9882. // Depth texture
  9883. var depthTexture = gl.createTexture();
  9884. gl.activeTexture(gl.TEXTURE0);
  9885. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9886. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9887. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9888. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9889. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9890. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9891. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9892. depthTexture._framebuffer = framebuffer;
  9893. depthTexture._baseWidth = width;
  9894. depthTexture._baseHeight = height;
  9895. depthTexture._width = width;
  9896. depthTexture._height = height;
  9897. depthTexture.isReady = true;
  9898. depthTexture.samples = 1;
  9899. depthTexture.generateMipMaps = generateMipMaps;
  9900. depthTexture.references = 1;
  9901. depthTexture.samplingMode = gl.NEAREST;
  9902. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9903. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9904. textures.push(depthTexture);
  9905. this._loadedTexturesCache.push(depthTexture);
  9906. }
  9907. gl.drawBuffers(attachments);
  9908. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9909. this.bindUnboundFramebuffer(null);
  9910. this.resetTextureCache();
  9911. return textures;
  9912. };
  9913. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9914. if (samples === void 0) { samples = 1; }
  9915. var depthStencilBuffer = null;
  9916. var gl = this._gl;
  9917. // Create the depth/stencil buffer
  9918. if (generateStencilBuffer) {
  9919. depthStencilBuffer = gl.createRenderbuffer();
  9920. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9921. if (samples > 1) {
  9922. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  9923. }
  9924. else {
  9925. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9926. }
  9927. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9928. }
  9929. else if (generateDepthBuffer) {
  9930. depthStencilBuffer = gl.createRenderbuffer();
  9931. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9932. if (samples > 1) {
  9933. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9934. }
  9935. else {
  9936. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9937. }
  9938. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9939. }
  9940. return depthStencilBuffer;
  9941. };
  9942. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9943. if (this.webGLVersion < 2) {
  9944. return 1;
  9945. }
  9946. if (texture.samples === samples) {
  9947. return samples;
  9948. }
  9949. var gl = this._gl;
  9950. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9951. // Dispose previous render buffers
  9952. if (texture._depthStencilBuffer) {
  9953. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9954. }
  9955. if (texture._MSAAFramebuffer) {
  9956. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9957. }
  9958. if (texture._MSAARenderBuffer) {
  9959. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9960. }
  9961. if (samples > 1) {
  9962. texture._MSAAFramebuffer = gl.createFramebuffer();
  9963. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9964. var colorRenderbuffer = gl.createRenderbuffer();
  9965. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9966. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9967. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9968. texture._MSAARenderBuffer = colorRenderbuffer;
  9969. }
  9970. else {
  9971. this.bindUnboundFramebuffer(texture._framebuffer);
  9972. }
  9973. texture.samples = samples;
  9974. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9975. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9976. this.bindUnboundFramebuffer(null);
  9977. return samples;
  9978. };
  9979. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  9980. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  9981. };
  9982. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  9983. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  9984. };
  9985. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9986. var gl = this._gl;
  9987. var texture = gl.createTexture();
  9988. var generateMipMaps = true;
  9989. var generateDepthBuffer = true;
  9990. var generateStencilBuffer = false;
  9991. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9992. if (options !== undefined) {
  9993. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9994. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9995. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9996. if (options.samplingMode !== undefined) {
  9997. samplingMode = options.samplingMode;
  9998. }
  9999. }
  10000. texture.isCube = true;
  10001. texture.references = 1;
  10002. texture.generateMipMaps = generateMipMaps;
  10003. texture.references = 1;
  10004. texture.samples = 1;
  10005. texture.samplingMode = samplingMode;
  10006. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10007. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10008. for (var face = 0; face < 6; face++) {
  10009. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10010. }
  10011. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10012. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10013. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10014. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10015. // Create the framebuffer
  10016. var framebuffer = gl.createFramebuffer();
  10017. this.bindUnboundFramebuffer(framebuffer);
  10018. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10019. // Mipmaps
  10020. if (texture.generateMipMaps) {
  10021. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10022. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10023. }
  10024. // Unbind
  10025. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10026. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10027. this.bindUnboundFramebuffer(null);
  10028. texture._framebuffer = framebuffer;
  10029. texture._width = size;
  10030. texture._height = size;
  10031. texture.isReady = true;
  10032. this.resetTextureCache();
  10033. this._loadedTexturesCache.push(texture);
  10034. return texture;
  10035. };
  10036. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10037. var _this = this;
  10038. if (onError === void 0) { onError = null; }
  10039. if (forcedExtension === void 0) { forcedExtension = null; }
  10040. var callback = function (loadData) {
  10041. if (_this._caps.textureLOD || !loadData) {
  10042. // Do not add extra process if texture lod is supported.
  10043. if (onLoad) {
  10044. onLoad();
  10045. }
  10046. return;
  10047. }
  10048. var mipSlices = 3;
  10049. var gl = _this._gl;
  10050. var width = loadData.width;
  10051. if (!width) {
  10052. return;
  10053. }
  10054. var textures = [];
  10055. for (var i = 0; i < mipSlices; i++) {
  10056. //compute LOD from even spacing in smoothness (matching shader calculation)
  10057. var smoothness = i / (mipSlices - 1);
  10058. var roughness = 1 - smoothness;
  10059. var minLODIndex = offset; // roughness = 0
  10060. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10061. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10062. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10063. var glTextureFromLod = gl.createTexture();
  10064. glTextureFromLod.isCube = true;
  10065. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10066. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10069. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10070. if (loadData.isDDS) {
  10071. var info = loadData.info;
  10072. var data = loadData.data;
  10073. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10074. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, true, 6, mipmapIndex);
  10075. }
  10076. else {
  10077. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10078. }
  10079. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10080. // Wrap in a base texture for easy binding.
  10081. var lodTexture = new BABYLON.BaseTexture(scene);
  10082. lodTexture.isCube = true;
  10083. lodTexture._texture = glTextureFromLod;
  10084. glTextureFromLod.isReady = true;
  10085. textures.push(lodTexture);
  10086. }
  10087. loadData.texture._lodTextureHigh = textures[2];
  10088. loadData.texture._lodTextureMid = textures[1];
  10089. loadData.texture._lodTextureLow = textures[0];
  10090. if (onLoad) {
  10091. onLoad();
  10092. }
  10093. };
  10094. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10095. };
  10096. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10097. var _this = this;
  10098. if (onLoad === void 0) { onLoad = null; }
  10099. if (onError === void 0) { onError = null; }
  10100. if (forcedExtension === void 0) { forcedExtension = null; }
  10101. var gl = this._gl;
  10102. var texture = gl.createTexture();
  10103. texture.isCube = true;
  10104. texture.url = rootUrl;
  10105. texture.references = 1;
  10106. texture.onLoadedCallbacks = [];
  10107. texture.generateMipMaps = !noMipmap;
  10108. var isKTX = false;
  10109. var isDDS = false;
  10110. var lastDot = rootUrl.lastIndexOf('.');
  10111. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10112. if (this._textureFormatInUse) {
  10113. extension = this._textureFormatInUse;
  10114. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10115. isKTX = true;
  10116. }
  10117. else {
  10118. isDDS = (extension === ".dds");
  10119. }
  10120. if (isKTX) {
  10121. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10122. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10123. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10124. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10125. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10126. ktx.uploadLevels(_this._gl, !noMipmap);
  10127. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10128. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10129. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10130. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10131. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10132. _this.resetTextureCache();
  10133. texture._width = ktx.pixelWidth;
  10134. texture._height = ktx.pixelHeight;
  10135. texture.isReady = true;
  10136. }, null, null, true, onError);
  10137. }
  10138. else if (isDDS) {
  10139. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10140. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10141. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10142. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10143. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10144. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 6);
  10145. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10146. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10147. }
  10148. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10149. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10150. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10151. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10152. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10153. _this.resetTextureCache();
  10154. texture._width = info.width;
  10155. texture._height = info.height;
  10156. texture.isReady = true;
  10157. texture.type = info.textureType;
  10158. if (onLoad) {
  10159. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10160. }
  10161. }, null, null, true, onError);
  10162. }
  10163. else {
  10164. cascadeLoad(rootUrl, scene, function (imgs) {
  10165. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10166. var height = width;
  10167. _this._prepareWorkingCanvas();
  10168. _this._workingCanvas.width = width;
  10169. _this._workingCanvas.height = height;
  10170. var faces = [
  10171. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10172. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10173. ];
  10174. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10175. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10176. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10177. for (var index = 0; index < faces.length; index++) {
  10178. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10179. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10180. }
  10181. if (!noMipmap) {
  10182. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10183. }
  10184. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10185. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10186. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10187. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10188. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10189. _this.resetTextureCache();
  10190. texture._width = width;
  10191. texture._height = height;
  10192. texture.isReady = true;
  10193. texture.onLoadedCallbacks.forEach(function (callback) {
  10194. callback();
  10195. });
  10196. if (onLoad) {
  10197. onLoad();
  10198. }
  10199. }, files, onError);
  10200. }
  10201. this._loadedTexturesCache.push(texture);
  10202. return texture;
  10203. };
  10204. Engine.prototype.updateTextureSize = function (texture, width, height) {
  10205. texture._width = width;
  10206. texture._height = height;
  10207. texture._size = width * height;
  10208. texture._baseWidth = width;
  10209. texture._baseHeight = height;
  10210. };
  10211. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10212. if (compression === void 0) { compression = null; }
  10213. if (level === void 0) { level = 0; }
  10214. var gl = this._gl;
  10215. var textureType = this._getWebGLTextureType(type);
  10216. var internalFormat = this._getInternalFormat(format);
  10217. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10218. var needConversion = false;
  10219. if (internalFormat === gl.RGB) {
  10220. internalFormat = gl.RGBA;
  10221. needConversion = true;
  10222. }
  10223. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10224. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10225. if (texture._width % 4 !== 0) {
  10226. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10227. }
  10228. // Data are known to be in +X +Y +Z -X -Y -Z
  10229. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10230. var faceData = data[faceIndex];
  10231. if (compression) {
  10232. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  10233. }
  10234. else {
  10235. if (needConversion) {
  10236. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  10237. }
  10238. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  10239. }
  10240. }
  10241. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  10242. if (isPot && texture.generateMipMaps && level === 0) {
  10243. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10244. }
  10245. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10246. this.resetTextureCache();
  10247. texture.isReady = true;
  10248. };
  10249. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10250. if (compression === void 0) { compression = null; }
  10251. var gl = this._gl;
  10252. var texture = gl.createTexture();
  10253. texture.isCube = true;
  10254. texture.references = 1;
  10255. texture.generateMipMaps = generateMipMaps;
  10256. texture.format = format;
  10257. texture.type = type;
  10258. var textureType = this._getWebGLTextureType(type);
  10259. var internalFormat = this._getInternalFormat(format);
  10260. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10261. var needConversion = false;
  10262. if (internalFormat === gl.RGB) {
  10263. internalFormat = gl.RGBA;
  10264. needConversion = true;
  10265. }
  10266. var width = size;
  10267. var height = width;
  10268. texture._width = width;
  10269. texture._height = height;
  10270. // Double check on POT to generate Mips.
  10271. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  10272. if (!isPot) {
  10273. generateMipMaps = false;
  10274. }
  10275. // Upload data if needed. The texture won t be ready until then.
  10276. if (data) {
  10277. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10278. }
  10279. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10280. // Filters
  10281. if (data && generateMipMaps) {
  10282. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10283. }
  10284. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10285. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10286. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10287. }
  10288. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10289. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10290. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10291. }
  10292. else {
  10293. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10294. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10295. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10296. }
  10297. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10298. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10299. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10300. return texture;
  10301. };
  10302. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10303. var _this = this;
  10304. if (onLoad === void 0) { onLoad = null; }
  10305. if (onError === void 0) { onError = null; }
  10306. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10307. if (invertY === void 0) { invertY = false; }
  10308. var gl = this._gl;
  10309. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10310. scene._addPendingData(texture);
  10311. texture.url = url;
  10312. this._loadedTexturesCache.push(texture);
  10313. var onerror = function () {
  10314. scene._removePendingData(texture);
  10315. if (onError) {
  10316. onError();
  10317. }
  10318. };
  10319. var internalCallback = function (data) {
  10320. var width = texture._width;
  10321. var height = texture._height;
  10322. var faceDataArrays = callback(data);
  10323. if (mipmmapGenerator) {
  10324. var textureType = _this._getWebGLTextureType(type);
  10325. var internalFormat = _this._getInternalFormat(format);
  10326. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10327. var needConversion = false;
  10328. if (internalFormat === gl.RGB) {
  10329. internalFormat = gl.RGBA;
  10330. needConversion = true;
  10331. }
  10332. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10333. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10334. var mipData = mipmmapGenerator(faceDataArrays);
  10335. for (var level = 0; level < mipData.length; level++) {
  10336. var mipSize = width >> level;
  10337. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10338. var mipFaceData = mipData[level][faceIndex];
  10339. if (needConversion) {
  10340. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10341. }
  10342. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10343. }
  10344. }
  10345. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10346. }
  10347. else {
  10348. texture.generateMipMaps = !noMipmap;
  10349. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10350. }
  10351. texture.isReady = true;
  10352. _this.resetTextureCache();
  10353. scene._removePendingData(texture);
  10354. if (onLoad) {
  10355. onLoad();
  10356. }
  10357. };
  10358. BABYLON.Tools.LoadFile(url, function (data) {
  10359. internalCallback(data);
  10360. }, onerror, scene.database, true);
  10361. return texture;
  10362. };
  10363. ;
  10364. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10365. var gl = this._gl;
  10366. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10368. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10369. if (!noMipmap && !isCompressed) {
  10370. gl.generateMipmap(gl.TEXTURE_2D);
  10371. }
  10372. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10373. this.resetTextureCache();
  10374. scene._removePendingData(texture);
  10375. texture.onLoadedCallbacks.forEach(function (callback) {
  10376. callback();
  10377. });
  10378. texture.onLoadedCallbacks = [];
  10379. };
  10380. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10381. var _this = this;
  10382. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10383. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10384. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10385. var gl = this._gl;
  10386. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10387. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10388. texture._baseWidth = width;
  10389. texture._baseHeight = height;
  10390. texture._width = potWidth;
  10391. texture._height = potHeight;
  10392. texture.isReady = true;
  10393. if (processFunction(potWidth, potHeight, function () {
  10394. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10395. })) {
  10396. // Returning as texture needs extra async steps
  10397. return;
  10398. }
  10399. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10400. };
  10401. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10402. // Create new RGBA data container.
  10403. var rgbaData;
  10404. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10405. rgbaData = new Float32Array(width * height * 4);
  10406. }
  10407. else {
  10408. rgbaData = new Uint32Array(width * height * 4);
  10409. }
  10410. // Convert each pixel.
  10411. for (var x = 0; x < width; x++) {
  10412. for (var y = 0; y < height; y++) {
  10413. var index = (y * width + x) * 3;
  10414. var newIndex = (y * width + x) * 4;
  10415. // Map Old Value to new value.
  10416. rgbaData[newIndex + 0] = rgbData[index + 0];
  10417. rgbaData[newIndex + 1] = rgbData[index + 1];
  10418. rgbaData[newIndex + 2] = rgbData[index + 2];
  10419. // Add fully opaque alpha channel.
  10420. rgbaData[newIndex + 3] = 1;
  10421. }
  10422. }
  10423. return rgbaData;
  10424. };
  10425. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10426. var gl = this._gl;
  10427. if (texture._framebuffer) {
  10428. gl.deleteFramebuffer(texture._framebuffer);
  10429. texture._framebuffer = null;
  10430. }
  10431. if (texture._depthStencilBuffer) {
  10432. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10433. texture._depthStencilBuffer = null;
  10434. }
  10435. if (texture._MSAAFramebuffer) {
  10436. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10437. texture._MSAAFramebuffer = null;
  10438. }
  10439. if (texture._MSAARenderBuffer) {
  10440. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10441. texture._MSAARenderBuffer = null;
  10442. }
  10443. };
  10444. Engine.prototype._releaseTexture = function (texture) {
  10445. var gl = this._gl;
  10446. this._releaseFramebufferObjects(texture);
  10447. gl.deleteTexture(texture);
  10448. // Unbind channels
  10449. this.unbindAllTextures();
  10450. var index = this._loadedTexturesCache.indexOf(texture);
  10451. if (index !== -1) {
  10452. this._loadedTexturesCache.splice(index, 1);
  10453. }
  10454. // Integrated fixed lod samplers.
  10455. if (texture._lodTextureHigh) {
  10456. texture._lodTextureHigh.dispose();
  10457. }
  10458. if (texture._lodTextureMid) {
  10459. texture._lodTextureMid.dispose();
  10460. }
  10461. if (texture._lodTextureLow) {
  10462. texture._lodTextureLow.dispose();
  10463. }
  10464. };
  10465. Engine.prototype.setProgram = function (program) {
  10466. if (this._currentProgram !== program) {
  10467. this._gl.useProgram(program);
  10468. this._currentProgram = program;
  10469. }
  10470. };
  10471. Engine.prototype.bindSamplers = function (effect) {
  10472. this.setProgram(effect.getProgram());
  10473. var samplers = effect.getSamplers();
  10474. for (var index = 0; index < samplers.length; index++) {
  10475. var uniform = effect.getUniform(samplers[index]);
  10476. this._gl.uniform1i(uniform, index);
  10477. }
  10478. this._currentEffect = null;
  10479. };
  10480. Engine.prototype.activateTexture = function (texture) {
  10481. if (this._activeTexture !== texture) {
  10482. this._gl.activeTexture(texture);
  10483. this._activeTexture = texture;
  10484. }
  10485. };
  10486. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10487. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10488. this._gl.bindTexture(target, texture);
  10489. this._activeTexturesCache[this._activeTexture] = texture;
  10490. }
  10491. };
  10492. Engine.prototype._bindTexture = function (channel, texture) {
  10493. if (channel < 0) {
  10494. return;
  10495. }
  10496. this.activateTexture(this._gl.TEXTURE0 + channel);
  10497. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10498. };
  10499. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10500. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10501. };
  10502. Engine.prototype.unbindAllTextures = function () {
  10503. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10504. this.activateTexture(this._gl["TEXTURE" + channel]);
  10505. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10506. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10507. }
  10508. };
  10509. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10510. if (channel < 0) {
  10511. return;
  10512. }
  10513. this._gl.uniform1i(uniform, channel);
  10514. this._setTexture(channel, texture);
  10515. };
  10516. Engine.prototype._setTexture = function (channel, texture) {
  10517. // Not ready?
  10518. if (!texture) {
  10519. if (this._activeTexturesCache[channel] != null) {
  10520. this.activateTexture(this._gl["TEXTURE" + channel]);
  10521. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10522. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10523. }
  10524. return;
  10525. }
  10526. // Video
  10527. var alreadyActivated = false;
  10528. if (texture.video) {
  10529. this.activateTexture(this._gl["TEXTURE" + channel]);
  10530. alreadyActivated = true;
  10531. texture.update();
  10532. }
  10533. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10534. texture.delayLoad();
  10535. return;
  10536. }
  10537. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10538. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10539. if (this._activeTexturesCache[channel] === internalTexture) {
  10540. return;
  10541. }
  10542. if (!alreadyActivated) {
  10543. this.activateTexture(this._gl["TEXTURE" + channel]);
  10544. }
  10545. if (internalTexture.isCube) {
  10546. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10547. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10548. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10549. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10550. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10551. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10552. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10553. }
  10554. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10555. }
  10556. else {
  10557. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10558. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10559. internalTexture._cachedWrapU = texture.wrapU;
  10560. switch (texture.wrapU) {
  10561. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10562. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10563. break;
  10564. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10565. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10566. break;
  10567. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10568. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10569. break;
  10570. }
  10571. }
  10572. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10573. internalTexture._cachedWrapV = texture.wrapV;
  10574. switch (texture.wrapV) {
  10575. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10576. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10577. break;
  10578. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10579. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10580. break;
  10581. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10582. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10583. break;
  10584. }
  10585. }
  10586. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10587. }
  10588. };
  10589. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10590. if (channel < 0) {
  10591. return;
  10592. }
  10593. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10594. this._textureUnits = new Int32Array(textures.length);
  10595. }
  10596. for (var i = 0; i < textures.length; i++) {
  10597. this._textureUnits[i] = channel + i;
  10598. }
  10599. this._gl.uniform1iv(uniform, this._textureUnits);
  10600. for (var index = 0; index < textures.length; index++) {
  10601. this._setTexture(channel + index, textures[index]);
  10602. }
  10603. };
  10604. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10605. var internalTexture = texture.getInternalTexture();
  10606. if (!internalTexture) {
  10607. return;
  10608. }
  10609. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10610. var value = texture.anisotropicFilteringLevel;
  10611. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10612. value = 1;
  10613. }
  10614. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10615. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10616. texture._cachedAnisotropicFilteringLevel = value;
  10617. }
  10618. };
  10619. Engine.prototype.readPixels = function (x, y, width, height) {
  10620. var data = new Uint8Array(height * width * 4);
  10621. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10622. return data;
  10623. };
  10624. /**
  10625. * Add an externaly attached data from its key.
  10626. * This method call will fail and return false, if such key already exists.
  10627. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10628. * @param key the unique key that identifies the data
  10629. * @param data the data object to associate to the key for this Engine instance
  10630. * @return true if no such key were already present and the data was added successfully, false otherwise
  10631. */
  10632. Engine.prototype.addExternalData = function (key, data) {
  10633. if (!this._externalData) {
  10634. this._externalData = new BABYLON.StringDictionary();
  10635. }
  10636. return this._externalData.add(key, data);
  10637. };
  10638. /**
  10639. * Get an externaly attached data from its key
  10640. * @param key the unique key that identifies the data
  10641. * @return the associated data, if present (can be null), or undefined if not present
  10642. */
  10643. Engine.prototype.getExternalData = function (key) {
  10644. if (!this._externalData) {
  10645. this._externalData = new BABYLON.StringDictionary();
  10646. }
  10647. return this._externalData.get(key);
  10648. };
  10649. /**
  10650. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10651. * @param key the unique key that identifies the data
  10652. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10653. * @return the associated data, can be null if the factory returned null.
  10654. */
  10655. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10656. if (!this._externalData) {
  10657. this._externalData = new BABYLON.StringDictionary();
  10658. }
  10659. return this._externalData.getOrAddWithFactory(key, factory);
  10660. };
  10661. /**
  10662. * Remove an externaly attached data from the Engine instance
  10663. * @param key the unique key that identifies the data
  10664. * @return true if the data was successfully removed, false if it doesn't exist
  10665. */
  10666. Engine.prototype.removeExternalData = function (key) {
  10667. if (!this._externalData) {
  10668. this._externalData = new BABYLON.StringDictionary();
  10669. }
  10670. return this._externalData.remove(key);
  10671. };
  10672. Engine.prototype.releaseInternalTexture = function (texture) {
  10673. if (!texture) {
  10674. return;
  10675. }
  10676. texture.references--;
  10677. // Final reference ?
  10678. if (texture.references === 0) {
  10679. var texturesCache = this.getLoadedTexturesCache();
  10680. var index = texturesCache.indexOf(texture);
  10681. if (index > -1) {
  10682. texturesCache.splice(index, 1);
  10683. }
  10684. this._releaseTexture(texture);
  10685. }
  10686. };
  10687. Engine.prototype.unbindAllAttributes = function () {
  10688. if (this._mustWipeVertexAttributes) {
  10689. this._mustWipeVertexAttributes = false;
  10690. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10691. this._gl.disableVertexAttribArray(i);
  10692. this._vertexAttribArraysEnabled[i] = false;
  10693. this._currentBufferPointers[i].active = false;
  10694. }
  10695. return;
  10696. }
  10697. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10698. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10699. continue;
  10700. }
  10701. this._gl.disableVertexAttribArray(i);
  10702. this._vertexAttribArraysEnabled[i] = false;
  10703. this._currentBufferPointers[i].active = false;
  10704. }
  10705. };
  10706. Engine.prototype.releaseEffects = function () {
  10707. for (var name in this._compiledEffects) {
  10708. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10709. }
  10710. this._compiledEffects = {};
  10711. };
  10712. // Dispose
  10713. Engine.prototype.dispose = function () {
  10714. this.hideLoadingUI();
  10715. this.stopRenderLoop();
  10716. // Empty texture
  10717. if (this._emptyTexture) {
  10718. this._releaseTexture(this._emptyTexture);
  10719. this._emptyTexture = null;
  10720. }
  10721. if (this._emptyCubeTexture) {
  10722. this._releaseTexture(this._emptyCubeTexture);
  10723. this._emptyCubeTexture = null;
  10724. }
  10725. // Rescale PP
  10726. if (this._rescalePostProcess) {
  10727. this._rescalePostProcess.dispose();
  10728. }
  10729. // Release scenes
  10730. while (this.scenes.length) {
  10731. this.scenes[0].dispose();
  10732. }
  10733. // Release audio engine
  10734. if (Engine.audioEngine) {
  10735. Engine.audioEngine.dispose();
  10736. }
  10737. // Release effects
  10738. this.releaseEffects();
  10739. // Unbind
  10740. this.unbindAllAttributes();
  10741. if (this._dummyFramebuffer) {
  10742. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10743. }
  10744. this._gl = null;
  10745. //WebVR
  10746. this.disableVR();
  10747. // Events
  10748. window.removeEventListener("blur", this._onBlur);
  10749. window.removeEventListener("focus", this._onFocus);
  10750. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  10751. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10752. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10753. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10754. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10755. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10756. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10757. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10758. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10759. // Remove from Instances
  10760. var index = Engine.Instances.indexOf(this);
  10761. if (index >= 0) {
  10762. Engine.Instances.splice(index, 1);
  10763. }
  10764. this._workingCanvas = null;
  10765. this._workingContext = null;
  10766. this._currentBufferPointers = null;
  10767. this._renderingCanvas = null;
  10768. this._currentProgram = null;
  10769. this.onResizeObservable.clear();
  10770. this.onCanvasBlurObservable.clear();
  10771. BABYLON.Effect.ResetCache();
  10772. };
  10773. // Loading screen
  10774. Engine.prototype.displayLoadingUI = function () {
  10775. var loadingScreen = this.loadingScreen;
  10776. if (loadingScreen) {
  10777. loadingScreen.displayLoadingUI();
  10778. }
  10779. };
  10780. Engine.prototype.hideLoadingUI = function () {
  10781. var loadingScreen = this.loadingScreen;
  10782. if (loadingScreen) {
  10783. loadingScreen.hideLoadingUI();
  10784. }
  10785. };
  10786. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10787. get: function () {
  10788. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10789. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10790. return this._loadingScreen;
  10791. },
  10792. set: function (loadingScreen) {
  10793. this._loadingScreen = loadingScreen;
  10794. },
  10795. enumerable: true,
  10796. configurable: true
  10797. });
  10798. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10799. set: function (text) {
  10800. this.loadingScreen.loadingUIText = text;
  10801. },
  10802. enumerable: true,
  10803. configurable: true
  10804. });
  10805. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10806. set: function (color) {
  10807. this.loadingScreen.loadingUIBackgroundColor = color;
  10808. },
  10809. enumerable: true,
  10810. configurable: true
  10811. });
  10812. Engine.prototype.attachContextLostEvent = function (callback) {
  10813. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10814. };
  10815. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10816. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10817. };
  10818. Engine.prototype.getVertexShaderSource = function (program) {
  10819. var shaders = this._gl.getAttachedShaders(program);
  10820. return this._gl.getShaderSource(shaders[0]);
  10821. };
  10822. Engine.prototype.getFragmentShaderSource = function (program) {
  10823. var shaders = this._gl.getAttachedShaders(program);
  10824. return this._gl.getShaderSource(shaders[1]);
  10825. };
  10826. Engine.prototype.getError = function () {
  10827. return this._gl.getError();
  10828. };
  10829. // FPS
  10830. Engine.prototype.getFps = function () {
  10831. return this._fps;
  10832. };
  10833. Engine.prototype.getDeltaTime = function () {
  10834. return this._deltaTime;
  10835. };
  10836. Engine.prototype._measureFps = function () {
  10837. this._performanceMonitor.sampleFrame();
  10838. this._fps = this._performanceMonitor.averageFPS;
  10839. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  10840. };
  10841. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10842. if (faceIndex === void 0) { faceIndex = -1; }
  10843. var gl = this._gl;
  10844. if (!this._dummyFramebuffer) {
  10845. this._dummyFramebuffer = gl.createFramebuffer();
  10846. }
  10847. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10848. if (faceIndex > -1) {
  10849. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  10850. }
  10851. else {
  10852. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10853. }
  10854. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  10855. var buffer;
  10856. switch (readType) {
  10857. case gl.UNSIGNED_BYTE:
  10858. buffer = new Uint8Array(4 * width * height);
  10859. readType = gl.UNSIGNED_BYTE;
  10860. break;
  10861. default:
  10862. buffer = new Float32Array(4 * width * height);
  10863. readType = gl.FLOAT;
  10864. break;
  10865. }
  10866. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  10867. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  10868. return buffer;
  10869. };
  10870. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10871. if (this._webGLVersion > 1) {
  10872. return this._caps.colorBufferFloat;
  10873. }
  10874. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10875. };
  10876. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10877. if (this._webGLVersion > 1) {
  10878. return this._caps.colorBufferFloat;
  10879. }
  10880. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10881. };
  10882. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10883. Engine.prototype._canRenderToFramebuffer = function (type) {
  10884. var gl = this._gl;
  10885. //clear existing errors
  10886. while (gl.getError() !== gl.NO_ERROR) { }
  10887. var successful = true;
  10888. var texture = gl.createTexture();
  10889. gl.bindTexture(gl.TEXTURE_2D, texture);
  10890. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10891. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10893. var fb = gl.createFramebuffer();
  10894. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10895. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10896. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10897. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10898. successful = successful && (gl.getError() === gl.NO_ERROR);
  10899. //try render by clearing frame buffer's color buffer
  10900. if (successful) {
  10901. gl.clear(gl.COLOR_BUFFER_BIT);
  10902. successful = successful && (gl.getError() === gl.NO_ERROR);
  10903. }
  10904. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10905. if (successful) {
  10906. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10907. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10908. var readFormat = gl.RGBA;
  10909. var readType = gl.UNSIGNED_BYTE;
  10910. var buffer = new Uint8Array(4);
  10911. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10912. successful = successful && (gl.getError() === gl.NO_ERROR);
  10913. }
  10914. //clean up
  10915. gl.deleteTexture(texture);
  10916. gl.deleteFramebuffer(fb);
  10917. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10918. //clear accumulated errors
  10919. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10920. return successful;
  10921. };
  10922. Engine.prototype._getWebGLTextureType = function (type) {
  10923. if (type === Engine.TEXTURETYPE_FLOAT) {
  10924. return this._gl.FLOAT;
  10925. }
  10926. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10927. // Add Half Float Constant.
  10928. return this._gl.HALF_FLOAT_OES;
  10929. }
  10930. return this._gl.UNSIGNED_BYTE;
  10931. };
  10932. ;
  10933. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10934. if (this._webGLVersion === 1) {
  10935. return this._gl.RGBA;
  10936. }
  10937. if (type === Engine.TEXTURETYPE_FLOAT) {
  10938. return this._gl.RGBA32F;
  10939. }
  10940. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10941. return this._gl.RGBA16F;
  10942. }
  10943. return this._gl.RGBA;
  10944. };
  10945. ;
  10946. // Statics
  10947. Engine.isSupported = function () {
  10948. try {
  10949. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10950. if (navigator.isCocoonJS) {
  10951. return true;
  10952. }
  10953. var tempcanvas = document.createElement("canvas");
  10954. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10955. return gl != null && !!window.WebGLRenderingContext;
  10956. }
  10957. catch (e) {
  10958. return false;
  10959. }
  10960. };
  10961. Engine.Instances = new Array();
  10962. // Const statics
  10963. Engine._ALPHA_DISABLE = 0;
  10964. Engine._ALPHA_ADD = 1;
  10965. Engine._ALPHA_COMBINE = 2;
  10966. Engine._ALPHA_SUBTRACT = 3;
  10967. Engine._ALPHA_MULTIPLY = 4;
  10968. Engine._ALPHA_MAXIMIZED = 5;
  10969. Engine._ALPHA_ONEONE = 6;
  10970. Engine._ALPHA_PREMULTIPLIED = 7;
  10971. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10972. Engine._ALPHA_INTERPOLATE = 9;
  10973. Engine._ALPHA_SCREENMODE = 10;
  10974. Engine._DELAYLOADSTATE_NONE = 0;
  10975. Engine._DELAYLOADSTATE_LOADED = 1;
  10976. Engine._DELAYLOADSTATE_LOADING = 2;
  10977. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10978. Engine._TEXTUREFORMAT_ALPHA = 0;
  10979. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10980. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10981. Engine._TEXTUREFORMAT_RGB = 4;
  10982. Engine._TEXTUREFORMAT_RGBA = 5;
  10983. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10984. Engine._TEXTURETYPE_FLOAT = 1;
  10985. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10986. // Depht or Stencil test Constants.
  10987. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10988. 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.
  10989. 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.
  10990. 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.
  10991. 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.
  10992. 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.
  10993. 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.
  10994. 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.
  10995. // Stencil Actions Constants.
  10996. Engine._KEEP = 0x1E00;
  10997. Engine._REPLACE = 0x1E01;
  10998. Engine._INCR = 0x1E02;
  10999. Engine._DECR = 0x1E03;
  11000. Engine._INVERT = 0x150A;
  11001. Engine._INCR_WRAP = 0x8507;
  11002. Engine._DECR_WRAP = 0x8508;
  11003. // Texture rescaling mode
  11004. Engine._SCALEMODE_FLOOR = 1;
  11005. Engine._SCALEMODE_NEAREST = 2;
  11006. Engine._SCALEMODE_CEILING = 3;
  11007. // Updatable statics so stick with vars here
  11008. Engine.CollisionsEpsilon = 0.001;
  11009. Engine.CodeRepository = "src/";
  11010. Engine.ShadersRepository = "src/Shaders/";
  11011. return Engine;
  11012. }());
  11013. BABYLON.Engine = Engine;
  11014. })(BABYLON || (BABYLON = {}));
  11015. //# sourceMappingURL=babylon.engine.js.map
  11016. /// <reference path="Tools\babylon.decorators.ts" />
  11017. var BABYLON;
  11018. (function (BABYLON) {
  11019. /**
  11020. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11021. */
  11022. var Node = (function () {
  11023. /**
  11024. * @constructor
  11025. * @param {string} name - the name and id to be given to this node
  11026. * @param {BABYLON.Scene} the scene this node will be added to
  11027. */
  11028. function Node(name, scene) {
  11029. this.state = "";
  11030. this.metadata = null;
  11031. this.doNotSerialize = false;
  11032. this.animations = new Array();
  11033. this._ranges = {};
  11034. this._childrenFlag = -1;
  11035. this._isEnabled = true;
  11036. this._isReady = true;
  11037. this._currentRenderId = -1;
  11038. this._parentRenderId = -1;
  11039. /**
  11040. * An event triggered when the mesh is disposed.
  11041. * @type {BABYLON.Observable}
  11042. */
  11043. this.onDisposeObservable = new BABYLON.Observable();
  11044. // Behaviors
  11045. this._behaviors = new Array();
  11046. this.name = name;
  11047. this.id = name;
  11048. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11049. this._initCache();
  11050. }
  11051. Object.defineProperty(Node.prototype, "parent", {
  11052. get: function () {
  11053. return this._parentNode;
  11054. },
  11055. set: function (parent) {
  11056. if (this._parentNode === parent) {
  11057. return;
  11058. }
  11059. if (this._parentNode) {
  11060. var index = this._parentNode._children.indexOf(this);
  11061. if (index !== -1) {
  11062. this._parentNode._children.splice(index, 1);
  11063. }
  11064. }
  11065. this._parentNode = parent;
  11066. if (this._parentNode) {
  11067. if (!this._parentNode._children) {
  11068. this._parentNode._children = new Array();
  11069. }
  11070. this._parentNode._children.push(this);
  11071. }
  11072. },
  11073. enumerable: true,
  11074. configurable: true
  11075. });
  11076. Node.prototype.getClassName = function () {
  11077. return "Node";
  11078. };
  11079. Object.defineProperty(Node.prototype, "onDispose", {
  11080. set: function (callback) {
  11081. if (this._onDisposeObserver) {
  11082. this.onDisposeObservable.remove(this._onDisposeObserver);
  11083. }
  11084. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11085. },
  11086. enumerable: true,
  11087. configurable: true
  11088. });
  11089. Node.prototype.getScene = function () {
  11090. return this._scene;
  11091. };
  11092. Node.prototype.getEngine = function () {
  11093. return this._scene.getEngine();
  11094. };
  11095. Node.prototype.addBehavior = function (behavior) {
  11096. var index = this._behaviors.indexOf(behavior);
  11097. if (index !== -1) {
  11098. return;
  11099. }
  11100. behavior.attach(this);
  11101. this._behaviors.push(behavior);
  11102. return this;
  11103. };
  11104. Node.prototype.removeBehavior = function (behavior) {
  11105. var index = this._behaviors.indexOf(behavior);
  11106. if (index === -1) {
  11107. return;
  11108. }
  11109. this._behaviors[index].detach(this);
  11110. this._behaviors.splice(index, 1);
  11111. return this;
  11112. };
  11113. Object.defineProperty(Node.prototype, "behaviors", {
  11114. get: function () {
  11115. return this._behaviors;
  11116. },
  11117. enumerable: true,
  11118. configurable: true
  11119. });
  11120. Node.prototype.getBehaviorByName = function (name) {
  11121. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11122. var behavior = _a[_i];
  11123. if (behavior.name === name) {
  11124. return behavior;
  11125. }
  11126. }
  11127. return null;
  11128. };
  11129. // override it in derived class
  11130. Node.prototype.getWorldMatrix = function () {
  11131. return BABYLON.Matrix.Identity();
  11132. };
  11133. // override it in derived class if you add new variables to the cache
  11134. // and call the parent class method
  11135. Node.prototype._initCache = function () {
  11136. this._cache = {};
  11137. this._cache.parent = undefined;
  11138. };
  11139. Node.prototype.updateCache = function (force) {
  11140. if (!force && this.isSynchronized())
  11141. return;
  11142. this._cache.parent = this.parent;
  11143. this._updateCache();
  11144. };
  11145. // override it in derived class if you add new variables to the cache
  11146. // and call the parent class method if !ignoreParentClass
  11147. Node.prototype._updateCache = function (ignoreParentClass) {
  11148. };
  11149. // override it in derived class if you add new variables to the cache
  11150. Node.prototype._isSynchronized = function () {
  11151. return true;
  11152. };
  11153. Node.prototype._markSyncedWithParent = function () {
  11154. this._parentRenderId = this.parent._currentRenderId;
  11155. };
  11156. Node.prototype.isSynchronizedWithParent = function () {
  11157. if (!this.parent) {
  11158. return true;
  11159. }
  11160. if (this._parentRenderId !== this.parent._currentRenderId) {
  11161. return false;
  11162. }
  11163. return this.parent.isSynchronized();
  11164. };
  11165. Node.prototype.isSynchronized = function (updateCache) {
  11166. var check = this.hasNewParent();
  11167. check = check || !this.isSynchronizedWithParent();
  11168. check = check || !this._isSynchronized();
  11169. if (updateCache)
  11170. this.updateCache(true);
  11171. return !check;
  11172. };
  11173. Node.prototype.hasNewParent = function (update) {
  11174. if (this._cache.parent === this.parent)
  11175. return false;
  11176. if (update)
  11177. this._cache.parent = this.parent;
  11178. return true;
  11179. };
  11180. /**
  11181. * Is this node ready to be used/rendered
  11182. * @return {boolean} is it ready
  11183. */
  11184. Node.prototype.isReady = function () {
  11185. return this._isReady;
  11186. };
  11187. /**
  11188. * Is this node enabled.
  11189. * If the node has a parent and is enabled, the parent will be inspected as well.
  11190. * @return {boolean} whether this node (and its parent) is enabled.
  11191. * @see setEnabled
  11192. */
  11193. Node.prototype.isEnabled = function () {
  11194. if (!this._isEnabled) {
  11195. return false;
  11196. }
  11197. if (this.parent) {
  11198. return this.parent.isEnabled();
  11199. }
  11200. return true;
  11201. };
  11202. /**
  11203. * Set the enabled state of this node.
  11204. * @param {boolean} value - the new enabled state
  11205. * @see isEnabled
  11206. */
  11207. Node.prototype.setEnabled = function (value) {
  11208. this._isEnabled = value;
  11209. };
  11210. /**
  11211. * Is this node a descendant of the given node.
  11212. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11213. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11214. * @see parent
  11215. */
  11216. Node.prototype.isDescendantOf = function (ancestor) {
  11217. if (this.parent) {
  11218. if (this.parent === ancestor) {
  11219. return true;
  11220. }
  11221. return this.parent.isDescendantOf(ancestor);
  11222. }
  11223. return false;
  11224. };
  11225. /**
  11226. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11227. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11228. * @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.
  11229. * @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.
  11230. */
  11231. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11232. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11233. if (!this._children) {
  11234. return;
  11235. }
  11236. for (var index = 0; index < this._children.length; index++) {
  11237. var item = this._children[index];
  11238. if (!predicate || predicate(item)) {
  11239. results.push(item);
  11240. }
  11241. if (!directDescendantsOnly) {
  11242. item._getDescendants(results, false, predicate);
  11243. }
  11244. }
  11245. };
  11246. /**
  11247. * Will return all nodes that have this node as ascendant.
  11248. * @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.
  11249. * @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.
  11250. * @return {BABYLON.Node[]} all children nodes of all types.
  11251. */
  11252. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11253. var results = [];
  11254. this._getDescendants(results, directDescendantsOnly, predicate);
  11255. return results;
  11256. };
  11257. /**
  11258. * Get all child-meshes of this node.
  11259. */
  11260. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11261. var results = [];
  11262. this._getDescendants(results, directDecendantsOnly, function (node) {
  11263. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11264. });
  11265. return results;
  11266. };
  11267. /**
  11268. * Get all direct children of this node.
  11269. */
  11270. Node.prototype.getChildren = function (predicate) {
  11271. return this.getDescendants(true, predicate);
  11272. };
  11273. Node.prototype._setReady = function (state) {
  11274. if (state === this._isReady) {
  11275. return;
  11276. }
  11277. if (!state) {
  11278. this._isReady = false;
  11279. return;
  11280. }
  11281. this._isReady = true;
  11282. if (this.onReady) {
  11283. this.onReady(this);
  11284. }
  11285. };
  11286. Node.prototype.getAnimationByName = function (name) {
  11287. for (var i = 0; i < this.animations.length; i++) {
  11288. var animation = this.animations[i];
  11289. if (animation.name === name) {
  11290. return animation;
  11291. }
  11292. }
  11293. return null;
  11294. };
  11295. Node.prototype.createAnimationRange = function (name, from, to) {
  11296. // check name not already in use
  11297. if (!this._ranges[name]) {
  11298. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11299. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11300. if (this.animations[i]) {
  11301. this.animations[i].createRange(name, from, to);
  11302. }
  11303. }
  11304. }
  11305. };
  11306. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11307. if (deleteFrames === void 0) { deleteFrames = true; }
  11308. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11309. if (this.animations[i]) {
  11310. this.animations[i].deleteRange(name, deleteFrames);
  11311. }
  11312. }
  11313. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11314. };
  11315. Node.prototype.getAnimationRange = function (name) {
  11316. return this._ranges[name];
  11317. };
  11318. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11319. var range = this.getAnimationRange(name);
  11320. if (!range) {
  11321. return null;
  11322. }
  11323. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11324. };
  11325. Node.prototype.serializeAnimationRanges = function () {
  11326. var serializationRanges = [];
  11327. for (var name in this._ranges) {
  11328. var range = {};
  11329. range.name = name;
  11330. range.from = this._ranges[name].from;
  11331. range.to = this._ranges[name].to;
  11332. serializationRanges.push(range);
  11333. }
  11334. return serializationRanges;
  11335. };
  11336. Node.prototype.dispose = function () {
  11337. this.parent = null;
  11338. // Callback
  11339. this.onDisposeObservable.notifyObservers(this);
  11340. this.onDisposeObservable.clear();
  11341. // Behaviors
  11342. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11343. var behavior = _a[_i];
  11344. behavior.detach(this);
  11345. }
  11346. };
  11347. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11348. if (parsedNode.ranges) {
  11349. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11350. var data = parsedNode.ranges[index];
  11351. node.createAnimationRange(data.name, data.from, data.to);
  11352. }
  11353. }
  11354. };
  11355. __decorate([
  11356. BABYLON.serialize()
  11357. ], Node.prototype, "name", void 0);
  11358. __decorate([
  11359. BABYLON.serialize()
  11360. ], Node.prototype, "id", void 0);
  11361. __decorate([
  11362. BABYLON.serialize()
  11363. ], Node.prototype, "uniqueId", void 0);
  11364. __decorate([
  11365. BABYLON.serialize()
  11366. ], Node.prototype, "state", void 0);
  11367. __decorate([
  11368. BABYLON.serialize()
  11369. ], Node.prototype, "metadata", void 0);
  11370. return Node;
  11371. }());
  11372. BABYLON.Node = Node;
  11373. })(BABYLON || (BABYLON = {}));
  11374. //# sourceMappingURL=babylon.node.js.map
  11375. var BABYLON;
  11376. (function (BABYLON) {
  11377. var BoundingSphere = (function () {
  11378. function BoundingSphere(minimum, maximum) {
  11379. this.minimum = minimum;
  11380. this.maximum = maximum;
  11381. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11382. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11383. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11384. this.radius = distance * 0.5;
  11385. this.centerWorld = BABYLON.Vector3.Zero();
  11386. this._update(BABYLON.Matrix.Identity());
  11387. }
  11388. // Methods
  11389. BoundingSphere.prototype._update = function (world) {
  11390. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11391. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11392. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11393. };
  11394. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11395. for (var i = 0; i < 6; i++) {
  11396. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11397. return false;
  11398. }
  11399. return true;
  11400. };
  11401. BoundingSphere.prototype.intersectsPoint = function (point) {
  11402. var x = this.centerWorld.x - point.x;
  11403. var y = this.centerWorld.y - point.y;
  11404. var z = this.centerWorld.z - point.z;
  11405. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11406. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11407. return false;
  11408. return true;
  11409. };
  11410. // Statics
  11411. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11412. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11413. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11414. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11415. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11416. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11417. return false;
  11418. return true;
  11419. };
  11420. return BoundingSphere;
  11421. }());
  11422. BABYLON.BoundingSphere = BoundingSphere;
  11423. })(BABYLON || (BABYLON = {}));
  11424. //# sourceMappingURL=babylon.boundingSphere.js.map
  11425. var BABYLON;
  11426. (function (BABYLON) {
  11427. var BoundingBox = (function () {
  11428. function BoundingBox(minimum, maximum) {
  11429. this.minimum = minimum;
  11430. this.maximum = maximum;
  11431. this.vectors = new Array();
  11432. this.vectorsWorld = new Array();
  11433. // Bounding vectors
  11434. this.vectors.push(this.minimum.clone());
  11435. this.vectors.push(this.maximum.clone());
  11436. this.vectors.push(this.minimum.clone());
  11437. this.vectors[2].x = this.maximum.x;
  11438. this.vectors.push(this.minimum.clone());
  11439. this.vectors[3].y = this.maximum.y;
  11440. this.vectors.push(this.minimum.clone());
  11441. this.vectors[4].z = this.maximum.z;
  11442. this.vectors.push(this.maximum.clone());
  11443. this.vectors[5].z = this.minimum.z;
  11444. this.vectors.push(this.maximum.clone());
  11445. this.vectors[6].x = this.minimum.x;
  11446. this.vectors.push(this.maximum.clone());
  11447. this.vectors[7].y = this.minimum.y;
  11448. // OBB
  11449. this.center = this.maximum.add(this.minimum).scale(0.5);
  11450. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11451. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11452. // World
  11453. for (var index = 0; index < this.vectors.length; index++) {
  11454. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11455. }
  11456. this.minimumWorld = BABYLON.Vector3.Zero();
  11457. this.maximumWorld = BABYLON.Vector3.Zero();
  11458. this.centerWorld = BABYLON.Vector3.Zero();
  11459. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11460. this._update(BABYLON.Matrix.Identity());
  11461. }
  11462. // Methods
  11463. BoundingBox.prototype.getWorldMatrix = function () {
  11464. return this._worldMatrix;
  11465. };
  11466. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11467. this._worldMatrix.copyFrom(matrix);
  11468. return this;
  11469. };
  11470. BoundingBox.prototype._update = function (world) {
  11471. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11472. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11473. for (var index = 0; index < this.vectors.length; index++) {
  11474. var v = this.vectorsWorld[index];
  11475. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11476. if (v.x < this.minimumWorld.x)
  11477. this.minimumWorld.x = v.x;
  11478. if (v.y < this.minimumWorld.y)
  11479. this.minimumWorld.y = v.y;
  11480. if (v.z < this.minimumWorld.z)
  11481. this.minimumWorld.z = v.z;
  11482. if (v.x > this.maximumWorld.x)
  11483. this.maximumWorld.x = v.x;
  11484. if (v.y > this.maximumWorld.y)
  11485. this.maximumWorld.y = v.y;
  11486. if (v.z > this.maximumWorld.z)
  11487. this.maximumWorld.z = v.z;
  11488. }
  11489. // Extend
  11490. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11491. this.extendSizeWorld.scaleInPlace(0.5);
  11492. // OBB
  11493. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11494. this.centerWorld.scaleInPlace(0.5);
  11495. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11496. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11497. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11498. this._worldMatrix = world;
  11499. };
  11500. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11501. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11502. };
  11503. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11504. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11505. };
  11506. BoundingBox.prototype.intersectsPoint = function (point) {
  11507. var delta = -BABYLON.Epsilon;
  11508. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11509. return false;
  11510. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11511. return false;
  11512. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11513. return false;
  11514. return true;
  11515. };
  11516. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11517. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11518. };
  11519. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11520. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11521. return false;
  11522. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11523. return false;
  11524. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11525. return false;
  11526. return true;
  11527. };
  11528. // Statics
  11529. BoundingBox.Intersects = function (box0, box1) {
  11530. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11531. return false;
  11532. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11533. return false;
  11534. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11535. return false;
  11536. return true;
  11537. };
  11538. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11539. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11540. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11541. return (num <= (sphereRadius * sphereRadius));
  11542. };
  11543. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11544. for (var p = 0; p < 6; p++) {
  11545. for (var i = 0; i < 8; i++) {
  11546. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11547. return false;
  11548. }
  11549. }
  11550. }
  11551. return true;
  11552. };
  11553. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11554. for (var p = 0; p < 6; p++) {
  11555. var inCount = 8;
  11556. for (var i = 0; i < 8; i++) {
  11557. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11558. --inCount;
  11559. }
  11560. else {
  11561. break;
  11562. }
  11563. }
  11564. if (inCount === 0)
  11565. return false;
  11566. }
  11567. return true;
  11568. };
  11569. return BoundingBox;
  11570. }());
  11571. BABYLON.BoundingBox = BoundingBox;
  11572. })(BABYLON || (BABYLON = {}));
  11573. //# sourceMappingURL=babylon.boundingBox.js.map
  11574. var BABYLON;
  11575. (function (BABYLON) {
  11576. var computeBoxExtents = function (axis, box) {
  11577. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11578. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11579. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11580. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11581. var r = r0 + r1 + r2;
  11582. return {
  11583. min: p - r,
  11584. max: p + r
  11585. };
  11586. };
  11587. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11588. var axisOverlap = function (axis, box0, box1) {
  11589. var result0 = computeBoxExtents(axis, box0);
  11590. var result1 = computeBoxExtents(axis, box1);
  11591. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11592. };
  11593. var BoundingInfo = (function () {
  11594. function BoundingInfo(minimum, maximum) {
  11595. this.minimum = minimum;
  11596. this.maximum = maximum;
  11597. this._isLocked = false;
  11598. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11599. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11600. }
  11601. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11602. get: function () {
  11603. return this._isLocked;
  11604. },
  11605. set: function (value) {
  11606. this._isLocked = value;
  11607. },
  11608. enumerable: true,
  11609. configurable: true
  11610. });
  11611. // Methods
  11612. BoundingInfo.prototype.update = function (world) {
  11613. if (this._isLocked) {
  11614. return;
  11615. }
  11616. this.boundingBox._update(world);
  11617. this.boundingSphere._update(world);
  11618. };
  11619. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11620. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11621. return false;
  11622. return this.boundingBox.isInFrustum(frustumPlanes);
  11623. };
  11624. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  11625. /**
  11626. * Gets the world distance between the min and max points of the bounding box
  11627. */
  11628. get: function () {
  11629. var boundingBox = this.boundingBox;
  11630. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  11631. return size.length();
  11632. },
  11633. enumerable: true,
  11634. configurable: true
  11635. });
  11636. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11637. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11638. };
  11639. BoundingInfo.prototype._checkCollision = function (collider) {
  11640. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11641. };
  11642. BoundingInfo.prototype.intersectsPoint = function (point) {
  11643. if (!this.boundingSphere.centerWorld) {
  11644. return false;
  11645. }
  11646. if (!this.boundingSphere.intersectsPoint(point)) {
  11647. return false;
  11648. }
  11649. if (!this.boundingBox.intersectsPoint(point)) {
  11650. return false;
  11651. }
  11652. return true;
  11653. };
  11654. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11655. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11656. return false;
  11657. }
  11658. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11659. return false;
  11660. }
  11661. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11662. return false;
  11663. }
  11664. if (!precise) {
  11665. return true;
  11666. }
  11667. var box0 = this.boundingBox;
  11668. var box1 = boundingInfo.boundingBox;
  11669. if (!axisOverlap(box0.directions[0], box0, box1))
  11670. return false;
  11671. if (!axisOverlap(box0.directions[1], box0, box1))
  11672. return false;
  11673. if (!axisOverlap(box0.directions[2], box0, box1))
  11674. return false;
  11675. if (!axisOverlap(box1.directions[0], box0, box1))
  11676. return false;
  11677. if (!axisOverlap(box1.directions[1], box0, box1))
  11678. return false;
  11679. if (!axisOverlap(box1.directions[2], box0, box1))
  11680. return false;
  11681. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11682. return false;
  11683. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11684. return false;
  11685. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11686. return false;
  11687. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11688. return false;
  11689. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11690. return false;
  11691. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11692. return false;
  11693. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11694. return false;
  11695. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11696. return false;
  11697. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11698. return false;
  11699. return true;
  11700. };
  11701. return BoundingInfo;
  11702. }());
  11703. BABYLON.BoundingInfo = BoundingInfo;
  11704. })(BABYLON || (BABYLON = {}));
  11705. //# sourceMappingURL=babylon.boundingInfo.js.map
  11706. var BABYLON;
  11707. (function (BABYLON) {
  11708. var AbstractMesh = (function (_super) {
  11709. __extends(AbstractMesh, _super);
  11710. // Constructor
  11711. function AbstractMesh(name, scene) {
  11712. var _this = _super.call(this, name, scene) || this;
  11713. _this._facetNb = 0; // facet number
  11714. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11715. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11716. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11717. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11718. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11719. _this._subDiv = {
  11720. max: 1,
  11721. X: 1,
  11722. Y: 1,
  11723. Z: 1
  11724. };
  11725. // Events
  11726. /**
  11727. * An event triggered when this mesh collides with another one
  11728. * @type {BABYLON.Observable}
  11729. */
  11730. _this.onCollideObservable = new BABYLON.Observable();
  11731. /**
  11732. * An event triggered when the collision's position changes
  11733. * @type {BABYLON.Observable}
  11734. */
  11735. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11736. /**
  11737. * An event triggered after the world matrix is updated
  11738. * @type {BABYLON.Observable}
  11739. */
  11740. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11741. /**
  11742. * An event triggered when material is changed
  11743. * @type {BABYLON.Observable}
  11744. */
  11745. _this.onMaterialChangedObservable = new BABYLON.Observable();
  11746. // Properties
  11747. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11748. _this.position = BABYLON.Vector3.Zero();
  11749. _this._rotation = BABYLON.Vector3.Zero();
  11750. _this._scaling = BABYLON.Vector3.One();
  11751. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11752. _this.visibility = 1.0;
  11753. _this.alphaIndex = Number.MAX_VALUE;
  11754. _this.infiniteDistance = false;
  11755. _this.isVisible = true;
  11756. _this.isPickable = true;
  11757. _this.showBoundingBox = false;
  11758. _this.showSubMeshesBoundingBox = false;
  11759. _this.isBlocker = false;
  11760. _this.enablePointerMoveEvents = false;
  11761. _this.renderingGroupId = 0;
  11762. _this._receiveShadows = false;
  11763. _this.renderOutline = false;
  11764. _this.outlineColor = BABYLON.Color3.Red();
  11765. _this.outlineWidth = 0.02;
  11766. _this.renderOverlay = false;
  11767. _this.overlayColor = BABYLON.Color3.Red();
  11768. _this.overlayAlpha = 0.5;
  11769. _this._hasVertexAlpha = false;
  11770. _this._useVertexColors = true;
  11771. _this._computeBonesUsingShaders = true;
  11772. _this._numBoneInfluencers = 4;
  11773. _this._applyFog = true;
  11774. _this.scalingDeterminant = 1;
  11775. _this.useOctreeForRenderingSelection = true;
  11776. _this.useOctreeForPicking = true;
  11777. _this.useOctreeForCollisions = true;
  11778. _this.layerMask = 0x0FFFFFFF;
  11779. /**
  11780. * True if the mesh must be rendered in any case.
  11781. */
  11782. _this.alwaysSelectAsActiveMesh = false;
  11783. // Collisions
  11784. _this._checkCollisions = false;
  11785. _this._collisionMask = -1;
  11786. _this._collisionGroup = -1;
  11787. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11788. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11789. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11790. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11791. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11792. // Edges
  11793. _this.edgesWidth = 1;
  11794. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11795. // Cache
  11796. _this._localWorld = BABYLON.Matrix.Zero();
  11797. _this._worldMatrix = BABYLON.Matrix.Zero();
  11798. _this._absolutePosition = BABYLON.Vector3.Zero();
  11799. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11800. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11801. _this._isDirty = false;
  11802. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11803. _this._isDisposed = false;
  11804. _this._renderId = 0;
  11805. _this._intersectionsInProgress = new Array();
  11806. _this._isWorldMatrixFrozen = false;
  11807. _this._unIndexed = false;
  11808. _this._lightSources = new Array();
  11809. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11810. if (collidedMesh === void 0) { collidedMesh = null; }
  11811. //TODO move this to the collision coordinator!
  11812. if (_this.getScene().workerCollisions)
  11813. newPosition.multiplyInPlace(_this._collider.radius);
  11814. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11815. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11816. _this.position.addInPlace(_this._diffPositionForCollisions);
  11817. }
  11818. if (collidedMesh) {
  11819. _this.onCollideObservable.notifyObservers(collidedMesh);
  11820. }
  11821. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11822. };
  11823. _this.getScene().addMesh(_this);
  11824. _this._resyncLightSources();
  11825. return _this;
  11826. }
  11827. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11828. get: function () {
  11829. return AbstractMesh._BILLBOARDMODE_NONE;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11835. get: function () {
  11836. return AbstractMesh._BILLBOARDMODE_X;
  11837. },
  11838. enumerable: true,
  11839. configurable: true
  11840. });
  11841. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11842. get: function () {
  11843. return AbstractMesh._BILLBOARDMODE_Y;
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11849. get: function () {
  11850. return AbstractMesh._BILLBOARDMODE_Z;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11856. get: function () {
  11857. return AbstractMesh._BILLBOARDMODE_ALL;
  11858. },
  11859. enumerable: true,
  11860. configurable: true
  11861. });
  11862. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11863. /**
  11864. * Read-only : the number of facets in the mesh
  11865. */
  11866. get: function () {
  11867. return this._facetNb;
  11868. },
  11869. enumerable: true,
  11870. configurable: true
  11871. });
  11872. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11873. /**
  11874. * The number (integer) of subdivisions per axis in the partioning space
  11875. */
  11876. get: function () {
  11877. return this._partitioningSubdivisions;
  11878. },
  11879. set: function (nb) {
  11880. this._partitioningSubdivisions = nb;
  11881. },
  11882. enumerable: true,
  11883. configurable: true
  11884. });
  11885. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11886. /**
  11887. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11888. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11889. */
  11890. get: function () {
  11891. return this._partitioningBBoxRatio;
  11892. },
  11893. set: function (ratio) {
  11894. this._partitioningBBoxRatio = ratio;
  11895. },
  11896. enumerable: true,
  11897. configurable: true
  11898. });
  11899. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11900. /**
  11901. * Read-only boolean : is the feature facetData enabled ?
  11902. */
  11903. get: function () {
  11904. return this._facetDataEnabled;
  11905. },
  11906. enumerable: true,
  11907. configurable: true
  11908. });
  11909. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11910. set: function (callback) {
  11911. if (this._onCollideObserver) {
  11912. this.onCollideObservable.remove(this._onCollideObserver);
  11913. }
  11914. this._onCollideObserver = this.onCollideObservable.add(callback);
  11915. },
  11916. enumerable: true,
  11917. configurable: true
  11918. });
  11919. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11920. set: function (callback) {
  11921. if (this._onCollisionPositionChangeObserver) {
  11922. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11923. }
  11924. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11925. },
  11926. enumerable: true,
  11927. configurable: true
  11928. });
  11929. Object.defineProperty(AbstractMesh.prototype, "material", {
  11930. get: function () {
  11931. return this._material;
  11932. },
  11933. set: function (value) {
  11934. if (this._material === value) {
  11935. return;
  11936. }
  11937. this._material = value;
  11938. if (this.onMaterialChangedObservable.hasObservers) {
  11939. this.onMaterialChangedObservable.notifyObservers(this);
  11940. }
  11941. if (!this.subMeshes) {
  11942. return;
  11943. }
  11944. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11945. var subMesh = _a[_i];
  11946. subMesh.setEffect(null);
  11947. }
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11953. get: function () {
  11954. return this._receiveShadows;
  11955. },
  11956. set: function (value) {
  11957. if (this._receiveShadows === value) {
  11958. return;
  11959. }
  11960. this._receiveShadows = value;
  11961. this._markSubMeshesAsLightDirty();
  11962. },
  11963. enumerable: true,
  11964. configurable: true
  11965. });
  11966. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11967. get: function () {
  11968. return this._hasVertexAlpha;
  11969. },
  11970. set: function (value) {
  11971. if (this._hasVertexAlpha === value) {
  11972. return;
  11973. }
  11974. this._hasVertexAlpha = value;
  11975. this._markSubMeshesAsAttributesDirty();
  11976. },
  11977. enumerable: true,
  11978. configurable: true
  11979. });
  11980. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11981. get: function () {
  11982. return this._useVertexColors;
  11983. },
  11984. set: function (value) {
  11985. if (this._useVertexColors === value) {
  11986. return;
  11987. }
  11988. this._useVertexColors = value;
  11989. this._markSubMeshesAsAttributesDirty();
  11990. },
  11991. enumerable: true,
  11992. configurable: true
  11993. });
  11994. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11995. get: function () {
  11996. return this._computeBonesUsingShaders;
  11997. },
  11998. set: function (value) {
  11999. if (this._computeBonesUsingShaders === value) {
  12000. return;
  12001. }
  12002. this._computeBonesUsingShaders = value;
  12003. this._markSubMeshesAsAttributesDirty();
  12004. },
  12005. enumerable: true,
  12006. configurable: true
  12007. });
  12008. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12009. get: function () {
  12010. return this._numBoneInfluencers;
  12011. },
  12012. set: function (value) {
  12013. if (this._numBoneInfluencers === value) {
  12014. return;
  12015. }
  12016. this._numBoneInfluencers = value;
  12017. this._markSubMeshesAsAttributesDirty();
  12018. },
  12019. enumerable: true,
  12020. configurable: true
  12021. });
  12022. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12023. get: function () {
  12024. return this._applyFog;
  12025. },
  12026. set: function (value) {
  12027. if (this._applyFog === value) {
  12028. return;
  12029. }
  12030. this._applyFog = value;
  12031. this._markSubMeshesAsMiscDirty();
  12032. },
  12033. enumerable: true,
  12034. configurable: true
  12035. });
  12036. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12037. get: function () {
  12038. return this._collisionMask;
  12039. },
  12040. set: function (mask) {
  12041. this._collisionMask = !isNaN(mask) ? mask : -1;
  12042. },
  12043. enumerable: true,
  12044. configurable: true
  12045. });
  12046. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12047. get: function () {
  12048. return this._collisionGroup;
  12049. },
  12050. set: function (mask) {
  12051. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12052. },
  12053. enumerable: true,
  12054. configurable: true
  12055. });
  12056. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12057. get: function () {
  12058. return null;
  12059. },
  12060. enumerable: true,
  12061. configurable: true
  12062. });
  12063. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12064. get: function () {
  12065. return this._skeleton;
  12066. },
  12067. set: function (value) {
  12068. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12069. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12070. }
  12071. if (value && value.needInitialSkinMatrix) {
  12072. value._registerMeshWithPoseMatrix(this);
  12073. }
  12074. this._skeleton = value;
  12075. if (!this._skeleton) {
  12076. this._bonesTransformMatrices = null;
  12077. }
  12078. this._markSubMeshesAsAttributesDirty();
  12079. },
  12080. enumerable: true,
  12081. configurable: true
  12082. });
  12083. /**
  12084. * Boolean : true if the mesh has been disposed.
  12085. */
  12086. AbstractMesh.prototype.isDisposed = function () {
  12087. return this._isDisposed;
  12088. };
  12089. /**
  12090. * Returns the string "AbstractMesh"
  12091. */
  12092. AbstractMesh.prototype.getClassName = function () {
  12093. return "AbstractMesh";
  12094. };
  12095. /**
  12096. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12097. */
  12098. AbstractMesh.prototype.toString = function (fullDetails) {
  12099. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12100. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12101. if (this._skeleton) {
  12102. ret += ", skeleton: " + this._skeleton.name;
  12103. }
  12104. if (fullDetails) {
  12105. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12106. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12107. }
  12108. return ret;
  12109. };
  12110. AbstractMesh.prototype._resyncLightSources = function () {
  12111. this._lightSources.length = 0;
  12112. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12113. var light = _a[_i];
  12114. if (!light.isEnabled()) {
  12115. continue;
  12116. }
  12117. if (light.canAffectMesh(this)) {
  12118. this._lightSources.push(light);
  12119. }
  12120. }
  12121. this._markSubMeshesAsLightDirty();
  12122. };
  12123. AbstractMesh.prototype._resyncLighSource = function (light) {
  12124. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12125. var index = this._lightSources.indexOf(light);
  12126. if (index === -1) {
  12127. if (!isIn) {
  12128. return;
  12129. }
  12130. this._lightSources.push(light);
  12131. }
  12132. else {
  12133. if (isIn) {
  12134. return;
  12135. }
  12136. this._lightSources.splice(index, 1);
  12137. }
  12138. this._markSubMeshesAsLightDirty();
  12139. };
  12140. AbstractMesh.prototype._removeLightSource = function (light) {
  12141. var index = this._lightSources.indexOf(light);
  12142. if (index === -1) {
  12143. return;
  12144. }
  12145. this._lightSources.splice(index, 1);
  12146. };
  12147. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12148. if (!this.subMeshes) {
  12149. return;
  12150. }
  12151. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12152. var subMesh = _a[_i];
  12153. if (subMesh._materialDefines) {
  12154. func(subMesh._materialDefines);
  12155. }
  12156. }
  12157. };
  12158. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12159. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12160. };
  12161. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12162. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12163. };
  12164. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12165. if (!this.subMeshes) {
  12166. return;
  12167. }
  12168. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12169. var subMesh = _a[_i];
  12170. var material = subMesh.getMaterial();
  12171. if (material) {
  12172. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12173. }
  12174. }
  12175. };
  12176. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12177. /**
  12178. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12179. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12180. * Default : (0.0, 0.0, 0.0)
  12181. */
  12182. get: function () {
  12183. return this._rotation;
  12184. },
  12185. set: function (newRotation) {
  12186. this._rotation = newRotation;
  12187. },
  12188. enumerable: true,
  12189. configurable: true
  12190. });
  12191. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12192. /**
  12193. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12194. * Default : (1.0, 1.0, 1.0)
  12195. */
  12196. get: function () {
  12197. return this._scaling;
  12198. },
  12199. set: function (newScaling) {
  12200. this._scaling = newScaling;
  12201. if (this.physicsImpostor) {
  12202. this.physicsImpostor.forceUpdate();
  12203. }
  12204. },
  12205. enumerable: true,
  12206. configurable: true
  12207. });
  12208. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12209. /**
  12210. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12211. * It's null by default.
  12212. * 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)
  12213. */
  12214. get: function () {
  12215. return this._rotationQuaternion;
  12216. },
  12217. set: function (quaternion) {
  12218. this._rotationQuaternion = quaternion;
  12219. //reset the rotation vector.
  12220. if (quaternion && this.rotation.length()) {
  12221. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12222. }
  12223. },
  12224. enumerable: true,
  12225. configurable: true
  12226. });
  12227. // Methods
  12228. /**
  12229. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12230. * Returns the AbstractMesh.
  12231. */
  12232. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12233. this._poseMatrix.copyFrom(matrix);
  12234. return this;
  12235. };
  12236. /**
  12237. * Returns the mesh Pose matrix.
  12238. * Returned object : Matrix
  12239. */
  12240. AbstractMesh.prototype.getPoseMatrix = function () {
  12241. return this._poseMatrix;
  12242. };
  12243. /**
  12244. * Disables the mesh edger rendering mode.
  12245. * Returns the AbstractMesh.
  12246. */
  12247. AbstractMesh.prototype.disableEdgesRendering = function () {
  12248. if (this._edgesRenderer !== undefined) {
  12249. this._edgesRenderer.dispose();
  12250. this._edgesRenderer = undefined;
  12251. }
  12252. return this;
  12253. };
  12254. /**
  12255. * Enables the edge rendering mode on the mesh.
  12256. * This mode makes the mesh edges visible.
  12257. * Returns the AbstractMesh.
  12258. */
  12259. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12260. if (epsilon === void 0) { epsilon = 0.95; }
  12261. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12262. this.disableEdgesRendering();
  12263. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12264. return this;
  12265. };
  12266. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12267. /**
  12268. * Returns true if the mesh is blocked. Used by the class Mesh.
  12269. * Returns the boolean `false` by default.
  12270. */
  12271. get: function () {
  12272. return false;
  12273. },
  12274. enumerable: true,
  12275. configurable: true
  12276. });
  12277. /**
  12278. * Returns the mesh itself by default, used by the class Mesh.
  12279. * Returned type : AbstractMesh
  12280. */
  12281. AbstractMesh.prototype.getLOD = function (camera) {
  12282. return this;
  12283. };
  12284. /**
  12285. * Returns 0 by default, used by the class Mesh.
  12286. * Returns an integer.
  12287. */
  12288. AbstractMesh.prototype.getTotalVertices = function () {
  12289. return 0;
  12290. };
  12291. /**
  12292. * Returns null by default, used by the class Mesh.
  12293. * Returned type : integer array
  12294. */
  12295. AbstractMesh.prototype.getIndices = function () {
  12296. return null;
  12297. };
  12298. /**
  12299. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12300. * Returned type : float array or Float32Array
  12301. */
  12302. AbstractMesh.prototype.getVerticesData = function (kind) {
  12303. return null;
  12304. };
  12305. /**
  12306. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12307. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12308. * The `data` are either a numeric array either a Float32Array.
  12309. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12310. * 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).
  12311. * Note that a new underlying VertexBuffer object is created each call.
  12312. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12313. *
  12314. * Possible `kind` values :
  12315. * - BABYLON.VertexBuffer.PositionKind
  12316. * - BABYLON.VertexBuffer.UVKind
  12317. * - BABYLON.VertexBuffer.UV2Kind
  12318. * - BABYLON.VertexBuffer.UV3Kind
  12319. * - BABYLON.VertexBuffer.UV4Kind
  12320. * - BABYLON.VertexBuffer.UV5Kind
  12321. * - BABYLON.VertexBuffer.UV6Kind
  12322. * - BABYLON.VertexBuffer.ColorKind
  12323. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12324. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12325. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12326. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12327. *
  12328. * Returns the Mesh.
  12329. */
  12330. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12331. return null;
  12332. };
  12333. /**
  12334. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12335. * If the mesh has no geometry, it is simply returned as it is.
  12336. * The `data` are either a numeric array either a Float32Array.
  12337. * No new underlying VertexBuffer object is created.
  12338. * 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.
  12339. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12340. *
  12341. * Possible `kind` values :
  12342. * - BABYLON.VertexBuffer.PositionKind
  12343. * - BABYLON.VertexBuffer.UVKind
  12344. * - BABYLON.VertexBuffer.UV2Kind
  12345. * - BABYLON.VertexBuffer.UV3Kind
  12346. * - BABYLON.VertexBuffer.UV4Kind
  12347. * - BABYLON.VertexBuffer.UV5Kind
  12348. * - BABYLON.VertexBuffer.UV6Kind
  12349. * - BABYLON.VertexBuffer.ColorKind
  12350. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12351. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12352. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12353. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12354. *
  12355. * Returns the Mesh.
  12356. */
  12357. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12358. return null;
  12359. };
  12360. /**
  12361. * Sets the mesh indices.
  12362. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12363. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12364. * This method creates a new index buffer each call.
  12365. * Returns the Mesh.
  12366. */
  12367. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12368. return null;
  12369. };
  12370. /** Returns false by default, used by the class Mesh.
  12371. * Returns a boolean
  12372. */
  12373. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12374. return false;
  12375. };
  12376. /**
  12377. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12378. * Returns a BoundingInfo
  12379. */
  12380. AbstractMesh.prototype.getBoundingInfo = function () {
  12381. if (this._masterMesh) {
  12382. return this._masterMesh.getBoundingInfo();
  12383. }
  12384. if (!this._boundingInfo) {
  12385. this._updateBoundingInfo();
  12386. }
  12387. return this._boundingInfo;
  12388. };
  12389. /**
  12390. * Sets a mesh new object BoundingInfo.
  12391. * Returns the AbstractMesh.
  12392. */
  12393. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12394. this._boundingInfo = boundingInfo;
  12395. return this;
  12396. };
  12397. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12398. get: function () {
  12399. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12400. },
  12401. enumerable: true,
  12402. configurable: true
  12403. });
  12404. AbstractMesh.prototype._preActivate = function () {
  12405. };
  12406. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12407. };
  12408. AbstractMesh.prototype._activate = function (renderId) {
  12409. this._renderId = renderId;
  12410. };
  12411. /**
  12412. * Returns the last update of the World matrix
  12413. * Returns a Matrix.
  12414. */
  12415. AbstractMesh.prototype.getWorldMatrix = function () {
  12416. if (this._masterMesh) {
  12417. return this._masterMesh.getWorldMatrix();
  12418. }
  12419. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12420. this.computeWorldMatrix();
  12421. }
  12422. return this._worldMatrix;
  12423. };
  12424. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12425. /**
  12426. * Returns directly the last state of the mesh World matrix.
  12427. * A Matrix is returned.
  12428. */
  12429. get: function () {
  12430. return this._worldMatrix;
  12431. },
  12432. enumerable: true,
  12433. configurable: true
  12434. });
  12435. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12436. /**
  12437. * Returns the current mesh absolute position.
  12438. * Retuns a Vector3.
  12439. */
  12440. get: function () {
  12441. return this._absolutePosition;
  12442. },
  12443. enumerable: true,
  12444. configurable: true
  12445. });
  12446. /**
  12447. * Prevents the World matrix to be computed any longer.
  12448. * Returns the AbstractMesh.
  12449. */
  12450. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12451. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12452. this.computeWorldMatrix(true);
  12453. this._isWorldMatrixFrozen = true;
  12454. return this;
  12455. };
  12456. /**
  12457. * Allows back the World matrix computation.
  12458. * Returns the AbstractMesh.
  12459. */
  12460. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12461. this._isWorldMatrixFrozen = false;
  12462. this.computeWorldMatrix(true);
  12463. return this;
  12464. };
  12465. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12466. /**
  12467. * True if the World matrix has been frozen.
  12468. * Returns a boolean.
  12469. */
  12470. get: function () {
  12471. return this._isWorldMatrixFrozen;
  12472. },
  12473. enumerable: true,
  12474. configurable: true
  12475. });
  12476. /**
  12477. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12478. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12479. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12480. * The passed axis is also normalized.
  12481. * Returns the AbstractMesh.
  12482. */
  12483. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12484. axis.normalize();
  12485. if (!this.rotationQuaternion) {
  12486. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12487. this.rotation = BABYLON.Vector3.Zero();
  12488. }
  12489. var rotationQuaternion;
  12490. if (!space || space === BABYLON.Space.LOCAL) {
  12491. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12492. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12493. }
  12494. else {
  12495. if (this.parent) {
  12496. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12497. invertParentWorldMatrix.invert();
  12498. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12499. }
  12500. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12501. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12502. }
  12503. return this;
  12504. };
  12505. /**
  12506. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12507. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12508. * The passed axis is also normalized.
  12509. * Returns the AbstractMesh.
  12510. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12511. */
  12512. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12513. axis.normalize();
  12514. if (!this.rotationQuaternion) {
  12515. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12516. this.rotation.copyFromFloats(0, 0, 0);
  12517. }
  12518. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12519. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12520. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12521. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12522. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12523. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12524. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12525. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12526. this.rotationQuaternion.multiplyInPlace(BABYLON.Tmp.Quaternion[0]);
  12527. return this;
  12528. };
  12529. /**
  12530. * Translates the mesh along the axis vector for the passed distance in the given space.
  12531. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12532. * Returns the AbstractMesh.
  12533. */
  12534. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12535. var displacementVector = axis.scale(distance);
  12536. if (!space || space === BABYLON.Space.LOCAL) {
  12537. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12538. this.setPositionWithLocalVector(tempV3);
  12539. }
  12540. else {
  12541. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12542. }
  12543. return this;
  12544. };
  12545. /**
  12546. * Adds a rotation step to the mesh current rotation.
  12547. * x, y, z are Euler angles expressed in radians.
  12548. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12549. * This means this rotation is made in the mesh local space only.
  12550. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12551. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12552. * ```javascript
  12553. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12554. * ```
  12555. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12556. * 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.
  12557. * Returns the AbstractMesh.
  12558. */
  12559. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12560. var rotationQuaternion;
  12561. if (this.rotationQuaternion) {
  12562. rotationQuaternion = this.rotationQuaternion;
  12563. }
  12564. else {
  12565. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12566. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12567. }
  12568. var accumulation = BABYLON.Tmp.Quaternion[0];
  12569. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12570. rotationQuaternion.multiplyInPlace(accumulation);
  12571. if (!this.rotationQuaternion) {
  12572. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12573. }
  12574. return this;
  12575. };
  12576. /**
  12577. * Retuns the mesh absolute position in the World.
  12578. * Returns a Vector3.
  12579. */
  12580. AbstractMesh.prototype.getAbsolutePosition = function () {
  12581. this.computeWorldMatrix();
  12582. return this._absolutePosition;
  12583. };
  12584. /**
  12585. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12586. * Returns the AbstractMesh.
  12587. */
  12588. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12589. if (!absolutePosition) {
  12590. return;
  12591. }
  12592. var absolutePositionX;
  12593. var absolutePositionY;
  12594. var absolutePositionZ;
  12595. if (absolutePosition.x === undefined) {
  12596. if (arguments.length < 3) {
  12597. return;
  12598. }
  12599. absolutePositionX = arguments[0];
  12600. absolutePositionY = arguments[1];
  12601. absolutePositionZ = arguments[2];
  12602. }
  12603. else {
  12604. absolutePositionX = absolutePosition.x;
  12605. absolutePositionY = absolutePosition.y;
  12606. absolutePositionZ = absolutePosition.z;
  12607. }
  12608. if (this.parent) {
  12609. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12610. invertParentWorldMatrix.invert();
  12611. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12612. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12613. }
  12614. else {
  12615. this.position.x = absolutePositionX;
  12616. this.position.y = absolutePositionY;
  12617. this.position.z = absolutePositionZ;
  12618. }
  12619. return this;
  12620. };
  12621. // ================================== Point of View Movement =================================
  12622. /**
  12623. * Perform relative position change from the point of view of behind the front of the mesh.
  12624. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12625. * Supports definition of mesh facing forward or backward.
  12626. * @param {number} amountRight
  12627. * @param {number} amountUp
  12628. * @param {number} amountForward
  12629. *
  12630. * Returns the AbstractMesh.
  12631. */
  12632. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12633. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12634. return this;
  12635. };
  12636. /**
  12637. * Calculate relative position change from the point of view of behind the front of the mesh.
  12638. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12639. * Supports definition of mesh facing forward or backward.
  12640. * @param {number} amountRight
  12641. * @param {number} amountUp
  12642. * @param {number} amountForward
  12643. *
  12644. * Returns a new Vector3.
  12645. */
  12646. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12647. var rotMatrix = new BABYLON.Matrix();
  12648. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12649. rotQuaternion.toRotationMatrix(rotMatrix);
  12650. var translationDelta = BABYLON.Vector3.Zero();
  12651. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12652. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12653. return translationDelta;
  12654. };
  12655. // ================================== Point of View Rotation =================================
  12656. /**
  12657. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12658. * Supports definition of mesh facing forward or backward.
  12659. * @param {number} flipBack
  12660. * @param {number} twirlClockwise
  12661. * @param {number} tiltRight
  12662. *
  12663. * Returns the AbstractMesh.
  12664. */
  12665. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12666. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12667. return this;
  12668. };
  12669. /**
  12670. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12671. * Supports definition of mesh facing forward or backward.
  12672. * @param {number} flipBack
  12673. * @param {number} twirlClockwise
  12674. * @param {number} tiltRight
  12675. *
  12676. * Returns a new Vector3.
  12677. */
  12678. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12679. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12680. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12681. };
  12682. /**
  12683. * Sets a new pivot matrix to the mesh.
  12684. * Returns the AbstractMesh.
  12685. */
  12686. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12687. this._pivotMatrix = matrix;
  12688. this._cache.pivotMatrixUpdated = true;
  12689. return this;
  12690. };
  12691. /**
  12692. * Returns the mesh pivot matrix.
  12693. * Default : Identity.
  12694. * A Matrix is returned.
  12695. */
  12696. AbstractMesh.prototype.getPivotMatrix = function () {
  12697. return this._pivotMatrix;
  12698. };
  12699. AbstractMesh.prototype._isSynchronized = function () {
  12700. if (this._isDirty) {
  12701. return false;
  12702. }
  12703. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12704. return false;
  12705. if (this._cache.pivotMatrixUpdated) {
  12706. return false;
  12707. }
  12708. if (this.infiniteDistance) {
  12709. return false;
  12710. }
  12711. if (!this._cache.position.equals(this.position))
  12712. return false;
  12713. if (this.rotationQuaternion) {
  12714. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12715. return false;
  12716. }
  12717. if (!this._cache.rotation.equals(this.rotation))
  12718. return false;
  12719. if (!this._cache.scaling.equals(this.scaling))
  12720. return false;
  12721. return true;
  12722. };
  12723. AbstractMesh.prototype._initCache = function () {
  12724. _super.prototype._initCache.call(this);
  12725. this._cache.localMatrixUpdated = false;
  12726. this._cache.position = BABYLON.Vector3.Zero();
  12727. this._cache.scaling = BABYLON.Vector3.Zero();
  12728. this._cache.rotation = BABYLON.Vector3.Zero();
  12729. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12730. this._cache.billboardMode = -1;
  12731. };
  12732. AbstractMesh.prototype.markAsDirty = function (property) {
  12733. if (property === "rotation") {
  12734. this.rotationQuaternion = null;
  12735. }
  12736. this._currentRenderId = Number.MAX_VALUE;
  12737. this._isDirty = true;
  12738. return this;
  12739. };
  12740. /**
  12741. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12742. * Returns the AbstractMesh.
  12743. */
  12744. AbstractMesh.prototype._updateBoundingInfo = function () {
  12745. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12746. this._boundingInfo.update(this.worldMatrixFromCache);
  12747. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12748. return this;
  12749. };
  12750. /**
  12751. * Update a mesh's children BoundingInfo objects only.
  12752. * Returns the AbstractMesh.
  12753. */
  12754. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12755. if (!this.subMeshes) {
  12756. return;
  12757. }
  12758. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12759. var subMesh = this.subMeshes[subIndex];
  12760. if (!subMesh.IsGlobal) {
  12761. subMesh.updateBoundingInfo(matrix);
  12762. }
  12763. }
  12764. return this;
  12765. };
  12766. /**
  12767. * Computes the mesh World matrix and returns it.
  12768. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12769. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12770. * If the parameter `force`is set to `true`, the actual computation is done.
  12771. * Returns the mesh World Matrix.
  12772. */
  12773. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12774. if (this._isWorldMatrixFrozen) {
  12775. return this._worldMatrix;
  12776. }
  12777. if (!force && this.isSynchronized(true)) {
  12778. this._currentRenderId = this.getScene().getRenderId();
  12779. return this._worldMatrix;
  12780. }
  12781. this._cache.position.copyFrom(this.position);
  12782. this._cache.scaling.copyFrom(this.scaling);
  12783. this._cache.pivotMatrixUpdated = false;
  12784. this._cache.billboardMode = this.billboardMode;
  12785. this._currentRenderId = this.getScene().getRenderId();
  12786. this._isDirty = false;
  12787. // Scaling
  12788. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12789. // Rotation
  12790. //rotate, if quaternion is set and rotation was used
  12791. if (this.rotationQuaternion) {
  12792. var len = this.rotation.length();
  12793. if (len) {
  12794. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12795. this.rotation.copyFromFloats(0, 0, 0);
  12796. }
  12797. }
  12798. if (this.rotationQuaternion) {
  12799. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12800. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12801. }
  12802. else {
  12803. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12804. this._cache.rotation.copyFrom(this.rotation);
  12805. }
  12806. // Translation
  12807. if (this.infiniteDistance && !this.parent) {
  12808. var camera = this.getScene().activeCamera;
  12809. if (camera) {
  12810. var cameraWorldMatrix = camera.getWorldMatrix();
  12811. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12812. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12813. }
  12814. }
  12815. else {
  12816. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12817. }
  12818. // Composing transformations
  12819. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12820. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12821. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12822. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12823. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12824. // Need to decompose each rotation here
  12825. var currentPosition = BABYLON.Tmp.Vector3[3];
  12826. if (this.parent && this.parent.getWorldMatrix) {
  12827. if (this._meshToBoneReferal) {
  12828. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12829. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12830. }
  12831. else {
  12832. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12833. }
  12834. }
  12835. else {
  12836. currentPosition.copyFrom(this.position);
  12837. }
  12838. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12839. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12840. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12841. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12842. }
  12843. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12844. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12845. }
  12846. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12847. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12848. }
  12849. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12850. }
  12851. else {
  12852. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12853. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12854. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12855. }
  12856. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12857. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12858. }
  12859. // Local world
  12860. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12861. // Parent
  12862. if (this.parent && this.parent.getWorldMatrix) {
  12863. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12864. if (this._meshToBoneReferal) {
  12865. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12866. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12867. }
  12868. else {
  12869. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12870. }
  12871. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12872. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12873. this._worldMatrix.copyFrom(this._localWorld);
  12874. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12875. }
  12876. else {
  12877. if (this._meshToBoneReferal) {
  12878. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12879. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12880. }
  12881. else {
  12882. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12883. }
  12884. }
  12885. this._markSyncedWithParent();
  12886. }
  12887. else {
  12888. this._worldMatrix.copyFrom(this._localWorld);
  12889. }
  12890. // Bounding info
  12891. this._updateBoundingInfo();
  12892. // Absolute position
  12893. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12894. // Callbacks
  12895. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12896. if (!this._poseMatrix) {
  12897. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12898. }
  12899. return this._worldMatrix;
  12900. };
  12901. /**
  12902. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12903. * @param func: callback function to add
  12904. *
  12905. * Returns the AbstractMesh.
  12906. */
  12907. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12908. this.onAfterWorldMatrixUpdateObservable.add(func);
  12909. return this;
  12910. };
  12911. /**
  12912. * Removes a registered callback function.
  12913. * Returns the AbstractMesh.
  12914. */
  12915. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12916. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12917. return this;
  12918. };
  12919. /**
  12920. * Sets the mesh position in its local space.
  12921. * Returns the AbstractMesh.
  12922. */
  12923. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12924. this.computeWorldMatrix();
  12925. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12926. return this;
  12927. };
  12928. /**
  12929. * Returns the mesh position in the local space from the current World matrix values.
  12930. * Returns a new Vector3.
  12931. */
  12932. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12933. this.computeWorldMatrix();
  12934. var invLocalWorldMatrix = this._localWorld.clone();
  12935. invLocalWorldMatrix.invert();
  12936. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12937. };
  12938. /**
  12939. * Translates the mesh along the passed Vector3 in its local space.
  12940. * Returns the AbstractMesh.
  12941. */
  12942. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12943. this.computeWorldMatrix(true);
  12944. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12945. return this;
  12946. };
  12947. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12948. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12949. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12950. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12951. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12952. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12953. /// <returns>Mesh oriented towards targetMesh</returns>
  12954. if (yawCor === void 0) { yawCor = 0; }
  12955. if (pitchCor === void 0) { pitchCor = 0; }
  12956. if (rollCor === void 0) { rollCor = 0; }
  12957. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12958. var dv = AbstractMesh._lookAtVectorCache;
  12959. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12960. targetPoint.subtractToRef(pos, dv);
  12961. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12962. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12963. var pitch = Math.atan2(dv.y, len);
  12964. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12965. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12966. return this;
  12967. };
  12968. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12969. this._meshToBoneReferal = affectedMesh;
  12970. this.parent = bone;
  12971. if (bone.getWorldMatrix().determinant() < 0) {
  12972. this.scalingDeterminant *= -1;
  12973. }
  12974. return this;
  12975. };
  12976. AbstractMesh.prototype.detachFromBone = function () {
  12977. if (this.parent.getWorldMatrix().determinant() < 0) {
  12978. this.scalingDeterminant *= -1;
  12979. }
  12980. this._meshToBoneReferal = null;
  12981. this.parent = null;
  12982. return this;
  12983. };
  12984. /**
  12985. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12986. * A mesh is in the frustum if its bounding box intersects the frustum.
  12987. * Boolean returned.
  12988. */
  12989. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12990. return this._boundingInfo.isInFrustum(frustumPlanes);
  12991. };
  12992. /**
  12993. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12994. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12995. * Boolean returned.
  12996. */
  12997. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12998. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12999. ;
  13000. };
  13001. /**
  13002. * True if the mesh intersects another mesh or a SolidParticle object.
  13003. * 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)
  13004. * Returns a boolean.
  13005. */
  13006. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13007. if (!this._boundingInfo || !mesh._boundingInfo) {
  13008. return false;
  13009. }
  13010. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13011. };
  13012. /**
  13013. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13014. * Returns a boolean.
  13015. */
  13016. AbstractMesh.prototype.intersectsPoint = function (point) {
  13017. if (!this._boundingInfo) {
  13018. return false;
  13019. }
  13020. return this._boundingInfo.intersectsPoint(point);
  13021. };
  13022. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13023. return this.physicsImpostor;
  13024. };
  13025. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13026. if (!camera) {
  13027. camera = this.getScene().activeCamera;
  13028. }
  13029. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13030. };
  13031. /**
  13032. * Returns the distance from the mesh to the active camera.
  13033. * Returns a float.
  13034. */
  13035. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13036. if (!camera) {
  13037. camera = this.getScene().activeCamera;
  13038. }
  13039. return this.absolutePosition.subtract(camera.position).length();
  13040. };
  13041. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13042. if (!this.physicsImpostor) {
  13043. return;
  13044. }
  13045. this.physicsImpostor.applyImpulse(force, contactPoint);
  13046. return this;
  13047. };
  13048. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13049. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13050. return;
  13051. }
  13052. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13053. mainPivot: pivot1,
  13054. connectedPivot: pivot2,
  13055. nativeParams: options
  13056. });
  13057. return this;
  13058. };
  13059. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13060. // Collisions
  13061. /**
  13062. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13063. * Default `false`.
  13064. */
  13065. get: function () {
  13066. return this._checkCollisions;
  13067. },
  13068. set: function (collisionEnabled) {
  13069. this._checkCollisions = collisionEnabled;
  13070. if (this.getScene().workerCollisions) {
  13071. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13072. }
  13073. },
  13074. enumerable: true,
  13075. configurable: true
  13076. });
  13077. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  13078. var globalPosition = this.getAbsolutePosition();
  13079. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13080. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13081. if (!this._collider) {
  13082. this._collider = new BABYLON.Collider();
  13083. }
  13084. this._collider.radius = this.ellipsoid;
  13085. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13086. return this;
  13087. };
  13088. // Submeshes octree
  13089. /**
  13090. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13091. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13092. * Returns an Octree of submeshes.
  13093. */
  13094. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13095. if (maxCapacity === void 0) { maxCapacity = 64; }
  13096. if (maxDepth === void 0) { maxDepth = 2; }
  13097. if (!this._submeshesOctree) {
  13098. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13099. }
  13100. this.computeWorldMatrix(true);
  13101. // Update octree
  13102. var bbox = this.getBoundingInfo().boundingBox;
  13103. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13104. return this._submeshesOctree;
  13105. };
  13106. // Collisions
  13107. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13108. this._generatePointsArray();
  13109. // Transformation
  13110. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13111. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13112. subMesh._lastColliderWorldVertices = [];
  13113. subMesh._trianglePlanes = [];
  13114. var start = subMesh.verticesStart;
  13115. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13116. for (var i = start; i < end; i++) {
  13117. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13118. }
  13119. }
  13120. // Collide
  13121. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13122. if (collider.collisionFound) {
  13123. collider.collidedMesh = this;
  13124. }
  13125. return this;
  13126. };
  13127. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13128. var subMeshes;
  13129. var len;
  13130. // Octrees
  13131. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13132. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13133. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13134. len = intersections.length;
  13135. subMeshes = intersections.data;
  13136. }
  13137. else {
  13138. subMeshes = this.subMeshes;
  13139. len = subMeshes.length;
  13140. }
  13141. for (var index = 0; index < len; index++) {
  13142. var subMesh = subMeshes[index];
  13143. // Bounding test
  13144. if (len > 1 && !subMesh._checkCollision(collider))
  13145. continue;
  13146. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13147. }
  13148. return this;
  13149. };
  13150. AbstractMesh.prototype._checkCollision = function (collider) {
  13151. // Bounding box test
  13152. if (!this._boundingInfo._checkCollision(collider))
  13153. return this;
  13154. // Transformation matrix
  13155. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13156. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13157. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13158. return this;
  13159. };
  13160. // Picking
  13161. AbstractMesh.prototype._generatePointsArray = function () {
  13162. return false;
  13163. };
  13164. /**
  13165. * Checks if the passed Ray intersects with the mesh.
  13166. * Returns an object PickingInfo.
  13167. */
  13168. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13169. var pickingInfo = new BABYLON.PickingInfo();
  13170. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13171. return pickingInfo;
  13172. }
  13173. if (!this._generatePointsArray()) {
  13174. return pickingInfo;
  13175. }
  13176. var intersectInfo = null;
  13177. // Octrees
  13178. var subMeshes;
  13179. var len;
  13180. if (this._submeshesOctree && this.useOctreeForPicking) {
  13181. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13182. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13183. len = intersections.length;
  13184. subMeshes = intersections.data;
  13185. }
  13186. else {
  13187. subMeshes = this.subMeshes;
  13188. len = subMeshes.length;
  13189. }
  13190. for (var index = 0; index < len; index++) {
  13191. var subMesh = subMeshes[index];
  13192. // Bounding test
  13193. if (len > 1 && !subMesh.canIntersects(ray))
  13194. continue;
  13195. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13196. if (currentIntersectInfo) {
  13197. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13198. intersectInfo = currentIntersectInfo;
  13199. intersectInfo.subMeshId = index;
  13200. if (fastCheck) {
  13201. break;
  13202. }
  13203. }
  13204. }
  13205. }
  13206. if (intersectInfo) {
  13207. // Get picked point
  13208. var world = this.getWorldMatrix();
  13209. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13210. var direction = ray.direction.clone();
  13211. direction = direction.scale(intersectInfo.distance);
  13212. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13213. var pickedPoint = worldOrigin.add(worldDirection);
  13214. // Return result
  13215. pickingInfo.hit = true;
  13216. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13217. pickingInfo.pickedPoint = pickedPoint;
  13218. pickingInfo.pickedMesh = this;
  13219. pickingInfo.bu = intersectInfo.bu;
  13220. pickingInfo.bv = intersectInfo.bv;
  13221. pickingInfo.faceId = intersectInfo.faceId;
  13222. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13223. return pickingInfo;
  13224. }
  13225. return pickingInfo;
  13226. };
  13227. /**
  13228. * Clones the mesh, used by the class Mesh.
  13229. * Just returns `null` for an AbstractMesh.
  13230. */
  13231. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13232. return null;
  13233. };
  13234. /**
  13235. * Disposes all the mesh submeshes.
  13236. * Returns the AbstractMesh.
  13237. */
  13238. AbstractMesh.prototype.releaseSubMeshes = function () {
  13239. if (this.subMeshes) {
  13240. while (this.subMeshes.length) {
  13241. this.subMeshes[0].dispose();
  13242. }
  13243. }
  13244. else {
  13245. this.subMeshes = new Array();
  13246. }
  13247. return this;
  13248. };
  13249. /**
  13250. * Disposes the AbstractMesh.
  13251. * Some internal references are kept for further use.
  13252. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13253. * Returns nothing.
  13254. */
  13255. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13256. var _this = this;
  13257. var index;
  13258. // Action manager
  13259. if (this.actionManager) {
  13260. this.actionManager.dispose();
  13261. this.actionManager = null;
  13262. }
  13263. // Skeleton
  13264. this.skeleton = null;
  13265. // Animations
  13266. this.getScene().stopAnimation(this);
  13267. // Physics
  13268. if (this.physicsImpostor) {
  13269. this.physicsImpostor.dispose();
  13270. }
  13271. // Intersections in progress
  13272. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13273. var other = this._intersectionsInProgress[index];
  13274. var pos = other._intersectionsInProgress.indexOf(this);
  13275. other._intersectionsInProgress.splice(pos, 1);
  13276. }
  13277. this._intersectionsInProgress = [];
  13278. // Lights
  13279. var lights = this.getScene().lights;
  13280. lights.forEach(function (light) {
  13281. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13282. if (meshIndex !== -1) {
  13283. light.includedOnlyMeshes.splice(meshIndex, 1);
  13284. }
  13285. meshIndex = light.excludedMeshes.indexOf(_this);
  13286. if (meshIndex !== -1) {
  13287. light.excludedMeshes.splice(meshIndex, 1);
  13288. }
  13289. // Shadow generators
  13290. var generator = light.getShadowGenerator();
  13291. if (generator) {
  13292. var shadowMap = generator.getShadowMap();
  13293. meshIndex = shadowMap.renderList.indexOf(_this);
  13294. if (meshIndex !== -1) {
  13295. shadowMap.renderList.splice(meshIndex, 1);
  13296. }
  13297. }
  13298. });
  13299. // Edges
  13300. if (this._edgesRenderer) {
  13301. this._edgesRenderer.dispose();
  13302. this._edgesRenderer = null;
  13303. }
  13304. // SubMeshes
  13305. if (this.getClassName() !== "InstancedMesh") {
  13306. this.releaseSubMeshes();
  13307. }
  13308. // Octree
  13309. var sceneOctree = this.getScene().selectionOctree;
  13310. if (sceneOctree) {
  13311. var index = sceneOctree.dynamicContent.indexOf(this);
  13312. if (index !== -1) {
  13313. sceneOctree.dynamicContent.splice(index, 1);
  13314. }
  13315. }
  13316. // Engine
  13317. this.getScene().getEngine().wipeCaches();
  13318. // Remove from scene
  13319. this.getScene().removeMesh(this);
  13320. if (!doNotRecurse) {
  13321. // Particles
  13322. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13323. if (this.getScene().particleSystems[index].emitter === this) {
  13324. this.getScene().particleSystems[index].dispose();
  13325. index--;
  13326. }
  13327. }
  13328. // Children
  13329. var objects = this.getDescendants(true);
  13330. for (index = 0; index < objects.length; index++) {
  13331. objects[index].dispose();
  13332. }
  13333. }
  13334. else {
  13335. var childMeshes = this.getChildMeshes(true);
  13336. for (index = 0; index < childMeshes.length; index++) {
  13337. var child = childMeshes[index];
  13338. child.parent = null;
  13339. child.computeWorldMatrix(true);
  13340. }
  13341. }
  13342. // facet data
  13343. if (this._facetDataEnabled) {
  13344. this.disableFacetData();
  13345. }
  13346. this.onAfterWorldMatrixUpdateObservable.clear();
  13347. this.onCollideObservable.clear();
  13348. this.onCollisionPositionChangeObservable.clear();
  13349. this._isDisposed = true;
  13350. _super.prototype.dispose.call(this);
  13351. };
  13352. /**
  13353. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13354. * This Vector3 is expressed in the World space.
  13355. */
  13356. AbstractMesh.prototype.getDirection = function (localAxis) {
  13357. var result = BABYLON.Vector3.Zero();
  13358. this.getDirectionToRef(localAxis, result);
  13359. return result;
  13360. };
  13361. /**
  13362. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13363. * localAxis is expressed in the mesh local space.
  13364. * result is computed in the Wordl space from the mesh World matrix.
  13365. * Returns the AbstractMesh.
  13366. */
  13367. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13368. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13369. return this;
  13370. };
  13371. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13372. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13373. if (this.getScene().getRenderId() == 0) {
  13374. this.computeWorldMatrix(true);
  13375. }
  13376. var wm = this.getWorldMatrix();
  13377. if (space == BABYLON.Space.WORLD) {
  13378. var tmat = BABYLON.Tmp.Matrix[0];
  13379. wm.invertToRef(tmat);
  13380. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13381. }
  13382. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13383. this._pivotMatrix.m[12] = -point.x;
  13384. this._pivotMatrix.m[13] = -point.y;
  13385. this._pivotMatrix.m[14] = -point.z;
  13386. this._cache.pivotMatrixUpdated = true;
  13387. return this;
  13388. };
  13389. /**
  13390. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13391. */
  13392. AbstractMesh.prototype.getPivotPoint = function () {
  13393. var point = BABYLON.Vector3.Zero();
  13394. this.getPivotPointToRef(point);
  13395. return point;
  13396. };
  13397. /**
  13398. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13399. * Returns the AbstractMesh.
  13400. */
  13401. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13402. result.x = -this._pivotMatrix.m[12];
  13403. result.y = -this._pivotMatrix.m[13];
  13404. result.z = -this._pivotMatrix.m[14];
  13405. return this;
  13406. };
  13407. /**
  13408. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13409. */
  13410. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13411. var point = BABYLON.Vector3.Zero();
  13412. this.getAbsolutePivotPointToRef(point);
  13413. return point;
  13414. };
  13415. /**
  13416. * Defines the passed mesh as the parent of the current mesh.
  13417. * Returns the AbstractMesh.
  13418. */
  13419. AbstractMesh.prototype.setParent = function (mesh) {
  13420. var child = this;
  13421. var parent = mesh;
  13422. if (mesh == null) {
  13423. var rotation = BABYLON.Tmp.Quaternion[0];
  13424. var position = BABYLON.Tmp.Vector3[0];
  13425. var scale = BABYLON.Tmp.Vector3[1];
  13426. child.getWorldMatrix().decompose(scale, rotation, position);
  13427. if (child.rotationQuaternion) {
  13428. child.rotationQuaternion.copyFrom(rotation);
  13429. }
  13430. else {
  13431. rotation.toEulerAnglesToRef(child.rotation);
  13432. }
  13433. child.position.x = position.x;
  13434. child.position.y = position.y;
  13435. child.position.z = position.z;
  13436. }
  13437. else {
  13438. var rotation = BABYLON.Tmp.Quaternion[0];
  13439. var position = BABYLON.Tmp.Vector3[0];
  13440. var scale = BABYLON.Tmp.Vector3[1];
  13441. var m1 = BABYLON.Tmp.Matrix[0];
  13442. var m2 = BABYLON.Tmp.Matrix[1];
  13443. parent.getWorldMatrix().decompose(scale, rotation, position);
  13444. rotation.toRotationMatrix(m1);
  13445. m2.setTranslation(position);
  13446. m2.multiplyToRef(m1, m1);
  13447. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13448. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13449. m.decompose(scale, rotation, position);
  13450. if (child.rotationQuaternion) {
  13451. child.rotationQuaternion.copyFrom(rotation);
  13452. }
  13453. else {
  13454. rotation.toEulerAnglesToRef(child.rotation);
  13455. }
  13456. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13457. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13458. m.decompose(scale, rotation, position);
  13459. child.position.x = position.x;
  13460. child.position.y = position.y;
  13461. child.position.z = position.z;
  13462. }
  13463. child.parent = parent;
  13464. return this;
  13465. };
  13466. /**
  13467. * Adds the passed mesh as a child to the current mesh.
  13468. * Returns the AbstractMesh.
  13469. */
  13470. AbstractMesh.prototype.addChild = function (mesh) {
  13471. mesh.setParent(this);
  13472. return this;
  13473. };
  13474. /**
  13475. * Removes the passed mesh from the current mesh children list.
  13476. * Returns the AbstractMesh.
  13477. */
  13478. AbstractMesh.prototype.removeChild = function (mesh) {
  13479. mesh.setParent(null);
  13480. return this;
  13481. };
  13482. /**
  13483. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13484. * Returns the AbstractMesh.
  13485. */
  13486. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13487. result.x = this._pivotMatrix.m[12];
  13488. result.y = this._pivotMatrix.m[13];
  13489. result.z = this._pivotMatrix.m[14];
  13490. this.getPivotPointToRef(result);
  13491. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13492. return this;
  13493. };
  13494. // Facet data
  13495. /**
  13496. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13497. * Returns the AbstractMesh.
  13498. */
  13499. AbstractMesh.prototype._initFacetData = function () {
  13500. if (!this._facetNormals) {
  13501. this._facetNormals = new Array();
  13502. }
  13503. if (!this._facetPositions) {
  13504. this._facetPositions = new Array();
  13505. }
  13506. if (!this._facetPartitioning) {
  13507. this._facetPartitioning = new Array();
  13508. }
  13509. this._facetNb = this.getIndices().length / 3;
  13510. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13511. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13512. for (var f = 0; f < this._facetNb; f++) {
  13513. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13514. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13515. }
  13516. this._facetDataEnabled = true;
  13517. return this;
  13518. };
  13519. /**
  13520. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13521. * This method can be called within the render loop.
  13522. * 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.
  13523. * Returns the AbstractMesh.
  13524. */
  13525. AbstractMesh.prototype.updateFacetData = function () {
  13526. if (!this._facetDataEnabled) {
  13527. this._initFacetData();
  13528. }
  13529. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13530. var indices = this.getIndices();
  13531. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13532. var bInfo = this.getBoundingInfo();
  13533. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13534. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13535. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13536. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13537. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13538. this._subDiv.max = this._partitioningSubdivisions;
  13539. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13540. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13541. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13542. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13543. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13544. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13545. // set the parameters for ComputeNormals()
  13546. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13547. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13548. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13549. this._facetParameters.bInfo = bInfo;
  13550. this._facetParameters.bbSize = this._bbSize;
  13551. this._facetParameters.subDiv = this._subDiv;
  13552. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13553. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13554. return this;
  13555. };
  13556. /**
  13557. * Returns the facetLocalNormals array.
  13558. * The normals are expressed in the mesh local space.
  13559. */
  13560. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13561. if (!this._facetNormals) {
  13562. this.updateFacetData();
  13563. }
  13564. return this._facetNormals;
  13565. };
  13566. /**
  13567. * Returns the facetLocalPositions array.
  13568. * The facet positions are expressed in the mesh local space.
  13569. */
  13570. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13571. if (!this._facetPositions) {
  13572. this.updateFacetData();
  13573. }
  13574. return this._facetPositions;
  13575. };
  13576. /**
  13577. * Returns the facetLocalPartioning array.
  13578. */
  13579. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13580. if (!this._facetPartitioning) {
  13581. this.updateFacetData();
  13582. }
  13583. return this._facetPartitioning;
  13584. };
  13585. /**
  13586. * Returns the i-th facet position in the world system.
  13587. * This method allocates a new Vector3 per call.
  13588. */
  13589. AbstractMesh.prototype.getFacetPosition = function (i) {
  13590. var pos = BABYLON.Vector3.Zero();
  13591. this.getFacetPositionToRef(i, pos);
  13592. return pos;
  13593. };
  13594. /**
  13595. * Sets the reference Vector3 with the i-th facet position in the world system.
  13596. * Returns the AbstractMesh.
  13597. */
  13598. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13599. var localPos = (this.getFacetLocalPositions())[i];
  13600. var world = this.getWorldMatrix();
  13601. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13602. return this;
  13603. };
  13604. /**
  13605. * Returns the i-th facet normal in the world system.
  13606. * This method allocates a new Vector3 per call.
  13607. */
  13608. AbstractMesh.prototype.getFacetNormal = function (i) {
  13609. var norm = BABYLON.Vector3.Zero();
  13610. this.getFacetNormalToRef(i, norm);
  13611. return norm;
  13612. };
  13613. /**
  13614. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13615. * Returns the AbstractMesh.
  13616. */
  13617. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13618. var localNorm = (this.getFacetLocalNormals())[i];
  13619. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13620. return this;
  13621. };
  13622. /**
  13623. * 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).
  13624. */
  13625. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13626. var bInfo = this.getBoundingInfo();
  13627. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13628. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13629. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13630. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13631. return null;
  13632. }
  13633. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13634. };
  13635. /**
  13636. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13637. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13638. * 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.
  13639. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13640. * 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.
  13641. */
  13642. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13643. if (checkFace === void 0) { checkFace = false; }
  13644. if (facing === void 0) { facing = true; }
  13645. var world = this.getWorldMatrix();
  13646. var invMat = BABYLON.Tmp.Matrix[5];
  13647. world.invertToRef(invMat);
  13648. var invVect = BABYLON.Tmp.Vector3[8];
  13649. var closest = null;
  13650. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13651. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13652. if (projected) {
  13653. // tranform the local computed projected vector to world coordinates
  13654. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13655. }
  13656. return closest;
  13657. };
  13658. /**
  13659. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13660. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13661. * 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.
  13662. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13663. * 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.
  13664. */
  13665. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13666. if (checkFace === void 0) { checkFace = false; }
  13667. if (facing === void 0) { facing = true; }
  13668. var closest = null;
  13669. var tmpx = 0.0;
  13670. var tmpy = 0.0;
  13671. var tmpz = 0.0;
  13672. var d = 0.0; // tmp dot facet normal * facet position
  13673. var t0 = 0.0;
  13674. var projx = 0.0;
  13675. var projy = 0.0;
  13676. var projz = 0.0;
  13677. // Get all the facets in the same partitioning block than (x, y, z)
  13678. var facetPositions = this.getFacetLocalPositions();
  13679. var facetNormals = this.getFacetLocalNormals();
  13680. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13681. if (!facetsInBlock) {
  13682. return null;
  13683. }
  13684. // Get the closest facet to (x, y, z)
  13685. var shortest = Number.MAX_VALUE; // init distance vars
  13686. var tmpDistance = shortest;
  13687. var fib; // current facet in the block
  13688. var norm; // current facet normal
  13689. var p0; // current facet barycenter position
  13690. // loop on all the facets in the current partitioning block
  13691. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13692. fib = facetsInBlock[idx];
  13693. norm = facetNormals[fib];
  13694. p0 = facetPositions[fib];
  13695. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13696. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13697. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13698. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13699. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13700. projx = x + norm.x * t0;
  13701. projy = y + norm.y * t0;
  13702. projz = z + norm.z * t0;
  13703. tmpx = projx - x;
  13704. tmpy = projy - y;
  13705. tmpz = projz - z;
  13706. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13707. if (tmpDistance < shortest) {
  13708. shortest = tmpDistance;
  13709. closest = fib;
  13710. if (projected) {
  13711. projected.x = projx;
  13712. projected.y = projy;
  13713. projected.z = projz;
  13714. }
  13715. }
  13716. }
  13717. }
  13718. return closest;
  13719. };
  13720. /**
  13721. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13722. */
  13723. AbstractMesh.prototype.getFacetDataParameters = function () {
  13724. return this._facetParameters;
  13725. };
  13726. /**
  13727. * Disables the feature FacetData and frees the related memory.
  13728. * Returns the AbstractMesh.
  13729. */
  13730. AbstractMesh.prototype.disableFacetData = function () {
  13731. if (this._facetDataEnabled) {
  13732. this._facetDataEnabled = false;
  13733. this._facetPositions = null;
  13734. this._facetNormals = null;
  13735. this._facetPartitioning = null;
  13736. this._facetParameters = null;
  13737. }
  13738. return this;
  13739. };
  13740. /**
  13741. * Creates new normals data for the mesh.
  13742. * @param updatable.
  13743. */
  13744. AbstractMesh.prototype.createNormals = function (updatable) {
  13745. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13746. var indices = this.getIndices();
  13747. var normals;
  13748. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13749. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13750. }
  13751. else {
  13752. normals = [];
  13753. }
  13754. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13755. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13756. };
  13757. // Statics
  13758. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13759. AbstractMesh._BILLBOARDMODE_X = 1;
  13760. AbstractMesh._BILLBOARDMODE_Y = 2;
  13761. AbstractMesh._BILLBOARDMODE_Z = 4;
  13762. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13763. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13764. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13765. return AbstractMesh;
  13766. }(BABYLON.Node));
  13767. BABYLON.AbstractMesh = AbstractMesh;
  13768. })(BABYLON || (BABYLON = {}));
  13769. //# sourceMappingURL=babylon.abstractMesh.js.map
  13770. var BABYLON;
  13771. (function (BABYLON) {
  13772. var Light = (function (_super) {
  13773. __extends(Light, _super);
  13774. /**
  13775. * Creates a Light object in the scene.
  13776. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13777. */
  13778. function Light(name, scene) {
  13779. var _this = _super.call(this, name, scene) || this;
  13780. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13781. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13782. _this.intensity = 1.0;
  13783. _this.range = Number.MAX_VALUE;
  13784. /**
  13785. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13786. * of light.
  13787. */
  13788. _this._photometricScale = 1.0;
  13789. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13790. _this._radius = 0.00001;
  13791. _this.renderPriority = 0;
  13792. /**
  13793. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13794. * the current shadow generator.
  13795. */
  13796. _this.shadowEnabled = true;
  13797. _this._excludeWithLayerMask = 0;
  13798. _this._includeOnlyWithLayerMask = 0;
  13799. _this._lightmapMode = 0;
  13800. _this._excludedMeshesIds = new Array();
  13801. _this._includedOnlyMeshesIds = new Array();
  13802. _this.getScene().addLight(_this);
  13803. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13804. _this._buildUniformLayout();
  13805. _this.includedOnlyMeshes = new Array();
  13806. _this.excludedMeshes = new Array();
  13807. _this._resyncMeshes();
  13808. return _this;
  13809. }
  13810. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13811. /**
  13812. * If every light affecting the material is in this lightmapMode,
  13813. * material.lightmapTexture adds or multiplies
  13814. * (depends on material.useLightmapAsShadowmap)
  13815. * after every other light calculations.
  13816. */
  13817. get: function () {
  13818. return Light._LIGHTMAP_DEFAULT;
  13819. },
  13820. enumerable: true,
  13821. configurable: true
  13822. });
  13823. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13824. /**
  13825. * material.lightmapTexture as only diffuse lighting from this light
  13826. * adds pnly specular lighting from this light
  13827. * adds dynamic shadows
  13828. */
  13829. get: function () {
  13830. return Light._LIGHTMAP_SPECULAR;
  13831. },
  13832. enumerable: true,
  13833. configurable: true
  13834. });
  13835. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13836. /**
  13837. * material.lightmapTexture as only lighting
  13838. * no light calculation from this light
  13839. * only adds dynamic shadows from this light
  13840. */
  13841. get: function () {
  13842. return Light._LIGHTMAP_SHADOWSONLY;
  13843. },
  13844. enumerable: true,
  13845. configurable: true
  13846. });
  13847. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13848. /**
  13849. * Each light type uses the default quantity according to its type:
  13850. * point/spot lights use luminous intensity
  13851. * directional lights use illuminance
  13852. */
  13853. get: function () {
  13854. return Light._INTENSITYMODE_AUTOMATIC;
  13855. },
  13856. enumerable: true,
  13857. configurable: true
  13858. });
  13859. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13860. /**
  13861. * lumen (lm)
  13862. */
  13863. get: function () {
  13864. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13865. },
  13866. enumerable: true,
  13867. configurable: true
  13868. });
  13869. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13870. /**
  13871. * candela (lm/sr)
  13872. */
  13873. get: function () {
  13874. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13875. },
  13876. enumerable: true,
  13877. configurable: true
  13878. });
  13879. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13880. /**
  13881. * lux (lm/m^2)
  13882. */
  13883. get: function () {
  13884. return Light._INTENSITYMODE_ILLUMINANCE;
  13885. },
  13886. enumerable: true,
  13887. configurable: true
  13888. });
  13889. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13890. /**
  13891. * nit (cd/m^2)
  13892. */
  13893. get: function () {
  13894. return Light._INTENSITYMODE_LUMINANCE;
  13895. },
  13896. enumerable: true,
  13897. configurable: true
  13898. });
  13899. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13900. /**
  13901. * Light type const id of the point light.
  13902. */
  13903. get: function () {
  13904. return Light._LIGHTTYPEID_POINTLIGHT;
  13905. },
  13906. enumerable: true,
  13907. configurable: true
  13908. });
  13909. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13910. /**
  13911. * Light type const id of the directional light.
  13912. */
  13913. get: function () {
  13914. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13915. },
  13916. enumerable: true,
  13917. configurable: true
  13918. });
  13919. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13920. /**
  13921. * Light type const id of the spot light.
  13922. */
  13923. get: function () {
  13924. return Light._LIGHTTYPEID_SPOTLIGHT;
  13925. },
  13926. enumerable: true,
  13927. configurable: true
  13928. });
  13929. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13930. /**
  13931. * Light type const id of the hemispheric light.
  13932. */
  13933. get: function () {
  13934. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13935. },
  13936. enumerable: true,
  13937. configurable: true
  13938. });
  13939. Object.defineProperty(Light.prototype, "intensityMode", {
  13940. /**
  13941. * Gets the photometric scale used to interpret the intensity.
  13942. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13943. */
  13944. get: function () {
  13945. return this._intensityMode;
  13946. },
  13947. /**
  13948. * Sets the photometric scale used to interpret the intensity.
  13949. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13950. */
  13951. set: function (value) {
  13952. this._intensityMode = value;
  13953. this._computePhotometricScale();
  13954. },
  13955. enumerable: true,
  13956. configurable: true
  13957. });
  13958. ;
  13959. ;
  13960. Object.defineProperty(Light.prototype, "radius", {
  13961. /**
  13962. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13963. */
  13964. get: function () {
  13965. return this._radius;
  13966. },
  13967. /**
  13968. * sets the light radius used by PBR Materials to simulate soft area lights.
  13969. */
  13970. set: function (value) {
  13971. this._radius = value;
  13972. this._computePhotometricScale();
  13973. },
  13974. enumerable: true,
  13975. configurable: true
  13976. });
  13977. ;
  13978. ;
  13979. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13980. get: function () {
  13981. return this._includedOnlyMeshes;
  13982. },
  13983. set: function (value) {
  13984. this._includedOnlyMeshes = value;
  13985. this._hookArrayForIncludedOnly(value);
  13986. },
  13987. enumerable: true,
  13988. configurable: true
  13989. });
  13990. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13991. get: function () {
  13992. return this._excludedMeshes;
  13993. },
  13994. set: function (value) {
  13995. this._excludedMeshes = value;
  13996. this._hookArrayForExcluded(value);
  13997. },
  13998. enumerable: true,
  13999. configurable: true
  14000. });
  14001. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14002. get: function () {
  14003. return this._excludeWithLayerMask;
  14004. },
  14005. set: function (value) {
  14006. this._excludeWithLayerMask = value;
  14007. this._resyncMeshes();
  14008. },
  14009. enumerable: true,
  14010. configurable: true
  14011. });
  14012. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14013. get: function () {
  14014. return this._includeOnlyWithLayerMask;
  14015. },
  14016. set: function (value) {
  14017. this._includeOnlyWithLayerMask = value;
  14018. this._resyncMeshes();
  14019. },
  14020. enumerable: true,
  14021. configurable: true
  14022. });
  14023. Object.defineProperty(Light.prototype, "lightmapMode", {
  14024. get: function () {
  14025. return this._lightmapMode;
  14026. },
  14027. set: function (value) {
  14028. if (this._lightmapMode === value) {
  14029. return;
  14030. }
  14031. this._lightmapMode = value;
  14032. this._markMeshesAsLightDirty();
  14033. },
  14034. enumerable: true,
  14035. configurable: true
  14036. });
  14037. Light.prototype._buildUniformLayout = function () {
  14038. // Overridden
  14039. };
  14040. /**
  14041. * Returns the string "Light".
  14042. */
  14043. Light.prototype.getClassName = function () {
  14044. return "Light";
  14045. };
  14046. /**
  14047. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14048. */
  14049. Light.prototype.toString = function (fullDetails) {
  14050. var ret = "Name: " + this.name;
  14051. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14052. if (this.animations) {
  14053. for (var i = 0; i < this.animations.length; i++) {
  14054. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14055. }
  14056. }
  14057. if (fullDetails) {
  14058. }
  14059. return ret;
  14060. };
  14061. /**
  14062. * Set the enabled state of this node.
  14063. * @param {boolean} value - the new enabled state
  14064. * @see isEnabled
  14065. */
  14066. Light.prototype.setEnabled = function (value) {
  14067. _super.prototype.setEnabled.call(this, value);
  14068. this._resyncMeshes();
  14069. };
  14070. /**
  14071. * Returns the Light associated shadow generator.
  14072. */
  14073. Light.prototype.getShadowGenerator = function () {
  14074. return this._shadowGenerator;
  14075. };
  14076. /**
  14077. * Returns a Vector3, the absolute light position in the World.
  14078. */
  14079. Light.prototype.getAbsolutePosition = function () {
  14080. return BABYLON.Vector3.Zero();
  14081. };
  14082. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14083. };
  14084. Light.prototype._getWorldMatrix = function () {
  14085. return BABYLON.Matrix.Identity();
  14086. };
  14087. /**
  14088. * Boolean : True if the light will affect the passed mesh.
  14089. */
  14090. Light.prototype.canAffectMesh = function (mesh) {
  14091. if (!mesh) {
  14092. return true;
  14093. }
  14094. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14095. return false;
  14096. }
  14097. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14098. return false;
  14099. }
  14100. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14101. return false;
  14102. }
  14103. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14104. return false;
  14105. }
  14106. return true;
  14107. };
  14108. /**
  14109. * Returns the light World matrix.
  14110. */
  14111. Light.prototype.getWorldMatrix = function () {
  14112. this._currentRenderId = this.getScene().getRenderId();
  14113. var worldMatrix = this._getWorldMatrix();
  14114. if (this.parent && this.parent.getWorldMatrix) {
  14115. if (!this._parentedWorldMatrix) {
  14116. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14117. }
  14118. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14119. this._markSyncedWithParent();
  14120. return this._parentedWorldMatrix;
  14121. }
  14122. return worldMatrix;
  14123. };
  14124. /**
  14125. * Sort function to order lights for rendering.
  14126. * @param a First Light object to compare to second.
  14127. * @param b Second Light object to compare first.
  14128. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14129. */
  14130. Light.compareLightsPriority = function (a, b) {
  14131. //shadow-casting lights have priority over non-shadow-casting lights
  14132. //the renderPrioirty is a secondary sort criterion
  14133. if (a.shadowEnabled !== b.shadowEnabled) {
  14134. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14135. }
  14136. return b.renderPriority - a.renderPriority;
  14137. };
  14138. /**
  14139. * Disposes the light.
  14140. */
  14141. Light.prototype.dispose = function () {
  14142. if (this._shadowGenerator) {
  14143. this._shadowGenerator.dispose();
  14144. this._shadowGenerator = null;
  14145. }
  14146. // Animations
  14147. this.getScene().stopAnimation(this);
  14148. // Remove from meshes
  14149. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14150. var mesh = _a[_i];
  14151. mesh._removeLightSource(this);
  14152. }
  14153. this._uniformBuffer.dispose();
  14154. // Remove from scene
  14155. this.getScene().removeLight(this);
  14156. _super.prototype.dispose.call(this);
  14157. };
  14158. /**
  14159. * Returns the light type ID (integer).
  14160. */
  14161. Light.prototype.getTypeID = function () {
  14162. return 0;
  14163. };
  14164. /**
  14165. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14166. */
  14167. Light.prototype.getScaledIntensity = function () {
  14168. return this._photometricScale * this.intensity;
  14169. };
  14170. /**
  14171. * Returns a new Light object, named "name", from the current one.
  14172. */
  14173. Light.prototype.clone = function (name) {
  14174. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14175. };
  14176. /**
  14177. * Serializes the current light into a Serialization object.
  14178. * Returns the serialized object.
  14179. */
  14180. Light.prototype.serialize = function () {
  14181. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14182. // Type
  14183. serializationObject.type = this.getTypeID();
  14184. // Parent
  14185. if (this.parent) {
  14186. serializationObject.parentId = this.parent.id;
  14187. }
  14188. // Inclusion / exclusions
  14189. if (this.excludedMeshes.length > 0) {
  14190. serializationObject.excludedMeshesIds = [];
  14191. this.excludedMeshes.forEach(function (mesh) {
  14192. serializationObject.excludedMeshesIds.push(mesh.id);
  14193. });
  14194. }
  14195. if (this.includedOnlyMeshes.length > 0) {
  14196. serializationObject.includedOnlyMeshesIds = [];
  14197. this.includedOnlyMeshes.forEach(function (mesh) {
  14198. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14199. });
  14200. }
  14201. // Animations
  14202. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14203. serializationObject.ranges = this.serializeAnimationRanges();
  14204. return serializationObject;
  14205. };
  14206. /**
  14207. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14208. * This new light is named "name" and added to the passed scene.
  14209. */
  14210. Light.GetConstructorFromName = function (type, name, scene) {
  14211. switch (type) {
  14212. case 0:
  14213. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14214. case 1:
  14215. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14216. case 2:
  14217. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14218. case 3:
  14219. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14220. }
  14221. };
  14222. /**
  14223. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14224. */
  14225. Light.Parse = function (parsedLight, scene) {
  14226. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14227. // Inclusion / exclusions
  14228. if (parsedLight.excludedMeshesIds) {
  14229. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14230. }
  14231. if (parsedLight.includedOnlyMeshesIds) {
  14232. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14233. }
  14234. // Parent
  14235. if (parsedLight.parentId) {
  14236. light._waitingParentId = parsedLight.parentId;
  14237. }
  14238. // Animations
  14239. if (parsedLight.animations) {
  14240. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14241. var parsedAnimation = parsedLight.animations[animationIndex];
  14242. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14243. }
  14244. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14245. }
  14246. if (parsedLight.autoAnimate) {
  14247. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14248. }
  14249. return light;
  14250. };
  14251. Light.prototype._hookArrayForExcluded = function (array) {
  14252. var _this = this;
  14253. var oldPush = array.push;
  14254. array.push = function () {
  14255. var items = [];
  14256. for (var _i = 0; _i < arguments.length; _i++) {
  14257. items[_i] = arguments[_i];
  14258. }
  14259. var result = oldPush.apply(array, items);
  14260. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14261. var item = items_1[_a];
  14262. item._resyncLighSource(_this);
  14263. }
  14264. return result;
  14265. };
  14266. var oldSplice = array.splice;
  14267. array.splice = function (index, deleteCount) {
  14268. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14269. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14270. var item = deleted_1[_i];
  14271. item._resyncLighSource(_this);
  14272. }
  14273. return deleted;
  14274. };
  14275. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14276. var item = array_1[_i];
  14277. item._resyncLighSource(this);
  14278. }
  14279. };
  14280. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14281. var _this = this;
  14282. var oldPush = array.push;
  14283. array.push = function () {
  14284. var items = [];
  14285. for (var _i = 0; _i < arguments.length; _i++) {
  14286. items[_i] = arguments[_i];
  14287. }
  14288. var result = oldPush.apply(array, items);
  14289. _this._resyncMeshes();
  14290. return result;
  14291. };
  14292. var oldSplice = array.splice;
  14293. array.splice = function (index, deleteCount) {
  14294. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14295. _this._resyncMeshes();
  14296. return deleted;
  14297. };
  14298. this._resyncMeshes();
  14299. };
  14300. Light.prototype._resyncMeshes = function () {
  14301. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14302. var mesh = _a[_i];
  14303. mesh._resyncLighSource(this);
  14304. }
  14305. };
  14306. Light.prototype._markMeshesAsLightDirty = function () {
  14307. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14308. var mesh = _a[_i];
  14309. if (mesh._lightSources.indexOf(this) !== -1) {
  14310. mesh._markSubMeshesAsLightDirty();
  14311. }
  14312. }
  14313. };
  14314. /**
  14315. * Recomputes the cached photometric scale if needed.
  14316. */
  14317. Light.prototype._computePhotometricScale = function () {
  14318. this._photometricScale = this._getPhotometricScale();
  14319. this.getScene().resetCachedMaterial();
  14320. };
  14321. /**
  14322. * Returns the Photometric Scale according to the light type and intensity mode.
  14323. */
  14324. Light.prototype._getPhotometricScale = function () {
  14325. var photometricScale = 0.0;
  14326. var lightTypeID = this.getTypeID();
  14327. //get photometric mode
  14328. var photometricMode = this.intensityMode;
  14329. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14330. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14331. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14332. }
  14333. else {
  14334. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14335. }
  14336. }
  14337. //compute photometric scale
  14338. switch (lightTypeID) {
  14339. case Light.LIGHTTYPEID_POINTLIGHT:
  14340. case Light.LIGHTTYPEID_SPOTLIGHT:
  14341. switch (photometricMode) {
  14342. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14343. photometricScale = 1.0 / (4.0 * Math.PI);
  14344. break;
  14345. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14346. photometricScale = 1.0;
  14347. break;
  14348. case Light.INTENSITYMODE_LUMINANCE:
  14349. photometricScale = this.radius * this.radius;
  14350. break;
  14351. }
  14352. break;
  14353. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14354. switch (photometricMode) {
  14355. case Light.INTENSITYMODE_ILLUMINANCE:
  14356. photometricScale = 1.0;
  14357. break;
  14358. case Light.INTENSITYMODE_LUMINANCE:
  14359. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14360. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14361. var apexAngleRadians = this.radius;
  14362. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14363. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14364. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14365. photometricScale = solidAngle;
  14366. break;
  14367. }
  14368. break;
  14369. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14370. // No fall off in hemisperic light.
  14371. photometricScale = 1.0;
  14372. break;
  14373. }
  14374. return photometricScale;
  14375. };
  14376. Light.prototype._reorderLightsInScene = function () {
  14377. var scene = this.getScene();
  14378. if (this.renderPriority != 0) {
  14379. scene.requireLightSorting = true;
  14380. }
  14381. this.getScene().sortLightsByPriority();
  14382. };
  14383. //lightmapMode Consts
  14384. Light._LIGHTMAP_DEFAULT = 0;
  14385. Light._LIGHTMAP_SPECULAR = 1;
  14386. Light._LIGHTMAP_SHADOWSONLY = 2;
  14387. // Intensity Mode Consts
  14388. Light._INTENSITYMODE_AUTOMATIC = 0;
  14389. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14390. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14391. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14392. Light._INTENSITYMODE_LUMINANCE = 4;
  14393. // Light types ids const.
  14394. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14395. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14396. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14397. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14398. __decorate([
  14399. BABYLON.serializeAsColor3()
  14400. ], Light.prototype, "diffuse", void 0);
  14401. __decorate([
  14402. BABYLON.serializeAsColor3()
  14403. ], Light.prototype, "specular", void 0);
  14404. __decorate([
  14405. BABYLON.serialize()
  14406. ], Light.prototype, "intensity", void 0);
  14407. __decorate([
  14408. BABYLON.serialize()
  14409. ], Light.prototype, "range", void 0);
  14410. __decorate([
  14411. BABYLON.serialize()
  14412. ], Light.prototype, "intensityMode", null);
  14413. __decorate([
  14414. BABYLON.serialize()
  14415. ], Light.prototype, "radius", null);
  14416. __decorate([
  14417. BABYLON.serialize()
  14418. ], Light.prototype, "_renderPriority", void 0);
  14419. __decorate([
  14420. BABYLON.expandToProperty("_reorderLightsInScene")
  14421. ], Light.prototype, "renderPriority", void 0);
  14422. __decorate([
  14423. BABYLON.serialize()
  14424. ], Light.prototype, "shadowEnabled", void 0);
  14425. __decorate([
  14426. BABYLON.serialize("excludeWithLayerMask")
  14427. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14428. __decorate([
  14429. BABYLON.serialize("includeOnlyWithLayerMask")
  14430. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14431. __decorate([
  14432. BABYLON.serialize("lightmapMode")
  14433. ], Light.prototype, "_lightmapMode", void 0);
  14434. return Light;
  14435. }(BABYLON.Node));
  14436. BABYLON.Light = Light;
  14437. })(BABYLON || (BABYLON = {}));
  14438. //# sourceMappingURL=babylon.light.js.map
  14439. var BABYLON;
  14440. (function (BABYLON) {
  14441. var Camera = (function (_super) {
  14442. __extends(Camera, _super);
  14443. function Camera(name, position, scene) {
  14444. var _this = _super.call(this, name, scene) || this;
  14445. _this.upVector = BABYLON.Vector3.Up();
  14446. _this.orthoLeft = null;
  14447. _this.orthoRight = null;
  14448. _this.orthoBottom = null;
  14449. _this.orthoTop = null;
  14450. _this.fov = 0.8;
  14451. _this.minZ = 1.0;
  14452. _this.maxZ = 10000.0;
  14453. _this.inertia = 0.9;
  14454. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14455. _this.isIntermediate = false;
  14456. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14457. _this.layerMask = 0x0FFFFFFF;
  14458. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14459. // Camera rig members
  14460. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14461. _this._rigCameras = new Array();
  14462. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14463. _this.customRenderTargets = new Array();
  14464. // Observables
  14465. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14466. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14467. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  14468. // Cache
  14469. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14470. _this._projectionMatrix = new BABYLON.Matrix();
  14471. _this._doNotComputeProjectionMatrix = false;
  14472. _this._postProcesses = new Array();
  14473. _this._transformMatrix = BABYLON.Matrix.Zero();
  14474. _this._activeMeshes = new BABYLON.SmartArray(256);
  14475. _this._globalPosition = BABYLON.Vector3.Zero();
  14476. _this._refreshFrustumPlanes = true;
  14477. _this.getScene().addCamera(_this);
  14478. if (!_this.getScene().activeCamera) {
  14479. _this.getScene().activeCamera = _this;
  14480. }
  14481. _this.position = position;
  14482. return _this;
  14483. }
  14484. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14485. get: function () {
  14486. return Camera._PERSPECTIVE_CAMERA;
  14487. },
  14488. enumerable: true,
  14489. configurable: true
  14490. });
  14491. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14492. get: function () {
  14493. return Camera._ORTHOGRAPHIC_CAMERA;
  14494. },
  14495. enumerable: true,
  14496. configurable: true
  14497. });
  14498. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14499. get: function () {
  14500. return Camera._FOVMODE_VERTICAL_FIXED;
  14501. },
  14502. enumerable: true,
  14503. configurable: true
  14504. });
  14505. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14506. get: function () {
  14507. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14508. },
  14509. enumerable: true,
  14510. configurable: true
  14511. });
  14512. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14513. get: function () {
  14514. return Camera._RIG_MODE_NONE;
  14515. },
  14516. enumerable: true,
  14517. configurable: true
  14518. });
  14519. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14520. get: function () {
  14521. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14522. },
  14523. enumerable: true,
  14524. configurable: true
  14525. });
  14526. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14527. get: function () {
  14528. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14529. },
  14530. enumerable: true,
  14531. configurable: true
  14532. });
  14533. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14534. get: function () {
  14535. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14536. },
  14537. enumerable: true,
  14538. configurable: true
  14539. });
  14540. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14541. get: function () {
  14542. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14543. },
  14544. enumerable: true,
  14545. configurable: true
  14546. });
  14547. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14548. get: function () {
  14549. return Camera._RIG_MODE_VR;
  14550. },
  14551. enumerable: true,
  14552. configurable: true
  14553. });
  14554. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14555. get: function () {
  14556. return Camera._RIG_MODE_WEBVR;
  14557. },
  14558. enumerable: true,
  14559. configurable: true
  14560. });
  14561. Camera.prototype.getClassName = function () {
  14562. return "Camera";
  14563. };
  14564. /**
  14565. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14566. */
  14567. Camera.prototype.toString = function (fullDetails) {
  14568. var ret = "Name: " + this.name;
  14569. ret += ", type: " + this.getClassName();
  14570. if (this.animations) {
  14571. for (var i = 0; i < this.animations.length; i++) {
  14572. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14573. }
  14574. }
  14575. if (fullDetails) {
  14576. }
  14577. return ret;
  14578. };
  14579. Object.defineProperty(Camera.prototype, "globalPosition", {
  14580. get: function () {
  14581. return this._globalPosition;
  14582. },
  14583. enumerable: true,
  14584. configurable: true
  14585. });
  14586. Camera.prototype.getActiveMeshes = function () {
  14587. return this._activeMeshes;
  14588. };
  14589. Camera.prototype.isActiveMesh = function (mesh) {
  14590. return (this._activeMeshes.indexOf(mesh) !== -1);
  14591. };
  14592. //Cache
  14593. Camera.prototype._initCache = function () {
  14594. _super.prototype._initCache.call(this);
  14595. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14596. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14597. this._cache.mode = undefined;
  14598. this._cache.minZ = undefined;
  14599. this._cache.maxZ = undefined;
  14600. this._cache.fov = undefined;
  14601. this._cache.fovMode = undefined;
  14602. this._cache.aspectRatio = undefined;
  14603. this._cache.orthoLeft = undefined;
  14604. this._cache.orthoRight = undefined;
  14605. this._cache.orthoBottom = undefined;
  14606. this._cache.orthoTop = undefined;
  14607. this._cache.renderWidth = undefined;
  14608. this._cache.renderHeight = undefined;
  14609. };
  14610. Camera.prototype._updateCache = function (ignoreParentClass) {
  14611. if (!ignoreParentClass) {
  14612. _super.prototype._updateCache.call(this);
  14613. }
  14614. var engine = this.getEngine();
  14615. this._cache.position.copyFrom(this.position);
  14616. this._cache.upVector.copyFrom(this.upVector);
  14617. this._cache.mode = this.mode;
  14618. this._cache.minZ = this.minZ;
  14619. this._cache.maxZ = this.maxZ;
  14620. this._cache.fov = this.fov;
  14621. this._cache.fovMode = this.fovMode;
  14622. this._cache.aspectRatio = engine.getAspectRatio(this);
  14623. this._cache.orthoLeft = this.orthoLeft;
  14624. this._cache.orthoRight = this.orthoRight;
  14625. this._cache.orthoBottom = this.orthoBottom;
  14626. this._cache.orthoTop = this.orthoTop;
  14627. this._cache.renderWidth = engine.getRenderWidth();
  14628. this._cache.renderHeight = engine.getRenderHeight();
  14629. };
  14630. Camera.prototype._updateFromScene = function () {
  14631. this.updateCache();
  14632. this.update();
  14633. };
  14634. // Synchronized
  14635. Camera.prototype._isSynchronized = function () {
  14636. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14637. };
  14638. Camera.prototype._isSynchronizedViewMatrix = function () {
  14639. if (!_super.prototype._isSynchronized.call(this))
  14640. return false;
  14641. return this._cache.position.equals(this.position)
  14642. && this._cache.upVector.equals(this.upVector)
  14643. && this.isSynchronizedWithParent();
  14644. };
  14645. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14646. var check = this._cache.mode === this.mode
  14647. && this._cache.minZ === this.minZ
  14648. && this._cache.maxZ === this.maxZ;
  14649. if (!check) {
  14650. return false;
  14651. }
  14652. var engine = this.getEngine();
  14653. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14654. check = this._cache.fov === this.fov
  14655. && this._cache.fovMode === this.fovMode
  14656. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14657. }
  14658. else {
  14659. check = this._cache.orthoLeft === this.orthoLeft
  14660. && this._cache.orthoRight === this.orthoRight
  14661. && this._cache.orthoBottom === this.orthoBottom
  14662. && this._cache.orthoTop === this.orthoTop
  14663. && this._cache.renderWidth === engine.getRenderWidth()
  14664. && this._cache.renderHeight === engine.getRenderHeight();
  14665. }
  14666. return check;
  14667. };
  14668. // Controls
  14669. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14670. };
  14671. Camera.prototype.detachControl = function (element) {
  14672. };
  14673. Camera.prototype.update = function () {
  14674. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14675. this._updateRigCameras();
  14676. }
  14677. this._checkInputs();
  14678. };
  14679. Camera.prototype._checkInputs = function () {
  14680. this.onAfterCheckInputsObservable.notifyObservers(this);
  14681. };
  14682. Object.defineProperty(Camera.prototype, "rigCameras", {
  14683. get: function () {
  14684. return this._rigCameras;
  14685. },
  14686. enumerable: true,
  14687. configurable: true
  14688. });
  14689. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14690. get: function () {
  14691. return this._rigPostProcess;
  14692. },
  14693. enumerable: true,
  14694. configurable: true
  14695. });
  14696. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14697. // invalidate framebuffer
  14698. if (this._postProcesses.length > 0) {
  14699. this._postProcesses[0].markTextureDirty();
  14700. }
  14701. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14702. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14703. var cam = this._rigCameras[i];
  14704. var rigPostProcess = cam._rigPostProcess;
  14705. // for VR rig, there does not have to be a post process
  14706. if (rigPostProcess) {
  14707. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14708. if (isPass) {
  14709. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14710. cam.isIntermediate = this._postProcesses.length === 0;
  14711. }
  14712. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14713. rigPostProcess.markTextureDirty();
  14714. }
  14715. else {
  14716. cam._postProcesses = this._postProcesses.slice(0);
  14717. }
  14718. }
  14719. };
  14720. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14721. if (insertAt === void 0) { insertAt = null; }
  14722. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14723. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14724. return 0;
  14725. }
  14726. if (insertAt == null || insertAt < 0) {
  14727. this._postProcesses.push(postProcess);
  14728. }
  14729. else {
  14730. this._postProcesses.splice(insertAt, 0, postProcess);
  14731. }
  14732. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14733. return this._postProcesses.indexOf(postProcess);
  14734. };
  14735. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14736. if (atIndices === void 0) { atIndices = null; }
  14737. var result = [];
  14738. var i;
  14739. var index;
  14740. if (!atIndices) {
  14741. var idx = this._postProcesses.indexOf(postProcess);
  14742. if (idx !== -1) {
  14743. this._postProcesses.splice(idx, 1);
  14744. }
  14745. }
  14746. else {
  14747. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14748. // iterate descending, so can just splice as we go
  14749. for (i = atIndices.length - 1; i >= 0; i--) {
  14750. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14751. result.push(i);
  14752. continue;
  14753. }
  14754. index = atIndices[i];
  14755. this._postProcesses.splice(index, 1);
  14756. }
  14757. }
  14758. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14759. return result;
  14760. };
  14761. Camera.prototype.getWorldMatrix = function () {
  14762. if (!this._worldMatrix) {
  14763. this._worldMatrix = BABYLON.Matrix.Identity();
  14764. }
  14765. var viewMatrix = this.getViewMatrix();
  14766. viewMatrix.invertToRef(this._worldMatrix);
  14767. return this._worldMatrix;
  14768. };
  14769. Camera.prototype._getViewMatrix = function () {
  14770. return BABYLON.Matrix.Identity();
  14771. };
  14772. Camera.prototype.getViewMatrix = function (force) {
  14773. if (!force && this._isSynchronizedViewMatrix()) {
  14774. return this._computedViewMatrix;
  14775. }
  14776. this._computedViewMatrix = this._getViewMatrix();
  14777. this._currentRenderId = this.getScene().getRenderId();
  14778. this._refreshFrustumPlanes = true;
  14779. if (!this.parent || !this.parent.getWorldMatrix) {
  14780. this._globalPosition.copyFrom(this.position);
  14781. }
  14782. else {
  14783. if (!this._worldMatrix) {
  14784. this._worldMatrix = BABYLON.Matrix.Identity();
  14785. }
  14786. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14787. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14788. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14789. this._computedViewMatrix.invert();
  14790. this._markSyncedWithParent();
  14791. }
  14792. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14793. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14794. }
  14795. this.onViewMatrixChangedObservable.notifyObservers(this);
  14796. return this._computedViewMatrix;
  14797. };
  14798. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14799. this._doNotComputeProjectionMatrix = true;
  14800. if (projection !== undefined) {
  14801. this._projectionMatrix = projection;
  14802. }
  14803. };
  14804. ;
  14805. Camera.prototype.unfreezeProjectionMatrix = function () {
  14806. this._doNotComputeProjectionMatrix = false;
  14807. };
  14808. ;
  14809. Camera.prototype.getProjectionMatrix = function (force) {
  14810. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14811. return this._projectionMatrix;
  14812. }
  14813. this._refreshFrustumPlanes = true;
  14814. var engine = this.getEngine();
  14815. var scene = this.getScene();
  14816. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14817. if (this.minZ <= 0) {
  14818. this.minZ = 0.1;
  14819. }
  14820. if (scene.useRightHandedSystem) {
  14821. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14822. }
  14823. else {
  14824. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14825. }
  14826. }
  14827. else {
  14828. var halfWidth = engine.getRenderWidth() / 2.0;
  14829. var halfHeight = engine.getRenderHeight() / 2.0;
  14830. if (scene.useRightHandedSystem) {
  14831. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14832. }
  14833. else {
  14834. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14835. }
  14836. }
  14837. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  14838. return this._projectionMatrix;
  14839. };
  14840. Camera.prototype.getTranformationMatrix = function () {
  14841. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14842. return this._transformMatrix;
  14843. };
  14844. Camera.prototype.updateFrustumPlanes = function () {
  14845. if (!this._refreshFrustumPlanes) {
  14846. return;
  14847. }
  14848. this.getTranformationMatrix();
  14849. if (!this._frustumPlanes) {
  14850. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14851. }
  14852. else {
  14853. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14854. }
  14855. this._refreshFrustumPlanes = false;
  14856. };
  14857. Camera.prototype.isInFrustum = function (target) {
  14858. this.updateFrustumPlanes();
  14859. return target.isInFrustum(this._frustumPlanes);
  14860. };
  14861. Camera.prototype.isCompletelyInFrustum = function (target) {
  14862. this.updateFrustumPlanes();
  14863. return target.isCompletelyInFrustum(this._frustumPlanes);
  14864. };
  14865. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14866. if (length === void 0) { length = 100; }
  14867. if (!transform) {
  14868. transform = this.getWorldMatrix();
  14869. }
  14870. if (!origin) {
  14871. origin = this.position;
  14872. }
  14873. var forward = new BABYLON.Vector3(0, 0, 1);
  14874. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14875. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14876. return new BABYLON.Ray(origin, direction, length);
  14877. };
  14878. Camera.prototype.dispose = function () {
  14879. // Observables
  14880. this.onViewMatrixChangedObservable.clear();
  14881. this.onProjectionMatrixChangedObservable.clear();
  14882. this.onAfterCheckInputsObservable.clear();
  14883. // Inputs
  14884. this.inputs.clear();
  14885. // Animations
  14886. this.getScene().stopAnimation(this);
  14887. // Remove from scene
  14888. this.getScene().removeCamera(this);
  14889. while (this._rigCameras.length > 0) {
  14890. this._rigCameras.pop().dispose();
  14891. }
  14892. // Postprocesses
  14893. var i = this._postProcesses.length;
  14894. while (--i >= 0) {
  14895. this._postProcesses[i].dispose(this);
  14896. }
  14897. // Render targets
  14898. var i = this.customRenderTargets.length;
  14899. while (--i >= 0) {
  14900. this.customRenderTargets[i].dispose();
  14901. }
  14902. this.customRenderTargets = [];
  14903. // Active Meshes
  14904. this._activeMeshes.dispose();
  14905. _super.prototype.dispose.call(this);
  14906. };
  14907. Object.defineProperty(Camera.prototype, "leftCamera", {
  14908. // ---- Camera rigs section ----
  14909. get: function () {
  14910. if (this._rigCameras.length < 1) {
  14911. return undefined;
  14912. }
  14913. return this._rigCameras[0];
  14914. },
  14915. enumerable: true,
  14916. configurable: true
  14917. });
  14918. Object.defineProperty(Camera.prototype, "rightCamera", {
  14919. get: function () {
  14920. if (this._rigCameras.length < 2) {
  14921. return undefined;
  14922. }
  14923. return this._rigCameras[1];
  14924. },
  14925. enumerable: true,
  14926. configurable: true
  14927. });
  14928. Camera.prototype.getLeftTarget = function () {
  14929. if (this._rigCameras.length < 1) {
  14930. return undefined;
  14931. }
  14932. return this._rigCameras[0].getTarget();
  14933. };
  14934. Camera.prototype.getRightTarget = function () {
  14935. if (this._rigCameras.length < 2) {
  14936. return undefined;
  14937. }
  14938. return this._rigCameras[1].getTarget();
  14939. };
  14940. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14941. while (this._rigCameras.length > 0) {
  14942. this._rigCameras.pop().dispose();
  14943. }
  14944. this.cameraRigMode = mode;
  14945. this._cameraRigParams = {};
  14946. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14947. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14948. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14949. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14950. // create the rig cameras, unless none
  14951. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14952. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14953. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14954. }
  14955. switch (this.cameraRigMode) {
  14956. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14957. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14958. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14959. break;
  14960. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14961. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14962. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14963. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14964. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14965. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14966. break;
  14967. case Camera.RIG_MODE_VR:
  14968. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14969. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14970. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14971. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14972. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14973. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14974. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14975. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14976. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14977. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14978. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14979. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14980. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14981. if (metrics.compensateDistortion) {
  14982. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14983. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14984. }
  14985. break;
  14986. case Camera.RIG_MODE_WEBVR:
  14987. if (rigParams.vrDisplay) {
  14988. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14989. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14990. //Left eye
  14991. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14992. this._rigCameras[0].setCameraRigParameter("left", true);
  14993. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14994. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14995. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14996. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14997. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14998. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14999. this._rigCameras[0].parent = this;
  15000. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15001. //Right eye
  15002. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15003. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15004. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15005. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15006. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15007. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15008. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15009. this._rigCameras[1].parent = this;
  15010. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15011. }
  15012. break;
  15013. }
  15014. this._cascadePostProcessesToRigCams();
  15015. this.
  15016. update();
  15017. };
  15018. Camera.prototype._getVRProjectionMatrix = function () {
  15019. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15020. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15021. return this._projectionMatrix;
  15022. };
  15023. Camera.prototype._updateCameraRotationMatrix = function () {
  15024. //Here for WebVR
  15025. };
  15026. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15027. //Here for WebVR
  15028. };
  15029. /**
  15030. * This function MUST be overwritten by the different WebVR cameras available.
  15031. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15032. */
  15033. Camera.prototype._getWebVRProjectionMatrix = function () {
  15034. return BABYLON.Matrix.Identity();
  15035. };
  15036. /**
  15037. * This function MUST be overwritten by the different WebVR cameras available.
  15038. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15039. */
  15040. Camera.prototype._getWebVRViewMatrix = function () {
  15041. return BABYLON.Matrix.Identity();
  15042. };
  15043. Camera.prototype.setCameraRigParameter = function (name, value) {
  15044. if (!this._cameraRigParams) {
  15045. this._cameraRigParams = {};
  15046. }
  15047. this._cameraRigParams[name] = value;
  15048. //provisionnally:
  15049. if (name === "interaxialDistance") {
  15050. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15051. }
  15052. };
  15053. /**
  15054. * needs to be overridden by children so sub has required properties to be copied
  15055. */
  15056. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15057. return null;
  15058. };
  15059. /**
  15060. * May need to be overridden by children
  15061. */
  15062. Camera.prototype._updateRigCameras = function () {
  15063. for (var i = 0; i < this._rigCameras.length; i++) {
  15064. this._rigCameras[i].minZ = this.minZ;
  15065. this._rigCameras[i].maxZ = this.maxZ;
  15066. this._rigCameras[i].fov = this.fov;
  15067. }
  15068. // only update viewport when ANAGLYPH
  15069. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15070. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15071. }
  15072. };
  15073. Camera.prototype._setupInputs = function () {
  15074. };
  15075. Camera.prototype.serialize = function () {
  15076. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15077. // Type
  15078. serializationObject.type = this.getClassName();
  15079. // Parent
  15080. if (this.parent) {
  15081. serializationObject.parentId = this.parent.id;
  15082. }
  15083. if (this.inputs) {
  15084. this.inputs.serialize(serializationObject);
  15085. }
  15086. // Animations
  15087. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15088. serializationObject.ranges = this.serializeAnimationRanges();
  15089. return serializationObject;
  15090. };
  15091. Camera.prototype.clone = function (name) {
  15092. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15093. };
  15094. Camera.prototype.getDirection = function (localAxis) {
  15095. var result = BABYLON.Vector3.Zero();
  15096. this.getDirectionToRef(localAxis, result);
  15097. return result;
  15098. };
  15099. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15100. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15101. };
  15102. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15103. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15104. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15105. switch (type) {
  15106. case "ArcRotateCamera":
  15107. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15108. case "DeviceOrientationCamera":
  15109. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15110. case "FollowCamera":
  15111. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15112. case "ArcFollowCamera":
  15113. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15114. case "GamepadCamera":
  15115. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15116. case "TouchCamera":
  15117. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15118. case "VirtualJoysticksCamera":
  15119. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15120. case "WebVRFreeCamera":
  15121. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15122. case "WebVRGamepadCamera":
  15123. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15124. case "VRDeviceOrientationFreeCamera":
  15125. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15126. case "VRDeviceOrientationGamepadCamera":
  15127. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15128. case "AnaglyphArcRotateCamera":
  15129. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15130. case "AnaglyphFreeCamera":
  15131. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15132. case "AnaglyphGamepadCamera":
  15133. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15134. case "AnaglyphUniversalCamera":
  15135. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15136. case "StereoscopicArcRotateCamera":
  15137. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15138. case "StereoscopicFreeCamera":
  15139. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15140. case "StereoscopicGamepadCamera":
  15141. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15142. case "StereoscopicUniversalCamera":
  15143. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15144. case "FreeCamera":// Forcing Universal here
  15145. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15146. default:// Universal Camera is the default value
  15147. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15148. }
  15149. };
  15150. Camera.Parse = function (parsedCamera, scene) {
  15151. var type = parsedCamera.type;
  15152. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15153. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15154. // Parent
  15155. if (parsedCamera.parentId) {
  15156. camera._waitingParentId = parsedCamera.parentId;
  15157. }
  15158. //If camera has an input manager, let it parse inputs settings
  15159. if (camera.inputs) {
  15160. camera.inputs.parse(parsedCamera);
  15161. camera._setupInputs();
  15162. }
  15163. if (camera.setPosition) {
  15164. camera.position.copyFromFloats(0, 0, 0);
  15165. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15166. }
  15167. // Target
  15168. if (parsedCamera.target) {
  15169. if (camera.setTarget) {
  15170. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15171. }
  15172. }
  15173. // Apply 3d rig, when found
  15174. if (parsedCamera.cameraRigMode) {
  15175. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15176. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15177. }
  15178. // Animations
  15179. if (parsedCamera.animations) {
  15180. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15181. var parsedAnimation = parsedCamera.animations[animationIndex];
  15182. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15183. }
  15184. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15185. }
  15186. if (parsedCamera.autoAnimate) {
  15187. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15188. }
  15189. return camera;
  15190. };
  15191. // Statics
  15192. Camera._PERSPECTIVE_CAMERA = 0;
  15193. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15194. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15195. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15196. Camera._RIG_MODE_NONE = 0;
  15197. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15198. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15199. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15200. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15201. Camera._RIG_MODE_VR = 20;
  15202. Camera._RIG_MODE_WEBVR = 21;
  15203. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15204. __decorate([
  15205. BABYLON.serializeAsVector3()
  15206. ], Camera.prototype, "position", void 0);
  15207. __decorate([
  15208. BABYLON.serializeAsVector3()
  15209. ], Camera.prototype, "upVector", void 0);
  15210. __decorate([
  15211. BABYLON.serialize()
  15212. ], Camera.prototype, "orthoLeft", void 0);
  15213. __decorate([
  15214. BABYLON.serialize()
  15215. ], Camera.prototype, "orthoRight", void 0);
  15216. __decorate([
  15217. BABYLON.serialize()
  15218. ], Camera.prototype, "orthoBottom", void 0);
  15219. __decorate([
  15220. BABYLON.serialize()
  15221. ], Camera.prototype, "orthoTop", void 0);
  15222. __decorate([
  15223. BABYLON.serialize()
  15224. ], Camera.prototype, "fov", void 0);
  15225. __decorate([
  15226. BABYLON.serialize()
  15227. ], Camera.prototype, "minZ", void 0);
  15228. __decorate([
  15229. BABYLON.serialize()
  15230. ], Camera.prototype, "maxZ", void 0);
  15231. __decorate([
  15232. BABYLON.serialize()
  15233. ], Camera.prototype, "inertia", void 0);
  15234. __decorate([
  15235. BABYLON.serialize()
  15236. ], Camera.prototype, "mode", void 0);
  15237. __decorate([
  15238. BABYLON.serialize()
  15239. ], Camera.prototype, "layerMask", void 0);
  15240. __decorate([
  15241. BABYLON.serialize()
  15242. ], Camera.prototype, "fovMode", void 0);
  15243. __decorate([
  15244. BABYLON.serialize()
  15245. ], Camera.prototype, "cameraRigMode", void 0);
  15246. __decorate([
  15247. BABYLON.serialize()
  15248. ], Camera.prototype, "interaxialDistance", void 0);
  15249. __decorate([
  15250. BABYLON.serialize()
  15251. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15252. return Camera;
  15253. }(BABYLON.Node));
  15254. BABYLON.Camera = Camera;
  15255. })(BABYLON || (BABYLON = {}));
  15256. //# sourceMappingURL=babylon.camera.js.map
  15257. var BABYLON;
  15258. (function (BABYLON) {
  15259. var RenderingManager = (function () {
  15260. function RenderingManager(scene) {
  15261. this._renderingGroups = new Array();
  15262. this._autoClearDepthStencil = {};
  15263. this._customOpaqueSortCompareFn = {};
  15264. this._customAlphaTestSortCompareFn = {};
  15265. this._customTransparentSortCompareFn = {};
  15266. this._renderinGroupInfo = null;
  15267. this._scene = scene;
  15268. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15269. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15270. }
  15271. }
  15272. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15273. if (depth === void 0) { depth = true; }
  15274. if (stencil === void 0) { stencil = true; }
  15275. if (this._depthStencilBufferAlreadyCleaned) {
  15276. return;
  15277. }
  15278. this._scene.getEngine().clear(null, false, depth, stencil);
  15279. this._depthStencilBufferAlreadyCleaned = true;
  15280. };
  15281. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15282. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15283. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15284. var info = null;
  15285. if (observable) {
  15286. if (!this._renderinGroupInfo) {
  15287. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15288. }
  15289. info = this._renderinGroupInfo;
  15290. info.scene = this._scene;
  15291. info.camera = this._scene.activeCamera;
  15292. }
  15293. // Dispatch sprites
  15294. if (renderSprites) {
  15295. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15296. var manager = this._scene.spriteManagers[index];
  15297. this.dispatchSprites(manager);
  15298. }
  15299. }
  15300. // Render
  15301. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15302. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15303. var renderingGroup = this._renderingGroups[index];
  15304. if (!renderingGroup && !observable)
  15305. continue;
  15306. this._currentIndex = index;
  15307. var renderingGroupMask = 0;
  15308. // Fire PRECLEAR stage
  15309. if (observable) {
  15310. renderingGroupMask = Math.pow(2, index);
  15311. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15312. info.renderingGroupId = index;
  15313. observable.notifyObservers(info, renderingGroupMask);
  15314. }
  15315. // Clear depth/stencil if needed
  15316. if (RenderingManager.AUTOCLEAR) {
  15317. var autoClear = this._autoClearDepthStencil[index];
  15318. if (autoClear && autoClear.autoClear) {
  15319. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15320. }
  15321. }
  15322. if (observable) {
  15323. // Fire PREOPAQUE stage
  15324. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15325. observable.notifyObservers(info, renderingGroupMask);
  15326. // Fire PRETRANSPARENT stage
  15327. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15328. observable.notifyObservers(info, renderingGroupMask);
  15329. }
  15330. if (renderingGroup)
  15331. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15332. // Fire POSTTRANSPARENT stage
  15333. if (observable) {
  15334. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15335. observable.notifyObservers(info, renderingGroupMask);
  15336. }
  15337. }
  15338. };
  15339. RenderingManager.prototype.reset = function () {
  15340. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15341. var renderingGroup = this._renderingGroups[index];
  15342. if (renderingGroup) {
  15343. renderingGroup.prepare();
  15344. }
  15345. }
  15346. };
  15347. RenderingManager.prototype.dispose = function () {
  15348. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15349. var renderingGroup = this._renderingGroups[index];
  15350. if (renderingGroup) {
  15351. renderingGroup.dispose();
  15352. }
  15353. }
  15354. this._renderingGroups.length = 0;
  15355. };
  15356. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15357. if (!this._renderingGroups[renderingGroupId]) {
  15358. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15359. }
  15360. };
  15361. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15362. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15363. this._prepareRenderingGroup(renderingGroupId);
  15364. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15365. };
  15366. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15367. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15368. this._prepareRenderingGroup(renderingGroupId);
  15369. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15370. };
  15371. RenderingManager.prototype.dispatch = function (subMesh) {
  15372. var mesh = subMesh.getMesh();
  15373. var renderingGroupId = mesh.renderingGroupId || 0;
  15374. this._prepareRenderingGroup(renderingGroupId);
  15375. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15376. };
  15377. /**
  15378. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15379. * This allowed control for front to back rendering or reversly depending of the special needs.
  15380. *
  15381. * @param renderingGroupId The rendering group id corresponding to its index
  15382. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15383. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15384. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15385. */
  15386. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15387. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15388. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15389. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15390. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15391. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15392. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15393. if (this._renderingGroups[renderingGroupId]) {
  15394. var group = this._renderingGroups[renderingGroupId];
  15395. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15396. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15397. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15398. }
  15399. };
  15400. /**
  15401. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15402. *
  15403. * @param renderingGroupId The rendering group id corresponding to its index
  15404. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15405. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15406. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15407. */
  15408. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15409. if (depth === void 0) { depth = true; }
  15410. if (stencil === void 0) { stencil = true; }
  15411. this._autoClearDepthStencil[renderingGroupId] = {
  15412. autoClear: autoClearDepthStencil,
  15413. depth: depth,
  15414. stencil: stencil
  15415. };
  15416. };
  15417. /**
  15418. * The max id used for rendering groups (not included)
  15419. */
  15420. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15421. /**
  15422. * The min id used for rendering groups (included)
  15423. */
  15424. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15425. /**
  15426. * Used to globally prevent autoclearing scenes.
  15427. */
  15428. RenderingManager.AUTOCLEAR = true;
  15429. return RenderingManager;
  15430. }());
  15431. BABYLON.RenderingManager = RenderingManager;
  15432. })(BABYLON || (BABYLON = {}));
  15433. //# sourceMappingURL=babylon.renderingManager.js.map
  15434. var BABYLON;
  15435. (function (BABYLON) {
  15436. var RenderingGroup = (function () {
  15437. /**
  15438. * Creates a new rendering group.
  15439. * @param index The rendering group index
  15440. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15441. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15442. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15443. */
  15444. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15445. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15446. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15447. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15448. this.index = index;
  15449. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15450. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15451. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15452. this._particleSystems = new BABYLON.SmartArray(256);
  15453. this._spriteManagers = new BABYLON.SmartArray(256);
  15454. this._edgesRenderers = new BABYLON.SmartArray(16);
  15455. this._scene = scene;
  15456. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15457. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15458. this.transparentSortCompareFn = transparentSortCompareFn;
  15459. }
  15460. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15461. /**
  15462. * Set the opaque sort comparison function.
  15463. * If null the sub meshes will be render in the order they were created
  15464. */
  15465. set: function (value) {
  15466. this._opaqueSortCompareFn = value;
  15467. if (value) {
  15468. this._renderOpaque = this.renderOpaqueSorted;
  15469. }
  15470. else {
  15471. this._renderOpaque = RenderingGroup.renderUnsorted;
  15472. }
  15473. },
  15474. enumerable: true,
  15475. configurable: true
  15476. });
  15477. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15478. /**
  15479. * Set the alpha test sort comparison function.
  15480. * If null the sub meshes will be render in the order they were created
  15481. */
  15482. set: function (value) {
  15483. this._alphaTestSortCompareFn = value;
  15484. if (value) {
  15485. this._renderAlphaTest = this.renderAlphaTestSorted;
  15486. }
  15487. else {
  15488. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15489. }
  15490. },
  15491. enumerable: true,
  15492. configurable: true
  15493. });
  15494. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15495. /**
  15496. * Set the transparent sort comparison function.
  15497. * If null the sub meshes will be render in the order they were created
  15498. */
  15499. set: function (value) {
  15500. if (value) {
  15501. this._transparentSortCompareFn = value;
  15502. }
  15503. else {
  15504. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15505. }
  15506. this._renderTransparent = this.renderTransparentSorted;
  15507. },
  15508. enumerable: true,
  15509. configurable: true
  15510. });
  15511. /**
  15512. * Render all the sub meshes contained in the group.
  15513. * @param customRenderFunction Used to override the default render behaviour of the group.
  15514. * @returns true if rendered some submeshes.
  15515. */
  15516. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  15517. if (customRenderFunction) {
  15518. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15519. return;
  15520. }
  15521. var engine = this._scene.getEngine();
  15522. // Opaque
  15523. if (this._opaqueSubMeshes.length !== 0) {
  15524. this._renderOpaque(this._opaqueSubMeshes);
  15525. }
  15526. // Alpha test
  15527. if (this._alphaTestSubMeshes.length !== 0) {
  15528. engine.setAlphaTesting(true);
  15529. this._renderAlphaTest(this._alphaTestSubMeshes);
  15530. engine.setAlphaTesting(false);
  15531. }
  15532. var stencilState = engine.getStencilBuffer();
  15533. engine.setStencilBuffer(false);
  15534. // Sprites
  15535. if (renderSprites) {
  15536. this._renderSprites();
  15537. }
  15538. // Particles
  15539. if (renderParticles) {
  15540. this._renderParticles(activeMeshes);
  15541. }
  15542. if (this.onBeforeTransparentRendering) {
  15543. this.onBeforeTransparentRendering();
  15544. }
  15545. // Transparent
  15546. if (this._transparentSubMeshes.length !== 0) {
  15547. this._renderTransparent(this._transparentSubMeshes);
  15548. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15549. }
  15550. // Set back stencil to false in case it changes before the edge renderer.
  15551. engine.setStencilBuffer(false);
  15552. // Edges
  15553. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15554. this._edgesRenderers.data[edgesRendererIndex].render();
  15555. }
  15556. // Restore Stencil state.
  15557. engine.setStencilBuffer(stencilState);
  15558. };
  15559. /**
  15560. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15561. * @param subMeshes The submeshes to render
  15562. */
  15563. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15564. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15565. };
  15566. /**
  15567. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15568. * @param subMeshes The submeshes to render
  15569. */
  15570. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15571. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15572. };
  15573. /**
  15574. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15575. * @param subMeshes The submeshes to render
  15576. */
  15577. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15578. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15579. };
  15580. /**
  15581. * Renders the submeshes in a specified order.
  15582. * @param subMeshes The submeshes to sort before render
  15583. * @param sortCompareFn The comparison function use to sort
  15584. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15585. * @param transparent Specifies to activate blending if true
  15586. */
  15587. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15588. var subIndex = 0;
  15589. var subMesh;
  15590. for (; subIndex < subMeshes.length; subIndex++) {
  15591. subMesh = subMeshes.data[subIndex];
  15592. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15593. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15594. }
  15595. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15596. sortedArray.sort(sortCompareFn);
  15597. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15598. subMesh = sortedArray[subIndex];
  15599. subMesh.render(transparent);
  15600. }
  15601. };
  15602. /**
  15603. * Renders the submeshes in the order they were dispatched (no sort applied).
  15604. * @param subMeshes The submeshes to render
  15605. */
  15606. RenderingGroup.renderUnsorted = function (subMeshes) {
  15607. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15608. var submesh = subMeshes.data[subIndex];
  15609. submesh.render(false);
  15610. }
  15611. };
  15612. /**
  15613. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15614. * are rendered back to front if in the same alpha index.
  15615. *
  15616. * @param a The first submesh
  15617. * @param b The second submesh
  15618. * @returns The result of the comparison
  15619. */
  15620. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15621. // Alpha index first
  15622. if (a._alphaIndex > b._alphaIndex) {
  15623. return 1;
  15624. }
  15625. if (a._alphaIndex < b._alphaIndex) {
  15626. return -1;
  15627. }
  15628. // Then distance to camera
  15629. return RenderingGroup.backToFrontSortCompare(a, b);
  15630. };
  15631. /**
  15632. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15633. * are rendered back to front.
  15634. *
  15635. * @param a The first submesh
  15636. * @param b The second submesh
  15637. * @returns The result of the comparison
  15638. */
  15639. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15640. // Then distance to camera
  15641. if (a._distanceToCamera < b._distanceToCamera) {
  15642. return 1;
  15643. }
  15644. if (a._distanceToCamera > b._distanceToCamera) {
  15645. return -1;
  15646. }
  15647. return 0;
  15648. };
  15649. /**
  15650. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15651. * are rendered front to back (prevent overdraw).
  15652. *
  15653. * @param a The first submesh
  15654. * @param b The second submesh
  15655. * @returns The result of the comparison
  15656. */
  15657. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15658. // Then distance to camera
  15659. if (a._distanceToCamera < b._distanceToCamera) {
  15660. return -1;
  15661. }
  15662. if (a._distanceToCamera > b._distanceToCamera) {
  15663. return 1;
  15664. }
  15665. return 0;
  15666. };
  15667. /**
  15668. * Resets the different lists of submeshes to prepare a new frame.
  15669. */
  15670. RenderingGroup.prototype.prepare = function () {
  15671. this._opaqueSubMeshes.reset();
  15672. this._transparentSubMeshes.reset();
  15673. this._alphaTestSubMeshes.reset();
  15674. this._particleSystems.reset();
  15675. this._spriteManagers.reset();
  15676. this._edgesRenderers.reset();
  15677. };
  15678. RenderingGroup.prototype.dispose = function () {
  15679. this._opaqueSubMeshes.dispose();
  15680. this._transparentSubMeshes.dispose();
  15681. this._alphaTestSubMeshes.dispose();
  15682. this._particleSystems.dispose();
  15683. this._spriteManagers.dispose();
  15684. this._edgesRenderers.dispose();
  15685. };
  15686. /**
  15687. * Inserts the submesh in its correct queue depending on its material.
  15688. * @param subMesh The submesh to dispatch
  15689. */
  15690. RenderingGroup.prototype.dispatch = function (subMesh) {
  15691. var material = subMesh.getMaterial();
  15692. var mesh = subMesh.getMesh();
  15693. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15694. this._transparentSubMeshes.push(subMesh);
  15695. }
  15696. else if (material.needAlphaTesting()) {
  15697. this._alphaTestSubMeshes.push(subMesh);
  15698. }
  15699. else {
  15700. this._opaqueSubMeshes.push(subMesh); // Opaque
  15701. }
  15702. if (mesh._edgesRenderer) {
  15703. this._edgesRenderers.push(mesh._edgesRenderer);
  15704. }
  15705. };
  15706. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15707. this._spriteManagers.push(spriteManager);
  15708. };
  15709. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15710. this._particleSystems.push(particleSystem);
  15711. };
  15712. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15713. if (this._particleSystems.length === 0) {
  15714. return;
  15715. }
  15716. // Particles
  15717. var activeCamera = this._scene.activeCamera;
  15718. this._scene._particlesDuration.beginMonitoring();
  15719. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15720. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15721. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15722. continue;
  15723. }
  15724. var emitter = particleSystem.emitter;
  15725. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  15726. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15727. }
  15728. }
  15729. this._scene._particlesDuration.endMonitoring(false);
  15730. };
  15731. RenderingGroup.prototype._renderSprites = function () {
  15732. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15733. return;
  15734. }
  15735. // Sprites
  15736. var activeCamera = this._scene.activeCamera;
  15737. this._scene._spritesDuration.beginMonitoring();
  15738. for (var id = 0; id < this._spriteManagers.length; id++) {
  15739. var spriteManager = this._spriteManagers.data[id];
  15740. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15741. spriteManager.render();
  15742. }
  15743. }
  15744. this._scene._spritesDuration.endMonitoring(false);
  15745. };
  15746. return RenderingGroup;
  15747. }());
  15748. BABYLON.RenderingGroup = RenderingGroup;
  15749. })(BABYLON || (BABYLON = {}));
  15750. //# sourceMappingURL=babylon.renderingGroup.js.map
  15751. var BABYLON;
  15752. (function (BABYLON) {
  15753. var ClickInfo = (function () {
  15754. function ClickInfo() {
  15755. this._singleClick = false;
  15756. this._doubleClick = false;
  15757. this._hasSwiped = false;
  15758. this._ignore = false;
  15759. }
  15760. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15761. get: function () {
  15762. return this._singleClick;
  15763. },
  15764. set: function (b) {
  15765. this._singleClick = b;
  15766. },
  15767. enumerable: true,
  15768. configurable: true
  15769. });
  15770. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15771. get: function () {
  15772. return this._doubleClick;
  15773. },
  15774. set: function (b) {
  15775. this._doubleClick = b;
  15776. },
  15777. enumerable: true,
  15778. configurable: true
  15779. });
  15780. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15781. get: function () {
  15782. return this._hasSwiped;
  15783. },
  15784. set: function (b) {
  15785. this._hasSwiped = b;
  15786. },
  15787. enumerable: true,
  15788. configurable: true
  15789. });
  15790. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15791. get: function () {
  15792. return this._ignore;
  15793. },
  15794. set: function (b) {
  15795. this._ignore = b;
  15796. },
  15797. enumerable: true,
  15798. configurable: true
  15799. });
  15800. return ClickInfo;
  15801. }());
  15802. var PointerEventTypes = (function () {
  15803. function PointerEventTypes() {
  15804. }
  15805. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15806. get: function () {
  15807. return PointerEventTypes._POINTERDOWN;
  15808. },
  15809. enumerable: true,
  15810. configurable: true
  15811. });
  15812. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15813. get: function () {
  15814. return PointerEventTypes._POINTERUP;
  15815. },
  15816. enumerable: true,
  15817. configurable: true
  15818. });
  15819. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15820. get: function () {
  15821. return PointerEventTypes._POINTERMOVE;
  15822. },
  15823. enumerable: true,
  15824. configurable: true
  15825. });
  15826. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15827. get: function () {
  15828. return PointerEventTypes._POINTERWHEEL;
  15829. },
  15830. enumerable: true,
  15831. configurable: true
  15832. });
  15833. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15834. get: function () {
  15835. return PointerEventTypes._POINTERPICK;
  15836. },
  15837. enumerable: true,
  15838. configurable: true
  15839. });
  15840. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15841. get: function () {
  15842. return PointerEventTypes._POINTERTAP;
  15843. },
  15844. enumerable: true,
  15845. configurable: true
  15846. });
  15847. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15848. get: function () {
  15849. return PointerEventTypes._POINTERDOUBLETAP;
  15850. },
  15851. enumerable: true,
  15852. configurable: true
  15853. });
  15854. PointerEventTypes._POINTERDOWN = 0x01;
  15855. PointerEventTypes._POINTERUP = 0x02;
  15856. PointerEventTypes._POINTERMOVE = 0x04;
  15857. PointerEventTypes._POINTERWHEEL = 0x08;
  15858. PointerEventTypes._POINTERPICK = 0x10;
  15859. PointerEventTypes._POINTERTAP = 0x20;
  15860. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15861. return PointerEventTypes;
  15862. }());
  15863. BABYLON.PointerEventTypes = PointerEventTypes;
  15864. var PointerInfoBase = (function () {
  15865. function PointerInfoBase(type, event) {
  15866. this.type = type;
  15867. this.event = event;
  15868. }
  15869. return PointerInfoBase;
  15870. }());
  15871. BABYLON.PointerInfoBase = PointerInfoBase;
  15872. /**
  15873. * This class is used to store pointer related info for the onPrePointerObservable event.
  15874. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15875. */
  15876. var PointerInfoPre = (function (_super) {
  15877. __extends(PointerInfoPre, _super);
  15878. function PointerInfoPre(type, event, localX, localY) {
  15879. var _this = _super.call(this, type, event) || this;
  15880. _this.skipOnPointerObservable = false;
  15881. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15882. return _this;
  15883. }
  15884. return PointerInfoPre;
  15885. }(PointerInfoBase));
  15886. BABYLON.PointerInfoPre = PointerInfoPre;
  15887. /**
  15888. * This type contains all the data related to a pointer event in Babylon.js.
  15889. * 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.
  15890. */
  15891. var PointerInfo = (function (_super) {
  15892. __extends(PointerInfo, _super);
  15893. function PointerInfo(type, event, pickInfo) {
  15894. var _this = _super.call(this, type, event) || this;
  15895. _this.pickInfo = pickInfo;
  15896. return _this;
  15897. }
  15898. return PointerInfo;
  15899. }(PointerInfoBase));
  15900. BABYLON.PointerInfo = PointerInfo;
  15901. /**
  15902. * This class is used by the onRenderingGroupObservable
  15903. */
  15904. var RenderingGroupInfo = (function () {
  15905. function RenderingGroupInfo() {
  15906. }
  15907. /**
  15908. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15909. * This stage will be fired no matter what
  15910. */
  15911. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15912. /**
  15913. * Called before opaque object are rendered.
  15914. * This stage will be fired only if there's 3D Opaque content to render
  15915. */
  15916. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15917. /**
  15918. * Called after the opaque objects are rendered and before the transparent ones
  15919. * This stage will be fired only if there's 3D transparent content to render
  15920. */
  15921. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15922. /**
  15923. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15924. * This stage will be fired no matter what
  15925. */
  15926. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15927. return RenderingGroupInfo;
  15928. }());
  15929. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15930. /**
  15931. * Represents a scene to be rendered by the engine.
  15932. * @see http://doc.babylonjs.com/page.php?p=21911
  15933. */
  15934. var Scene = (function () {
  15935. /**
  15936. * @constructor
  15937. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15938. */
  15939. function Scene(engine) {
  15940. // Members
  15941. this.autoClear = true;
  15942. this.autoClearDepthAndStencil = true;
  15943. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15944. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15945. this.forceWireframe = false;
  15946. this._forcePointsCloud = false;
  15947. this.forceShowBoundingBoxes = false;
  15948. this.animationsEnabled = true;
  15949. this.constantlyUpdateMeshUnderPointer = false;
  15950. this.hoverCursor = "pointer";
  15951. this.defaultCursor = "";
  15952. // Metadata
  15953. this.metadata = null;
  15954. // Events
  15955. /**
  15956. * An event triggered when the scene is disposed.
  15957. * @type {BABYLON.Observable}
  15958. */
  15959. this.onDisposeObservable = new BABYLON.Observable();
  15960. /**
  15961. * An event triggered before rendering the scene
  15962. * @type {BABYLON.Observable}
  15963. */
  15964. this.onBeforeRenderObservable = new BABYLON.Observable();
  15965. /**
  15966. * An event triggered after rendering the scene
  15967. * @type {BABYLON.Observable}
  15968. */
  15969. this.onAfterRenderObservable = new BABYLON.Observable();
  15970. /**
  15971. * An event triggered when the scene is ready
  15972. * @type {BABYLON.Observable}
  15973. */
  15974. this.onReadyObservable = new BABYLON.Observable();
  15975. /**
  15976. * An event triggered before rendering a camera
  15977. * @type {BABYLON.Observable}
  15978. */
  15979. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15980. /**
  15981. * An event triggered after rendering a camera
  15982. * @type {BABYLON.Observable}
  15983. */
  15984. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15985. /**
  15986. * An event triggered when a camera is created
  15987. * @type {BABYLON.Observable}
  15988. */
  15989. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15990. /**
  15991. * An event triggered when a camera is removed
  15992. * @type {BABYLON.Observable}
  15993. */
  15994. this.onCameraRemovedObservable = new BABYLON.Observable();
  15995. /**
  15996. * An event triggered when a light is created
  15997. * @type {BABYLON.Observable}
  15998. */
  15999. this.onNewLightAddedObservable = new BABYLON.Observable();
  16000. /**
  16001. * An event triggered when a light is removed
  16002. * @type {BABYLON.Observable}
  16003. */
  16004. this.onLightRemovedObservable = new BABYLON.Observable();
  16005. /**
  16006. * An event triggered when a geometry is created
  16007. * @type {BABYLON.Observable}
  16008. */
  16009. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16010. /**
  16011. * An event triggered when a geometry is removed
  16012. * @type {BABYLON.Observable}
  16013. */
  16014. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16015. /**
  16016. * An event triggered when a mesh is created
  16017. * @type {BABYLON.Observable}
  16018. */
  16019. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16020. /**
  16021. * An event triggered when a mesh is removed
  16022. * @type {BABYLON.Observable}
  16023. */
  16024. this.onMeshRemovedObservable = new BABYLON.Observable();
  16025. /**
  16026. * An event triggered before calculating deterministic simulation step
  16027. * @type {BABYLON.Observable}
  16028. */
  16029. this.onBeforeStepObservable = new BABYLON.Observable();
  16030. /**
  16031. * An event triggered after calculating deterministic simulation step
  16032. * @type {BABYLON.Observable}
  16033. */
  16034. this.onAfterStepObservable = new BABYLON.Observable();
  16035. /**
  16036. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16037. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16038. * 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)
  16039. */
  16040. this.onRenderingGroupObservable = new BABYLON.Observable();
  16041. // Animations
  16042. this.animations = [];
  16043. /**
  16044. * 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).
  16045. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16046. */
  16047. this.onPrePointerObservable = new BABYLON.Observable();
  16048. /**
  16049. * Observable event triggered each time an input event is received from the rendering canvas
  16050. */
  16051. this.onPointerObservable = new BABYLON.Observable();
  16052. this._meshPickProceed = false;
  16053. this._previousHasSwiped = false;
  16054. this._currentPickResult = null;
  16055. this._previousPickResult = null;
  16056. this._isButtonPressed = false;
  16057. this._doubleClickOccured = false;
  16058. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16059. this.cameraToUseForPointers = null;
  16060. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16061. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16062. this._startingPointerTime = 0;
  16063. this._previousStartingPointerTime = 0;
  16064. // Deterministic lockstep
  16065. this._timeAccumulator = 0;
  16066. this._currentStepId = 0;
  16067. this._currentInternalStep = 0;
  16068. // Coordinate system
  16069. /**
  16070. * use right-handed coordinate system on this scene.
  16071. * @type {boolean}
  16072. */
  16073. this._useRightHandedSystem = false;
  16074. // Fog
  16075. this._fogEnabled = true;
  16076. this._fogMode = Scene.FOGMODE_NONE;
  16077. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16078. this.fogDensity = 0.1;
  16079. this.fogStart = 0;
  16080. this.fogEnd = 1000.0;
  16081. // Lights
  16082. /**
  16083. * is shadow enabled on this scene.
  16084. * @type {boolean}
  16085. */
  16086. this._shadowsEnabled = true;
  16087. /**
  16088. * is light enabled on this scene.
  16089. * @type {boolean}
  16090. */
  16091. this._lightsEnabled = true;
  16092. /**
  16093. * All of the lights added to this scene.
  16094. * @see BABYLON.Light
  16095. * @type {BABYLON.Light[]}
  16096. */
  16097. this.lights = new Array();
  16098. // Cameras
  16099. /** All of the cameras added to this scene. */
  16100. this.cameras = new Array();
  16101. /** All of the active cameras added to this scene. */
  16102. this.activeCameras = new Array();
  16103. // Meshes
  16104. /**
  16105. * All of the (abstract) meshes added to this scene.
  16106. * @see BABYLON.AbstractMesh
  16107. * @type {BABYLON.AbstractMesh[]}
  16108. */
  16109. this.meshes = new Array();
  16110. // Geometries
  16111. this._geometries = new Array();
  16112. this.materials = new Array();
  16113. this.multiMaterials = new Array();
  16114. // Textures
  16115. this._texturesEnabled = true;
  16116. this.textures = new Array();
  16117. // Particles
  16118. this.particlesEnabled = true;
  16119. this.particleSystems = new Array();
  16120. // Sprites
  16121. this.spritesEnabled = true;
  16122. this.spriteManagers = new Array();
  16123. // Layers
  16124. this.layers = new Array();
  16125. this.highlightLayers = new Array();
  16126. // Skeletons
  16127. this._skeletonsEnabled = true;
  16128. this.skeletons = new Array();
  16129. // Morph targets
  16130. this.morphTargetManagers = new Array();
  16131. // Lens flares
  16132. this.lensFlaresEnabled = true;
  16133. this.lensFlareSystems = new Array();
  16134. // Collisions
  16135. this.collisionsEnabled = true;
  16136. /** Defines the gravity applied to this scene */
  16137. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16138. // Postprocesses
  16139. this.postProcessesEnabled = true;
  16140. // Customs render targets
  16141. this.renderTargetsEnabled = true;
  16142. this.dumpNextRenderTargets = false;
  16143. this.customRenderTargets = new Array();
  16144. // Imported meshes
  16145. this.importedMeshesFiles = new Array();
  16146. // Probes
  16147. this.probesEnabled = true;
  16148. this.reflectionProbes = new Array();
  16149. this._actionManagers = new Array();
  16150. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16151. // Procedural textures
  16152. this.proceduralTexturesEnabled = true;
  16153. this._proceduralTextures = new Array();
  16154. this.soundTracks = new Array();
  16155. this._audioEnabled = true;
  16156. this._headphone = false;
  16157. // Performance counters
  16158. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16159. this._totalLightsCounter = new BABYLON.PerfCounter();
  16160. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16161. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16162. this._totalVertices = new BABYLON.PerfCounter();
  16163. this._activeIndices = new BABYLON.PerfCounter();
  16164. this._activeParticles = new BABYLON.PerfCounter();
  16165. this._lastFrameDuration = new BABYLON.PerfCounter();
  16166. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16167. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16168. this._particlesDuration = new BABYLON.PerfCounter();
  16169. this._renderDuration = new BABYLON.PerfCounter();
  16170. this._spritesDuration = new BABYLON.PerfCounter();
  16171. this._activeBones = new BABYLON.PerfCounter();
  16172. this._animationTime = 0;
  16173. this.animationTimeScale = 1;
  16174. this._renderId = 0;
  16175. this._executeWhenReadyTimeoutId = -1;
  16176. this._intermediateRendering = false;
  16177. this._viewUpdateFlag = -1;
  16178. this._projectionUpdateFlag = -1;
  16179. this._toBeDisposed = new BABYLON.SmartArray(256);
  16180. this._pendingData = []; //ANY
  16181. this._activeMeshes = new BABYLON.SmartArray(256);
  16182. this._processedMaterials = new BABYLON.SmartArray(256);
  16183. this._renderTargets = new BABYLON.SmartArray(256);
  16184. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16185. this._activeSkeletons = new BABYLON.SmartArray(32);
  16186. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16187. this._activeAnimatables = new Array();
  16188. this._transformMatrix = BABYLON.Matrix.Zero();
  16189. this.requireLightSorting = false;
  16190. this._uniqueIdCounter = 0;
  16191. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16192. this._engine.scenes.push(this);
  16193. this._uid = null;
  16194. this._renderingManager = new BABYLON.RenderingManager(this);
  16195. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16196. if (BABYLON.OutlineRenderer) {
  16197. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16198. }
  16199. this.attachControl();
  16200. if (BABYLON.SoundTrack) {
  16201. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16202. }
  16203. //simplification queue
  16204. if (BABYLON.SimplificationQueue) {
  16205. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16206. }
  16207. //collision coordinator initialization. For now legacy per default.
  16208. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16209. // Uniform Buffer
  16210. this._createUbo();
  16211. // Default Image processing definition.
  16212. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16213. }
  16214. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16215. /** The fog is deactivated */
  16216. get: function () {
  16217. return Scene._FOGMODE_NONE;
  16218. },
  16219. enumerable: true,
  16220. configurable: true
  16221. });
  16222. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16223. /** The fog density is following an exponential function */
  16224. get: function () {
  16225. return Scene._FOGMODE_EXP;
  16226. },
  16227. enumerable: true,
  16228. configurable: true
  16229. });
  16230. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16231. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16232. get: function () {
  16233. return Scene._FOGMODE_EXP2;
  16234. },
  16235. enumerable: true,
  16236. configurable: true
  16237. });
  16238. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16239. /** The fog density is following a linear function. */
  16240. get: function () {
  16241. return Scene._FOGMODE_LINEAR;
  16242. },
  16243. enumerable: true,
  16244. configurable: true
  16245. });
  16246. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16247. /**
  16248. * Texture used in all pbr material as the reflection texture.
  16249. * As in the majority of the scene they are the same (exception for multi room and so on),
  16250. * this is easier to reference from here than from all the materials.
  16251. */
  16252. get: function () {
  16253. return this._environmentTexture;
  16254. },
  16255. /**
  16256. * Texture used in all pbr material as the reflection texture.
  16257. * As in the majority of the scene they are the same (exception for multi room and so on),
  16258. * this is easier to set here than in all the materials.
  16259. */
  16260. set: function (value) {
  16261. this._environmentTexture = value;
  16262. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16263. },
  16264. enumerable: true,
  16265. configurable: true
  16266. });
  16267. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16268. /**
  16269. * Default image processing configuration used either in the rendering
  16270. * Forward main pass or through the imageProcessingPostProcess if present.
  16271. * As in the majority of the scene they are the same (exception for multi camera),
  16272. * this is easier to reference from here than from all the materials and post process.
  16273. *
  16274. * No setter as we it is a shared configuration, you can set the values instead.
  16275. */
  16276. get: function () {
  16277. return this._imageProcessingConfiguration;
  16278. },
  16279. enumerable: true,
  16280. configurable: true
  16281. });
  16282. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16283. get: function () {
  16284. return this._forcePointsCloud;
  16285. },
  16286. set: function (value) {
  16287. if (this._forcePointsCloud === value) {
  16288. return;
  16289. }
  16290. this._forcePointsCloud = value;
  16291. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16292. },
  16293. enumerable: true,
  16294. configurable: true
  16295. });
  16296. Object.defineProperty(Scene.prototype, "onDispose", {
  16297. /** A function to be executed when this scene is disposed. */
  16298. set: function (callback) {
  16299. if (this._onDisposeObserver) {
  16300. this.onDisposeObservable.remove(this._onDisposeObserver);
  16301. }
  16302. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16303. },
  16304. enumerable: true,
  16305. configurable: true
  16306. });
  16307. Object.defineProperty(Scene.prototype, "beforeRender", {
  16308. /** A function to be executed before rendering this scene */
  16309. set: function (callback) {
  16310. if (this._onBeforeRenderObserver) {
  16311. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16312. }
  16313. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16314. },
  16315. enumerable: true,
  16316. configurable: true
  16317. });
  16318. Object.defineProperty(Scene.prototype, "afterRender", {
  16319. /** A function to be executed after rendering this scene */
  16320. set: function (callback) {
  16321. if (this._onAfterRenderObserver) {
  16322. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16323. }
  16324. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16325. },
  16326. enumerable: true,
  16327. configurable: true
  16328. });
  16329. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16330. set: function (callback) {
  16331. if (this._onBeforeCameraRenderObserver) {
  16332. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16333. }
  16334. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16335. },
  16336. enumerable: true,
  16337. configurable: true
  16338. });
  16339. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16340. set: function (callback) {
  16341. if (this._onAfterCameraRenderObserver) {
  16342. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16343. }
  16344. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16345. },
  16346. enumerable: true,
  16347. configurable: true
  16348. });
  16349. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16350. get: function () {
  16351. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16352. },
  16353. enumerable: true,
  16354. configurable: true
  16355. });
  16356. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16357. get: function () {
  16358. return this._useRightHandedSystem;
  16359. },
  16360. set: function (value) {
  16361. if (this._useRightHandedSystem === value) {
  16362. return;
  16363. }
  16364. this._useRightHandedSystem = value;
  16365. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16366. },
  16367. enumerable: true,
  16368. configurable: true
  16369. });
  16370. Scene.prototype.setStepId = function (newStepId) {
  16371. this._currentStepId = newStepId;
  16372. };
  16373. ;
  16374. Scene.prototype.getStepId = function () {
  16375. return this._currentStepId;
  16376. };
  16377. ;
  16378. Scene.prototype.getInternalStep = function () {
  16379. return this._currentInternalStep;
  16380. };
  16381. ;
  16382. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16383. get: function () {
  16384. return this._fogEnabled;
  16385. },
  16386. /**
  16387. * is fog enabled on this scene.
  16388. */
  16389. set: function (value) {
  16390. if (this._fogEnabled === value) {
  16391. return;
  16392. }
  16393. this._fogEnabled = value;
  16394. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16395. },
  16396. enumerable: true,
  16397. configurable: true
  16398. });
  16399. Object.defineProperty(Scene.prototype, "fogMode", {
  16400. get: function () {
  16401. return this._fogMode;
  16402. },
  16403. set: function (value) {
  16404. if (this._fogMode === value) {
  16405. return;
  16406. }
  16407. this._fogMode = value;
  16408. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16409. },
  16410. enumerable: true,
  16411. configurable: true
  16412. });
  16413. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16414. get: function () {
  16415. return this._shadowsEnabled;
  16416. },
  16417. set: function (value) {
  16418. if (this._shadowsEnabled === value) {
  16419. return;
  16420. }
  16421. this._shadowsEnabled = value;
  16422. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16423. },
  16424. enumerable: true,
  16425. configurable: true
  16426. });
  16427. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16428. get: function () {
  16429. return this._lightsEnabled;
  16430. },
  16431. set: function (value) {
  16432. if (this._lightsEnabled === value) {
  16433. return;
  16434. }
  16435. this._lightsEnabled = value;
  16436. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16437. },
  16438. enumerable: true,
  16439. configurable: true
  16440. });
  16441. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16442. /** The default material used on meshes when no material is affected */
  16443. get: function () {
  16444. if (!this._defaultMaterial) {
  16445. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16446. }
  16447. return this._defaultMaterial;
  16448. },
  16449. /** The default material used on meshes when no material is affected */
  16450. set: function (value) {
  16451. this._defaultMaterial = value;
  16452. },
  16453. enumerable: true,
  16454. configurable: true
  16455. });
  16456. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16457. get: function () {
  16458. return this._texturesEnabled;
  16459. },
  16460. set: function (value) {
  16461. if (this._texturesEnabled === value) {
  16462. return;
  16463. }
  16464. this._texturesEnabled = value;
  16465. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16466. },
  16467. enumerable: true,
  16468. configurable: true
  16469. });
  16470. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16471. get: function () {
  16472. return this._skeletonsEnabled;
  16473. },
  16474. set: function (value) {
  16475. if (this._skeletonsEnabled === value) {
  16476. return;
  16477. }
  16478. this._skeletonsEnabled = value;
  16479. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16480. },
  16481. enumerable: true,
  16482. configurable: true
  16483. });
  16484. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16485. get: function () {
  16486. if (!this._postProcessRenderPipelineManager) {
  16487. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16488. }
  16489. return this._postProcessRenderPipelineManager;
  16490. },
  16491. enumerable: true,
  16492. configurable: true
  16493. });
  16494. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16495. get: function () {
  16496. return this._frustumPlanes;
  16497. },
  16498. enumerable: true,
  16499. configurable: true
  16500. });
  16501. Object.defineProperty(Scene.prototype, "debugLayer", {
  16502. // Properties
  16503. get: function () {
  16504. if (!this._debugLayer) {
  16505. this._debugLayer = new BABYLON.DebugLayer(this);
  16506. }
  16507. return this._debugLayer;
  16508. },
  16509. enumerable: true,
  16510. configurable: true
  16511. });
  16512. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16513. get: function () {
  16514. return this._workerCollisions;
  16515. },
  16516. set: function (enabled) {
  16517. if (!BABYLON.CollisionCoordinatorLegacy) {
  16518. return;
  16519. }
  16520. enabled = (enabled && !!Worker);
  16521. this._workerCollisions = enabled;
  16522. if (this.collisionCoordinator) {
  16523. this.collisionCoordinator.destroy();
  16524. }
  16525. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16526. this.collisionCoordinator.init(this);
  16527. },
  16528. enumerable: true,
  16529. configurable: true
  16530. });
  16531. Object.defineProperty(Scene.prototype, "selectionOctree", {
  16532. get: function () {
  16533. return this._selectionOctree;
  16534. },
  16535. enumerable: true,
  16536. configurable: true
  16537. });
  16538. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16539. /**
  16540. * The mesh that is currently under the pointer.
  16541. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16542. */
  16543. get: function () {
  16544. return this._pointerOverMesh;
  16545. },
  16546. enumerable: true,
  16547. configurable: true
  16548. });
  16549. Object.defineProperty(Scene.prototype, "pointerX", {
  16550. /**
  16551. * Current on-screen X position of the pointer
  16552. * @return {number} X position of the pointer
  16553. */
  16554. get: function () {
  16555. return this._pointerX;
  16556. },
  16557. enumerable: true,
  16558. configurable: true
  16559. });
  16560. Object.defineProperty(Scene.prototype, "pointerY", {
  16561. /**
  16562. * Current on-screen Y position of the pointer
  16563. * @return {number} Y position of the pointer
  16564. */
  16565. get: function () {
  16566. return this._pointerY;
  16567. },
  16568. enumerable: true,
  16569. configurable: true
  16570. });
  16571. Scene.prototype.getCachedMaterial = function () {
  16572. return this._cachedMaterial;
  16573. };
  16574. Scene.prototype.getCachedEffect = function () {
  16575. return this._cachedEffect;
  16576. };
  16577. Scene.prototype.getCachedVisibility = function () {
  16578. return this._cachedVisibility;
  16579. };
  16580. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  16581. if (visibility === void 0) { visibility = 1; }
  16582. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16583. };
  16584. Scene.prototype.getBoundingBoxRenderer = function () {
  16585. if (!this._boundingBoxRenderer) {
  16586. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16587. }
  16588. return this._boundingBoxRenderer;
  16589. };
  16590. Scene.prototype.getOutlineRenderer = function () {
  16591. return this._outlineRenderer;
  16592. };
  16593. Scene.prototype.getEngine = function () {
  16594. return this._engine;
  16595. };
  16596. Scene.prototype.getTotalVertices = function () {
  16597. return this._totalVertices.current;
  16598. };
  16599. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16600. get: function () {
  16601. return this._totalVertices;
  16602. },
  16603. enumerable: true,
  16604. configurable: true
  16605. });
  16606. Scene.prototype.getActiveIndices = function () {
  16607. return this._activeIndices.current;
  16608. };
  16609. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16610. get: function () {
  16611. return this._activeIndices;
  16612. },
  16613. enumerable: true,
  16614. configurable: true
  16615. });
  16616. Scene.prototype.getActiveParticles = function () {
  16617. return this._activeParticles.current;
  16618. };
  16619. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16620. get: function () {
  16621. return this._activeParticles;
  16622. },
  16623. enumerable: true,
  16624. configurable: true
  16625. });
  16626. Scene.prototype.getActiveBones = function () {
  16627. return this._activeBones.current;
  16628. };
  16629. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16630. get: function () {
  16631. return this._activeBones;
  16632. },
  16633. enumerable: true,
  16634. configurable: true
  16635. });
  16636. // Stats
  16637. Scene.prototype.getLastFrameDuration = function () {
  16638. return this._lastFrameDuration.current;
  16639. };
  16640. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16641. get: function () {
  16642. return this._lastFrameDuration;
  16643. },
  16644. enumerable: true,
  16645. configurable: true
  16646. });
  16647. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16648. return this._evaluateActiveMeshesDuration.current;
  16649. };
  16650. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16651. get: function () {
  16652. return this._evaluateActiveMeshesDuration;
  16653. },
  16654. enumerable: true,
  16655. configurable: true
  16656. });
  16657. Scene.prototype.getActiveMeshes = function () {
  16658. return this._activeMeshes;
  16659. };
  16660. Scene.prototype.getRenderTargetsDuration = function () {
  16661. return this._renderTargetsDuration.current;
  16662. };
  16663. Scene.prototype.getRenderDuration = function () {
  16664. return this._renderDuration.current;
  16665. };
  16666. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16667. get: function () {
  16668. return this._renderDuration;
  16669. },
  16670. enumerable: true,
  16671. configurable: true
  16672. });
  16673. Scene.prototype.getParticlesDuration = function () {
  16674. return this._particlesDuration.current;
  16675. };
  16676. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16677. get: function () {
  16678. return this._particlesDuration;
  16679. },
  16680. enumerable: true,
  16681. configurable: true
  16682. });
  16683. Scene.prototype.getSpritesDuration = function () {
  16684. return this._spritesDuration.current;
  16685. };
  16686. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16687. get: function () {
  16688. return this._spritesDuration;
  16689. },
  16690. enumerable: true,
  16691. configurable: true
  16692. });
  16693. Scene.prototype.getAnimationRatio = function () {
  16694. return this._animationRatio;
  16695. };
  16696. Scene.prototype.getRenderId = function () {
  16697. return this._renderId;
  16698. };
  16699. Scene.prototype.incrementRenderId = function () {
  16700. this._renderId++;
  16701. };
  16702. Scene.prototype._updatePointerPosition = function (evt) {
  16703. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16704. this._pointerX = evt.clientX - canvasRect.left;
  16705. this._pointerY = evt.clientY - canvasRect.top;
  16706. this._unTranslatedPointerX = this._pointerX;
  16707. this._unTranslatedPointerY = this._pointerY;
  16708. };
  16709. Scene.prototype._createUbo = function () {
  16710. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16711. this._sceneUbo.addUniform("viewProjection", 16);
  16712. this._sceneUbo.addUniform("view", 16);
  16713. };
  16714. // Pointers handling
  16715. /**
  16716. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16717. * @param attachUp defines if you want to attach events to pointerup
  16718. * @param attachDown defines if you want to attach events to pointerdown
  16719. * @param attachMove defines if you want to attach events to pointermove
  16720. */
  16721. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16722. var _this = this;
  16723. if (attachUp === void 0) { attachUp = true; }
  16724. if (attachDown === void 0) { attachDown = true; }
  16725. if (attachMove === void 0) { attachMove = true; }
  16726. this._initActionManager = function (act, clickInfo) {
  16727. if (!_this._meshPickProceed) {
  16728. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16729. _this._currentPickResult = pickResult;
  16730. if (pickResult) {
  16731. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16732. }
  16733. _this._meshPickProceed = true;
  16734. }
  16735. return act;
  16736. };
  16737. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16738. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16739. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16740. btn !== _this._previousButtonPressed) {
  16741. _this._doubleClickOccured = false;
  16742. clickInfo.singleClick = true;
  16743. clickInfo.ignore = false;
  16744. cb(clickInfo, _this._currentPickResult);
  16745. }
  16746. };
  16747. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16748. var clickInfo = new ClickInfo();
  16749. _this._currentPickResult = null;
  16750. var act;
  16751. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16752. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16753. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16754. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16755. act = _this._initActionManager(act, clickInfo);
  16756. if (act)
  16757. checkPicking = act.hasPickTriggers;
  16758. }
  16759. if (checkPicking) {
  16760. var btn = evt.button;
  16761. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16762. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16763. if (!clickInfo.hasSwiped) {
  16764. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16765. if (!checkSingleClickImmediately) {
  16766. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16767. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16768. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16769. act = _this._initActionManager(act, clickInfo);
  16770. if (act)
  16771. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16772. }
  16773. }
  16774. if (checkSingleClickImmediately) {
  16775. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16776. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16777. btn !== _this._previousButtonPressed) {
  16778. clickInfo.singleClick = true;
  16779. cb(clickInfo, _this._currentPickResult);
  16780. }
  16781. }
  16782. else {
  16783. // wait that no double click has been raised during the double click delay
  16784. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16785. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16786. }
  16787. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16788. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16789. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16790. act = _this._initActionManager(act, clickInfo);
  16791. if (act)
  16792. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16793. }
  16794. if (checkDoubleClick) {
  16795. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16796. if (btn === _this._previousButtonPressed &&
  16797. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16798. !_this._doubleClickOccured) {
  16799. // pointer has not moved for 2 clicks, it's a double click
  16800. if (!clickInfo.hasSwiped &&
  16801. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16802. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16803. _this._previousStartingPointerTime = 0;
  16804. _this._doubleClickOccured = true;
  16805. clickInfo.doubleClick = true;
  16806. clickInfo.ignore = false;
  16807. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16808. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16809. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16810. cb(clickInfo, _this._currentPickResult);
  16811. }
  16812. else {
  16813. _this._doubleClickOccured = false;
  16814. _this._previousStartingPointerTime = _this._startingPointerTime;
  16815. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16816. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16817. _this._previousButtonPressed = btn;
  16818. _this._previousHasSwiped = clickInfo.hasSwiped;
  16819. if (Scene.ExclusiveDoubleClickMode) {
  16820. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16821. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16822. }
  16823. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16824. cb(clickInfo, _this._previousPickResult);
  16825. }
  16826. else {
  16827. cb(clickInfo, _this._currentPickResult);
  16828. }
  16829. }
  16830. }
  16831. else {
  16832. _this._doubleClickOccured = false;
  16833. _this._previousStartingPointerTime = _this._startingPointerTime;
  16834. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16835. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16836. _this._previousButtonPressed = btn;
  16837. _this._previousHasSwiped = clickInfo.hasSwiped;
  16838. }
  16839. }
  16840. }
  16841. }
  16842. clickInfo.ignore = true;
  16843. cb(clickInfo, _this._currentPickResult);
  16844. };
  16845. var spritePredicate = function (sprite) {
  16846. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16847. };
  16848. this._onPointerMove = function (evt) {
  16849. _this._updatePointerPosition(evt);
  16850. // PreObservable support
  16851. if (_this.onPrePointerObservable.hasObservers()) {
  16852. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16853. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16854. _this.onPrePointerObservable.notifyObservers(pi, type);
  16855. if (pi.skipOnPointerObservable) {
  16856. return;
  16857. }
  16858. }
  16859. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16860. return;
  16861. }
  16862. var canvas = _this._engine.getRenderingCanvas();
  16863. if (!_this.pointerMovePredicate) {
  16864. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16865. }
  16866. // Meshes
  16867. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16868. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16869. _this.setPointerOverSprite(null);
  16870. _this.setPointerOverMesh(pickResult.pickedMesh);
  16871. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16872. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16873. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16874. }
  16875. else {
  16876. canvas.style.cursor = _this.hoverCursor;
  16877. }
  16878. }
  16879. else {
  16880. canvas.style.cursor = _this.defaultCursor;
  16881. }
  16882. }
  16883. else {
  16884. _this.setPointerOverMesh(null);
  16885. // Sprites
  16886. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16887. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16888. _this.setPointerOverSprite(pickResult.pickedSprite);
  16889. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16890. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16891. }
  16892. else {
  16893. canvas.style.cursor = _this.hoverCursor;
  16894. }
  16895. }
  16896. else {
  16897. _this.setPointerOverSprite(null);
  16898. // Restore pointer
  16899. canvas.style.cursor = _this.defaultCursor;
  16900. }
  16901. }
  16902. if (_this.onPointerMove) {
  16903. _this.onPointerMove(evt, pickResult);
  16904. }
  16905. if (_this.onPointerObservable.hasObservers()) {
  16906. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16907. var pi = new PointerInfo(type, evt, pickResult);
  16908. _this.onPointerObservable.notifyObservers(pi, type);
  16909. }
  16910. };
  16911. this._onPointerDown = function (evt) {
  16912. _this._isButtonPressed = true;
  16913. _this._pickedDownMesh = null;
  16914. _this._meshPickProceed = false;
  16915. _this._updatePointerPosition(evt);
  16916. // PreObservable support
  16917. if (_this.onPrePointerObservable.hasObservers()) {
  16918. var type = PointerEventTypes.POINTERDOWN;
  16919. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16920. _this.onPrePointerObservable.notifyObservers(pi, type);
  16921. if (pi.skipOnPointerObservable) {
  16922. return;
  16923. }
  16924. }
  16925. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16926. return;
  16927. }
  16928. _this._startingPointerPosition.x = _this._pointerX;
  16929. _this._startingPointerPosition.y = _this._pointerY;
  16930. _this._startingPointerTime = new Date().getTime();
  16931. if (!_this.pointerDownPredicate) {
  16932. _this.pointerDownPredicate = function (mesh) {
  16933. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16934. };
  16935. }
  16936. // Meshes
  16937. _this._pickedDownMesh = null;
  16938. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16939. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16940. _this._pickedDownMesh = pickResult.pickedMesh;
  16941. var actionManager = pickResult.pickedMesh.actionManager;
  16942. if (actionManager) {
  16943. if (actionManager.hasPickTriggers) {
  16944. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16945. switch (evt.button) {
  16946. case 0:
  16947. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16948. break;
  16949. case 1:
  16950. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16951. break;
  16952. case 2:
  16953. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16954. break;
  16955. }
  16956. }
  16957. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16958. window.setTimeout((function () {
  16959. var _this = this;
  16960. 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);
  16961. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16962. if (this._isButtonPressed &&
  16963. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16964. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16965. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16966. this._startingPointerTime = 0;
  16967. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16968. }
  16969. }
  16970. }).bind(_this), Scene.LongPressDelay);
  16971. }
  16972. }
  16973. }
  16974. if (_this.onPointerDown) {
  16975. _this.onPointerDown(evt, pickResult);
  16976. }
  16977. if (_this.onPointerObservable.hasObservers()) {
  16978. var type = PointerEventTypes.POINTERDOWN;
  16979. var pi = new PointerInfo(type, evt, pickResult);
  16980. _this.onPointerObservable.notifyObservers(pi, type);
  16981. }
  16982. // Sprites
  16983. _this._pickedDownSprite = null;
  16984. if (_this.spriteManagers.length > 0) {
  16985. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16986. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16987. if (pickResult.pickedSprite.actionManager) {
  16988. _this._pickedDownSprite = pickResult.pickedSprite;
  16989. switch (evt.button) {
  16990. case 0:
  16991. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16992. break;
  16993. case 1:
  16994. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16995. break;
  16996. case 2:
  16997. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16998. break;
  16999. }
  17000. if (pickResult.pickedSprite.actionManager) {
  17001. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17002. }
  17003. }
  17004. }
  17005. }
  17006. };
  17007. this._onPointerUp = function (evt) {
  17008. _this._isButtonPressed = false;
  17009. _this._pickedUpMesh = null;
  17010. _this._meshPickProceed = false;
  17011. _this._updatePointerPosition(evt);
  17012. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17013. // PreObservable support
  17014. if (this.onPrePointerObservable.hasObservers()) {
  17015. if (!clickInfo.ignore) {
  17016. if (!clickInfo.hasSwiped) {
  17017. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17018. var type = PointerEventTypes.POINTERTAP;
  17019. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17020. this.onPrePointerObservable.notifyObservers(pi, type);
  17021. if (pi.skipOnPointerObservable) {
  17022. return;
  17023. }
  17024. }
  17025. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17026. var type = PointerEventTypes.POINTERDOUBLETAP;
  17027. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17028. this.onPrePointerObservable.notifyObservers(pi, type);
  17029. if (pi.skipOnPointerObservable) {
  17030. return;
  17031. }
  17032. }
  17033. }
  17034. }
  17035. else {
  17036. var type = PointerEventTypes.POINTERUP;
  17037. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17038. this.onPrePointerObservable.notifyObservers(pi, type);
  17039. if (pi.skipOnPointerObservable) {
  17040. return;
  17041. }
  17042. }
  17043. }
  17044. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17045. return;
  17046. }
  17047. if (!this.pointerUpPredicate) {
  17048. this.pointerUpPredicate = function (mesh) {
  17049. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17050. };
  17051. }
  17052. // Meshes
  17053. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17054. this._initActionManager(null, clickInfo);
  17055. }
  17056. if (!pickResult) {
  17057. pickResult = this._currentPickResult;
  17058. }
  17059. if (pickResult && pickResult && pickResult.pickedMesh) {
  17060. this._pickedUpMesh = pickResult.pickedMesh;
  17061. if (this._pickedDownMesh === this._pickedUpMesh) {
  17062. if (this.onPointerPick) {
  17063. this.onPointerPick(evt, pickResult);
  17064. }
  17065. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17066. var type = PointerEventTypes.POINTERPICK;
  17067. var pi = new PointerInfo(type, evt, pickResult);
  17068. this.onPointerObservable.notifyObservers(pi, type);
  17069. }
  17070. }
  17071. if (pickResult.pickedMesh.actionManager) {
  17072. if (clickInfo.ignore) {
  17073. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17074. }
  17075. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17076. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17077. }
  17078. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17079. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17080. }
  17081. }
  17082. }
  17083. if (this._pickedDownMesh &&
  17084. this._pickedDownMesh.actionManager &&
  17085. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17086. this._pickedDownMesh !== this._pickedUpMesh) {
  17087. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17088. }
  17089. if (this.onPointerUp) {
  17090. this.onPointerUp(evt, pickResult);
  17091. }
  17092. if (this.onPointerObservable.hasObservers()) {
  17093. if (!clickInfo.ignore) {
  17094. if (!clickInfo.hasSwiped) {
  17095. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17096. var type = PointerEventTypes.POINTERTAP;
  17097. var pi = new PointerInfo(type, evt, pickResult);
  17098. this.onPointerObservable.notifyObservers(pi, type);
  17099. }
  17100. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17101. var type = PointerEventTypes.POINTERDOUBLETAP;
  17102. var pi = new PointerInfo(type, evt, pickResult);
  17103. this.onPointerObservable.notifyObservers(pi, type);
  17104. }
  17105. }
  17106. }
  17107. else {
  17108. var type = PointerEventTypes.POINTERUP;
  17109. var pi = new PointerInfo(type, evt, pickResult);
  17110. this.onPointerObservable.notifyObservers(pi, type);
  17111. }
  17112. }
  17113. // Sprites
  17114. if (this.spriteManagers.length > 0) {
  17115. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  17116. if (pickResult.hit && pickResult.pickedSprite) {
  17117. if (pickResult.pickedSprite.actionManager) {
  17118. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17119. if (pickResult.pickedSprite.actionManager) {
  17120. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17121. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17122. }
  17123. }
  17124. }
  17125. }
  17126. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17127. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17128. }
  17129. }
  17130. this._previousPickResult = this._currentPickResult;
  17131. }).bind(_this));
  17132. };
  17133. this._onKeyDown = function (evt) {
  17134. if (_this.actionManager) {
  17135. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17136. }
  17137. };
  17138. this._onKeyUp = function (evt) {
  17139. if (_this.actionManager) {
  17140. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17141. }
  17142. };
  17143. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17144. var canvas = this._engine.getRenderingCanvas();
  17145. if (attachMove) {
  17146. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17147. // Wheel
  17148. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17149. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17150. }
  17151. if (attachDown) {
  17152. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17153. }
  17154. if (attachUp) {
  17155. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17156. }
  17157. canvas.tabIndex = 1;
  17158. canvas.addEventListener("keydown", this._onKeyDown, false);
  17159. canvas.addEventListener("keyup", this._onKeyUp, false);
  17160. };
  17161. Scene.prototype.detachControl = function () {
  17162. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17163. var canvas = this._engine.getRenderingCanvas();
  17164. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17165. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17166. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17167. // Wheel
  17168. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17169. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17170. canvas.removeEventListener("keydown", this._onKeyDown);
  17171. canvas.removeEventListener("keyup", this._onKeyUp);
  17172. };
  17173. // Ready
  17174. Scene.prototype.isReady = function () {
  17175. if (this._pendingData.length > 0) {
  17176. return false;
  17177. }
  17178. var index;
  17179. // Geometries
  17180. for (index = 0; index < this._geometries.length; index++) {
  17181. var geometry = this._geometries[index];
  17182. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17183. return false;
  17184. }
  17185. }
  17186. // Meshes
  17187. for (index = 0; index < this.meshes.length; index++) {
  17188. var mesh = this.meshes[index];
  17189. if (!mesh.isEnabled()) {
  17190. continue;
  17191. }
  17192. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17193. continue;
  17194. }
  17195. if (!mesh.isReady()) {
  17196. return false;
  17197. }
  17198. var mat = mesh.material;
  17199. if (mat) {
  17200. if (!mat.isReady(mesh)) {
  17201. return false;
  17202. }
  17203. }
  17204. }
  17205. return true;
  17206. };
  17207. Scene.prototype.resetCachedMaterial = function () {
  17208. this._cachedMaterial = null;
  17209. this._cachedEffect = null;
  17210. this._cachedVisibility = null;
  17211. };
  17212. Scene.prototype.registerBeforeRender = function (func) {
  17213. this.onBeforeRenderObservable.add(func);
  17214. };
  17215. Scene.prototype.unregisterBeforeRender = function (func) {
  17216. this.onBeforeRenderObservable.removeCallback(func);
  17217. };
  17218. Scene.prototype.registerAfterRender = function (func) {
  17219. this.onAfterRenderObservable.add(func);
  17220. };
  17221. Scene.prototype.unregisterAfterRender = function (func) {
  17222. this.onAfterRenderObservable.removeCallback(func);
  17223. };
  17224. Scene.prototype._addPendingData = function (data) {
  17225. this._pendingData.push(data);
  17226. };
  17227. Scene.prototype._removePendingData = function (data) {
  17228. var index = this._pendingData.indexOf(data);
  17229. if (index !== -1) {
  17230. this._pendingData.splice(index, 1);
  17231. }
  17232. };
  17233. Scene.prototype.getWaitingItemsCount = function () {
  17234. return this._pendingData.length;
  17235. };
  17236. /**
  17237. * Registers a function to be executed when the scene is ready.
  17238. * @param {Function} func - the function to be executed.
  17239. */
  17240. Scene.prototype.executeWhenReady = function (func) {
  17241. var _this = this;
  17242. this.onReadyObservable.add(func);
  17243. if (this._executeWhenReadyTimeoutId !== -1) {
  17244. return;
  17245. }
  17246. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17247. _this._checkIsReady();
  17248. }, 150);
  17249. };
  17250. Scene.prototype._checkIsReady = function () {
  17251. var _this = this;
  17252. if (this.isReady()) {
  17253. this.onReadyObservable.notifyObservers(this);
  17254. this.onReadyObservable.clear();
  17255. this._executeWhenReadyTimeoutId = -1;
  17256. return;
  17257. }
  17258. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17259. _this._checkIsReady();
  17260. }, 150);
  17261. };
  17262. // Animations
  17263. /**
  17264. * Will start the animation sequence of a given target
  17265. * @param target - the target
  17266. * @param {number} from - from which frame should animation start
  17267. * @param {number} to - till which frame should animation run.
  17268. * @param {boolean} [loop] - should the animation loop
  17269. * @param {number} [speedRatio] - the speed in which to run the animation
  17270. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17271. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17272. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17273. * See BABYLON.Animatable
  17274. */
  17275. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17276. if (speedRatio === void 0) { speedRatio = 1.0; }
  17277. if (from > to && speedRatio > 0) {
  17278. speedRatio *= -1;
  17279. }
  17280. this.stopAnimation(target);
  17281. if (!animatable) {
  17282. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17283. }
  17284. // Local animations
  17285. if (target.animations) {
  17286. animatable.appendAnimations(target, target.animations);
  17287. }
  17288. // Children animations
  17289. if (target.getAnimatables) {
  17290. var animatables = target.getAnimatables();
  17291. for (var index = 0; index < animatables.length; index++) {
  17292. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17293. }
  17294. }
  17295. animatable.reset();
  17296. return animatable;
  17297. };
  17298. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17299. if (speedRatio === undefined) {
  17300. speedRatio = 1.0;
  17301. }
  17302. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17303. return animatable;
  17304. };
  17305. Scene.prototype.getAnimatableByTarget = function (target) {
  17306. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17307. if (this._activeAnimatables[index].target === target) {
  17308. return this._activeAnimatables[index];
  17309. }
  17310. }
  17311. return null;
  17312. };
  17313. Object.defineProperty(Scene.prototype, "Animatables", {
  17314. get: function () {
  17315. return this._activeAnimatables;
  17316. },
  17317. enumerable: true,
  17318. configurable: true
  17319. });
  17320. /**
  17321. * Will stop the animation of the given target
  17322. * @param target - the target
  17323. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17324. * @see beginAnimation
  17325. */
  17326. Scene.prototype.stopAnimation = function (target, animationName) {
  17327. var animatable = this.getAnimatableByTarget(target);
  17328. if (animatable) {
  17329. animatable.stop(animationName);
  17330. }
  17331. };
  17332. Scene.prototype._animate = function () {
  17333. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17334. return;
  17335. }
  17336. // Getting time
  17337. var now = BABYLON.Tools.Now;
  17338. if (!this._animationTimeLast) {
  17339. if (this._pendingData.length > 0) {
  17340. return;
  17341. }
  17342. this._animationTimeLast = now;
  17343. }
  17344. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17345. this._animationTime += deltaTime;
  17346. this._animationTimeLast = now;
  17347. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17348. this._activeAnimatables[index]._animate(this._animationTime);
  17349. }
  17350. };
  17351. // Matrix
  17352. Scene.prototype.getViewMatrix = function () {
  17353. return this._viewMatrix;
  17354. };
  17355. Scene.prototype.getProjectionMatrix = function () {
  17356. return this._projectionMatrix;
  17357. };
  17358. Scene.prototype.getTransformMatrix = function () {
  17359. return this._transformMatrix;
  17360. };
  17361. Scene.prototype.setTransformMatrix = function (view, projection) {
  17362. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17363. return;
  17364. }
  17365. this._viewUpdateFlag = view.updateFlag;
  17366. this._projectionUpdateFlag = projection.updateFlag;
  17367. this._viewMatrix = view;
  17368. this._projectionMatrix = projection;
  17369. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17370. // Update frustum
  17371. if (!this._frustumPlanes) {
  17372. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17373. }
  17374. else {
  17375. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17376. }
  17377. if (this._sceneUbo.useUbo) {
  17378. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17379. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17380. this._sceneUbo.update();
  17381. }
  17382. };
  17383. Scene.prototype.getSceneUniformBuffer = function () {
  17384. return this._sceneUbo;
  17385. };
  17386. // Methods
  17387. Scene.prototype.getUniqueId = function () {
  17388. var result = this._uniqueIdCounter;
  17389. this._uniqueIdCounter++;
  17390. return result;
  17391. };
  17392. Scene.prototype.addMesh = function (newMesh) {
  17393. newMesh.uniqueId = this.getUniqueId();
  17394. var position = this.meshes.push(newMesh);
  17395. //notify the collision coordinator
  17396. if (this.collisionCoordinator) {
  17397. this.collisionCoordinator.onMeshAdded(newMesh);
  17398. }
  17399. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17400. };
  17401. Scene.prototype.removeMesh = function (toRemove) {
  17402. var index = this.meshes.indexOf(toRemove);
  17403. if (index !== -1) {
  17404. // Remove from the scene if mesh found
  17405. this.meshes.splice(index, 1);
  17406. }
  17407. //notify the collision coordinator
  17408. if (this.collisionCoordinator) {
  17409. this.collisionCoordinator.onMeshRemoved(toRemove);
  17410. }
  17411. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17412. return index;
  17413. };
  17414. Scene.prototype.removeSkeleton = function (toRemove) {
  17415. var index = this.skeletons.indexOf(toRemove);
  17416. if (index !== -1) {
  17417. // Remove from the scene if found
  17418. this.skeletons.splice(index, 1);
  17419. }
  17420. return index;
  17421. };
  17422. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17423. var index = this.morphTargetManagers.indexOf(toRemove);
  17424. if (index !== -1) {
  17425. // Remove from the scene if found
  17426. this.morphTargetManagers.splice(index, 1);
  17427. }
  17428. return index;
  17429. };
  17430. Scene.prototype.removeLight = function (toRemove) {
  17431. var index = this.lights.indexOf(toRemove);
  17432. if (index !== -1) {
  17433. // Remove from the scene if mesh found
  17434. this.lights.splice(index, 1);
  17435. this.sortLightsByPriority();
  17436. }
  17437. this.onLightRemovedObservable.notifyObservers(toRemove);
  17438. return index;
  17439. };
  17440. Scene.prototype.removeCamera = function (toRemove) {
  17441. var index = this.cameras.indexOf(toRemove);
  17442. if (index !== -1) {
  17443. // Remove from the scene if mesh found
  17444. this.cameras.splice(index, 1);
  17445. }
  17446. // Remove from activeCameras
  17447. var index2 = this.activeCameras.indexOf(toRemove);
  17448. if (index2 !== -1) {
  17449. // Remove from the scene if mesh found
  17450. this.activeCameras.splice(index2, 1);
  17451. }
  17452. // Reset the activeCamera
  17453. if (this.activeCamera === toRemove) {
  17454. if (this.cameras.length > 0) {
  17455. this.activeCamera = this.cameras[0];
  17456. }
  17457. else {
  17458. this.activeCamera = null;
  17459. }
  17460. }
  17461. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17462. return index;
  17463. };
  17464. Scene.prototype.addLight = function (newLight) {
  17465. newLight.uniqueId = this.getUniqueId();
  17466. this.lights.push(newLight);
  17467. this.sortLightsByPriority();
  17468. this.onNewLightAddedObservable.notifyObservers(newLight);
  17469. };
  17470. Scene.prototype.sortLightsByPriority = function () {
  17471. if (this.requireLightSorting) {
  17472. this.lights.sort(BABYLON.Light.compareLightsPriority);
  17473. }
  17474. };
  17475. Scene.prototype.addCamera = function (newCamera) {
  17476. newCamera.uniqueId = this.getUniqueId();
  17477. var position = this.cameras.push(newCamera);
  17478. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17479. };
  17480. /**
  17481. * Switch active camera
  17482. * @param {Camera} newCamera - new active camera
  17483. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17484. */
  17485. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17486. if (attachControl === void 0) { attachControl = true; }
  17487. var canvas = this._engine.getRenderingCanvas();
  17488. this.activeCamera.detachControl(canvas);
  17489. this.activeCamera = newCamera;
  17490. if (attachControl) {
  17491. newCamera.attachControl(canvas);
  17492. }
  17493. };
  17494. /**
  17495. * sets the active camera of the scene using its ID
  17496. * @param {string} id - the camera's ID
  17497. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17498. * @see activeCamera
  17499. */
  17500. Scene.prototype.setActiveCameraByID = function (id) {
  17501. var camera = this.getCameraByID(id);
  17502. if (camera) {
  17503. this.activeCamera = camera;
  17504. return camera;
  17505. }
  17506. return null;
  17507. };
  17508. /**
  17509. * sets the active camera of the scene using its name
  17510. * @param {string} name - the camera's name
  17511. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17512. * @see activeCamera
  17513. */
  17514. Scene.prototype.setActiveCameraByName = function (name) {
  17515. var camera = this.getCameraByName(name);
  17516. if (camera) {
  17517. this.activeCamera = camera;
  17518. return camera;
  17519. }
  17520. return null;
  17521. };
  17522. /**
  17523. * get a material using its id
  17524. * @param {string} the material's ID
  17525. * @return {BABYLON.Material|null} the material or null if none found.
  17526. */
  17527. Scene.prototype.getMaterialByID = function (id) {
  17528. for (var index = 0; index < this.materials.length; index++) {
  17529. if (this.materials[index].id === id) {
  17530. return this.materials[index];
  17531. }
  17532. }
  17533. return null;
  17534. };
  17535. /**
  17536. * get a material using its name
  17537. * @param {string} the material's name
  17538. * @return {BABYLON.Material|null} the material or null if none found.
  17539. */
  17540. Scene.prototype.getMaterialByName = function (name) {
  17541. for (var index = 0; index < this.materials.length; index++) {
  17542. if (this.materials[index].name === name) {
  17543. return this.materials[index];
  17544. }
  17545. }
  17546. return null;
  17547. };
  17548. Scene.prototype.getLensFlareSystemByName = function (name) {
  17549. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17550. if (this.lensFlareSystems[index].name === name) {
  17551. return this.lensFlareSystems[index];
  17552. }
  17553. }
  17554. return null;
  17555. };
  17556. Scene.prototype.getLensFlareSystemByID = function (id) {
  17557. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17558. if (this.lensFlareSystems[index].id === id) {
  17559. return this.lensFlareSystems[index];
  17560. }
  17561. }
  17562. return null;
  17563. };
  17564. Scene.prototype.getCameraByID = function (id) {
  17565. for (var index = 0; index < this.cameras.length; index++) {
  17566. if (this.cameras[index].id === id) {
  17567. return this.cameras[index];
  17568. }
  17569. }
  17570. return null;
  17571. };
  17572. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17573. for (var index = 0; index < this.cameras.length; index++) {
  17574. if (this.cameras[index].uniqueId === uniqueId) {
  17575. return this.cameras[index];
  17576. }
  17577. }
  17578. return null;
  17579. };
  17580. /**
  17581. * get a camera using its name
  17582. * @param {string} the camera's name
  17583. * @return {BABYLON.Camera|null} the camera or null if none found.
  17584. */
  17585. Scene.prototype.getCameraByName = function (name) {
  17586. for (var index = 0; index < this.cameras.length; index++) {
  17587. if (this.cameras[index].name === name) {
  17588. return this.cameras[index];
  17589. }
  17590. }
  17591. return null;
  17592. };
  17593. /**
  17594. * get a bone using its id
  17595. * @param {string} the bone's id
  17596. * @return {BABYLON.Bone|null} the bone or null if not found
  17597. */
  17598. Scene.prototype.getBoneByID = function (id) {
  17599. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17600. var skeleton = this.skeletons[skeletonIndex];
  17601. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17602. if (skeleton.bones[boneIndex].id === id) {
  17603. return skeleton.bones[boneIndex];
  17604. }
  17605. }
  17606. }
  17607. return null;
  17608. };
  17609. /**
  17610. * get a bone using its id
  17611. * @param {string} the bone's name
  17612. * @return {BABYLON.Bone|null} the bone or null if not found
  17613. */
  17614. Scene.prototype.getBoneByName = function (name) {
  17615. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17616. var skeleton = this.skeletons[skeletonIndex];
  17617. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17618. if (skeleton.bones[boneIndex].name === name) {
  17619. return skeleton.bones[boneIndex];
  17620. }
  17621. }
  17622. }
  17623. return null;
  17624. };
  17625. /**
  17626. * get a light node using its name
  17627. * @param {string} the light's name
  17628. * @return {BABYLON.Light|null} the light or null if none found.
  17629. */
  17630. Scene.prototype.getLightByName = function (name) {
  17631. for (var index = 0; index < this.lights.length; index++) {
  17632. if (this.lights[index].name === name) {
  17633. return this.lights[index];
  17634. }
  17635. }
  17636. return null;
  17637. };
  17638. /**
  17639. * get a light node using its ID
  17640. * @param {string} the light's id
  17641. * @return {BABYLON.Light|null} the light or null if none found.
  17642. */
  17643. Scene.prototype.getLightByID = function (id) {
  17644. for (var index = 0; index < this.lights.length; index++) {
  17645. if (this.lights[index].id === id) {
  17646. return this.lights[index];
  17647. }
  17648. }
  17649. return null;
  17650. };
  17651. /**
  17652. * get a light node using its scene-generated unique ID
  17653. * @param {number} the light's unique id
  17654. * @return {BABYLON.Light|null} the light or null if none found.
  17655. */
  17656. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17657. for (var index = 0; index < this.lights.length; index++) {
  17658. if (this.lights[index].uniqueId === uniqueId) {
  17659. return this.lights[index];
  17660. }
  17661. }
  17662. return null;
  17663. };
  17664. /**
  17665. * get a particle system by id
  17666. * @param id {number} the particle system id
  17667. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  17668. */
  17669. Scene.prototype.getParticleSystemByID = function (id) {
  17670. for (var index = 0; index < this.particleSystems.length; index++) {
  17671. if (this.particleSystems[index].id === id) {
  17672. return this.particleSystems[index];
  17673. }
  17674. }
  17675. return null;
  17676. };
  17677. /**
  17678. * get a geometry using its ID
  17679. * @param {string} the geometry's id
  17680. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17681. */
  17682. Scene.prototype.getGeometryByID = function (id) {
  17683. for (var index = 0; index < this._geometries.length; index++) {
  17684. if (this._geometries[index].id === id) {
  17685. return this._geometries[index];
  17686. }
  17687. }
  17688. return null;
  17689. };
  17690. /**
  17691. * add a new geometry to this scene.
  17692. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17693. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17694. * @return {boolean} was the geometry added or not
  17695. */
  17696. Scene.prototype.pushGeometry = function (geometry, force) {
  17697. if (!force && this.getGeometryByID(geometry.id)) {
  17698. return false;
  17699. }
  17700. this._geometries.push(geometry);
  17701. //notify the collision coordinator
  17702. if (this.collisionCoordinator) {
  17703. this.collisionCoordinator.onGeometryAdded(geometry);
  17704. }
  17705. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17706. return true;
  17707. };
  17708. /**
  17709. * Removes an existing geometry
  17710. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17711. * @return {boolean} was the geometry removed or not
  17712. */
  17713. Scene.prototype.removeGeometry = function (geometry) {
  17714. var index = this._geometries.indexOf(geometry);
  17715. if (index > -1) {
  17716. this._geometries.splice(index, 1);
  17717. //notify the collision coordinator
  17718. if (this.collisionCoordinator) {
  17719. this.collisionCoordinator.onGeometryDeleted(geometry);
  17720. }
  17721. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17722. return true;
  17723. }
  17724. return false;
  17725. };
  17726. Scene.prototype.getGeometries = function () {
  17727. return this._geometries;
  17728. };
  17729. /**
  17730. * Get the first added mesh found of a given ID
  17731. * @param {string} id - the id to search for
  17732. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17733. */
  17734. Scene.prototype.getMeshByID = function (id) {
  17735. for (var index = 0; index < this.meshes.length; index++) {
  17736. if (this.meshes[index].id === id) {
  17737. return this.meshes[index];
  17738. }
  17739. }
  17740. return null;
  17741. };
  17742. Scene.prototype.getMeshesByID = function (id) {
  17743. return this.meshes.filter(function (m) {
  17744. return m.id === id;
  17745. });
  17746. };
  17747. /**
  17748. * Get a mesh with its auto-generated unique id
  17749. * @param {number} uniqueId - the unique id to search for
  17750. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17751. */
  17752. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17753. for (var index = 0; index < this.meshes.length; index++) {
  17754. if (this.meshes[index].uniqueId === uniqueId) {
  17755. return this.meshes[index];
  17756. }
  17757. }
  17758. return null;
  17759. };
  17760. /**
  17761. * Get a the last added mesh found of a given ID
  17762. * @param {string} id - the id to search for
  17763. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17764. */
  17765. Scene.prototype.getLastMeshByID = function (id) {
  17766. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17767. if (this.meshes[index].id === id) {
  17768. return this.meshes[index];
  17769. }
  17770. }
  17771. return null;
  17772. };
  17773. /**
  17774. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17775. * @param {string} id - the id to search for
  17776. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17777. */
  17778. Scene.prototype.getLastEntryByID = function (id) {
  17779. var index;
  17780. for (index = this.meshes.length - 1; index >= 0; index--) {
  17781. if (this.meshes[index].id === id) {
  17782. return this.meshes[index];
  17783. }
  17784. }
  17785. for (index = this.cameras.length - 1; index >= 0; index--) {
  17786. if (this.cameras[index].id === id) {
  17787. return this.cameras[index];
  17788. }
  17789. }
  17790. for (index = this.lights.length - 1; index >= 0; index--) {
  17791. if (this.lights[index].id === id) {
  17792. return this.lights[index];
  17793. }
  17794. }
  17795. return null;
  17796. };
  17797. Scene.prototype.getNodeByID = function (id) {
  17798. var mesh = this.getMeshByID(id);
  17799. if (mesh) {
  17800. return mesh;
  17801. }
  17802. var light = this.getLightByID(id);
  17803. if (light) {
  17804. return light;
  17805. }
  17806. var camera = this.getCameraByID(id);
  17807. if (camera) {
  17808. return camera;
  17809. }
  17810. var bone = this.getBoneByID(id);
  17811. return bone;
  17812. };
  17813. Scene.prototype.getNodeByName = function (name) {
  17814. var mesh = this.getMeshByName(name);
  17815. if (mesh) {
  17816. return mesh;
  17817. }
  17818. var light = this.getLightByName(name);
  17819. if (light) {
  17820. return light;
  17821. }
  17822. var camera = this.getCameraByName(name);
  17823. if (camera) {
  17824. return camera;
  17825. }
  17826. var bone = this.getBoneByName(name);
  17827. return bone;
  17828. };
  17829. Scene.prototype.getMeshByName = function (name) {
  17830. for (var index = 0; index < this.meshes.length; index++) {
  17831. if (this.meshes[index].name === name) {
  17832. return this.meshes[index];
  17833. }
  17834. }
  17835. return null;
  17836. };
  17837. Scene.prototype.getSoundByName = function (name) {
  17838. var index;
  17839. if (BABYLON.AudioEngine) {
  17840. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17841. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17842. return this.mainSoundTrack.soundCollection[index];
  17843. }
  17844. }
  17845. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17846. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17847. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17848. return this.soundTracks[sdIndex].soundCollection[index];
  17849. }
  17850. }
  17851. }
  17852. }
  17853. return null;
  17854. };
  17855. Scene.prototype.getLastSkeletonByID = function (id) {
  17856. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17857. if (this.skeletons[index].id === id) {
  17858. return this.skeletons[index];
  17859. }
  17860. }
  17861. return null;
  17862. };
  17863. Scene.prototype.getSkeletonById = function (id) {
  17864. for (var index = 0; index < this.skeletons.length; index++) {
  17865. if (this.skeletons[index].id === id) {
  17866. return this.skeletons[index];
  17867. }
  17868. }
  17869. return null;
  17870. };
  17871. Scene.prototype.getSkeletonByName = function (name) {
  17872. for (var index = 0; index < this.skeletons.length; index++) {
  17873. if (this.skeletons[index].name === name) {
  17874. return this.skeletons[index];
  17875. }
  17876. }
  17877. return null;
  17878. };
  17879. Scene.prototype.getMorphTargetManagerById = function (id) {
  17880. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17881. if (this.morphTargetManagers[index].uniqueId === id) {
  17882. return this.morphTargetManagers[index];
  17883. }
  17884. }
  17885. return null;
  17886. };
  17887. Scene.prototype.isActiveMesh = function (mesh) {
  17888. return (this._activeMeshes.indexOf(mesh) !== -1);
  17889. };
  17890. /**
  17891. * Return a the first highlight layer of the scene with a given name.
  17892. * @param name The name of the highlight layer to look for.
  17893. * @return The highlight layer if found otherwise null.
  17894. */
  17895. Scene.prototype.getHighlightLayerByName = function (name) {
  17896. for (var index = 0; index < this.highlightLayers.length; index++) {
  17897. if (this.highlightLayers[index].name === name) {
  17898. return this.highlightLayers[index];
  17899. }
  17900. }
  17901. return null;
  17902. };
  17903. Object.defineProperty(Scene.prototype, "uid", {
  17904. /**
  17905. * Return a unique id as a string which can serve as an identifier for the scene
  17906. */
  17907. get: function () {
  17908. if (!this._uid) {
  17909. this._uid = BABYLON.Tools.RandomId();
  17910. }
  17911. return this._uid;
  17912. },
  17913. enumerable: true,
  17914. configurable: true
  17915. });
  17916. /**
  17917. * Add an externaly attached data from its key.
  17918. * This method call will fail and return false, if such key already exists.
  17919. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17920. * @param key the unique key that identifies the data
  17921. * @param data the data object to associate to the key for this Engine instance
  17922. * @return true if no such key were already present and the data was added successfully, false otherwise
  17923. */
  17924. Scene.prototype.addExternalData = function (key, data) {
  17925. if (!this._externalData) {
  17926. this._externalData = new BABYLON.StringDictionary();
  17927. }
  17928. return this._externalData.add(key, data);
  17929. };
  17930. /**
  17931. * Get an externaly attached data from its key
  17932. * @param key the unique key that identifies the data
  17933. * @return the associated data, if present (can be null), or undefined if not present
  17934. */
  17935. Scene.prototype.getExternalData = function (key) {
  17936. if (!this._externalData) {
  17937. return null;
  17938. }
  17939. return this._externalData.get(key);
  17940. };
  17941. /**
  17942. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17943. * @param key the unique key that identifies the data
  17944. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17945. * @return the associated data, can be null if the factory returned null.
  17946. */
  17947. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17948. if (!this._externalData) {
  17949. this._externalData = new BABYLON.StringDictionary();
  17950. }
  17951. return this._externalData.getOrAddWithFactory(key, factory);
  17952. };
  17953. /**
  17954. * Remove an externaly attached data from the Engine instance
  17955. * @param key the unique key that identifies the data
  17956. * @return true if the data was successfully removed, false if it doesn't exist
  17957. */
  17958. Scene.prototype.removeExternalData = function (key) {
  17959. return this._externalData.remove(key);
  17960. };
  17961. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17962. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17963. var material = subMesh.getMaterial();
  17964. if (mesh.showSubMeshesBoundingBox) {
  17965. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17966. }
  17967. if (material) {
  17968. // Render targets
  17969. if (material.getRenderTargetTextures) {
  17970. if (this._processedMaterials.indexOf(material) === -1) {
  17971. this._processedMaterials.push(material);
  17972. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17973. }
  17974. }
  17975. // Dispatch
  17976. this._activeIndices.addCount(subMesh.indexCount, false);
  17977. this._renderingManager.dispatch(subMesh);
  17978. }
  17979. }
  17980. };
  17981. Scene.prototype._isInIntermediateRendering = function () {
  17982. return this._intermediateRendering;
  17983. };
  17984. Scene.prototype._evaluateActiveMeshes = function () {
  17985. this.activeCamera._activeMeshes.reset();
  17986. this._activeMeshes.reset();
  17987. this._renderingManager.reset();
  17988. this._processedMaterials.reset();
  17989. this._activeParticleSystems.reset();
  17990. this._activeSkeletons.reset();
  17991. this._softwareSkinnedMeshes.reset();
  17992. if (this._boundingBoxRenderer) {
  17993. this._boundingBoxRenderer.reset();
  17994. }
  17995. // Meshes
  17996. var meshes;
  17997. var len;
  17998. if (this._selectionOctree) {
  17999. var selection = this._selectionOctree.select(this._frustumPlanes);
  18000. meshes = selection.data;
  18001. len = selection.length;
  18002. }
  18003. else {
  18004. len = this.meshes.length;
  18005. meshes = this.meshes;
  18006. }
  18007. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18008. var mesh = meshes[meshIndex];
  18009. if (mesh.isBlocked) {
  18010. continue;
  18011. }
  18012. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18013. if (!mesh.isReady() || !mesh.isEnabled()) {
  18014. continue;
  18015. }
  18016. mesh.computeWorldMatrix();
  18017. // Intersections
  18018. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18019. this._meshesForIntersections.pushNoDuplicate(mesh);
  18020. }
  18021. // Switch to current LOD
  18022. var meshLOD = mesh.getLOD(this.activeCamera);
  18023. if (!meshLOD) {
  18024. continue;
  18025. }
  18026. mesh._preActivate();
  18027. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18028. this._activeMeshes.push(mesh);
  18029. this.activeCamera._activeMeshes.push(mesh);
  18030. mesh._activate(this._renderId);
  18031. if (meshLOD !== mesh) {
  18032. meshLOD._activate(this._renderId);
  18033. }
  18034. this._activeMesh(mesh, meshLOD);
  18035. }
  18036. }
  18037. // Particle systems
  18038. this._particlesDuration.beginMonitoring();
  18039. var beforeParticlesDate = BABYLON.Tools.Now;
  18040. if (this.particlesEnabled) {
  18041. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18042. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18043. var particleSystem = this.particleSystems[particleIndex];
  18044. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18045. continue;
  18046. }
  18047. var emitter = particleSystem.emitter;
  18048. if (!emitter.position || emitter.isEnabled()) {
  18049. this._activeParticleSystems.push(particleSystem);
  18050. particleSystem.animate();
  18051. this._renderingManager.dispatchParticles(particleSystem);
  18052. }
  18053. }
  18054. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18055. }
  18056. this._particlesDuration.endMonitoring(false);
  18057. };
  18058. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18059. if (mesh.skeleton && this.skeletonsEnabled) {
  18060. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18061. mesh.skeleton.prepare();
  18062. }
  18063. if (!mesh.computeBonesUsingShaders) {
  18064. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18065. }
  18066. }
  18067. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18068. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18069. }
  18070. if (mesh && mesh.subMeshes) {
  18071. // Submeshes Octrees
  18072. var len;
  18073. var subMeshes;
  18074. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18075. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18076. len = intersections.length;
  18077. subMeshes = intersections.data;
  18078. }
  18079. else {
  18080. subMeshes = mesh.subMeshes;
  18081. len = subMeshes.length;
  18082. }
  18083. for (var subIndex = 0; subIndex < len; subIndex++) {
  18084. var subMesh = subMeshes[subIndex];
  18085. this._evaluateSubMesh(subMesh, mesh);
  18086. }
  18087. }
  18088. };
  18089. Scene.prototype.updateTransformMatrix = function (force) {
  18090. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18091. };
  18092. Scene.prototype._renderForCamera = function (camera) {
  18093. var engine = this._engine;
  18094. var startTime = BABYLON.Tools.Now;
  18095. this.activeCamera = camera;
  18096. if (!this.activeCamera)
  18097. throw new Error("Active camera not set");
  18098. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18099. // Viewport
  18100. engine.setViewport(this.activeCamera.viewport);
  18101. // Camera
  18102. this.resetCachedMaterial();
  18103. this._renderId++;
  18104. this.updateTransformMatrix();
  18105. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18106. // Meshes
  18107. this._evaluateActiveMeshesDuration.beginMonitoring();
  18108. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18109. this._evaluateActiveMeshes();
  18110. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18111. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18112. // Software skinning
  18113. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18114. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18115. mesh.applySkeleton(mesh.skeleton);
  18116. }
  18117. // Render targets
  18118. this._renderTargetsDuration.beginMonitoring();
  18119. var needsRestoreFrameBuffer = false;
  18120. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18121. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18122. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18123. }
  18124. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18125. this._intermediateRendering = true;
  18126. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18127. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18128. var renderTarget = this._renderTargets.data[renderIndex];
  18129. if (renderTarget._shouldRender()) {
  18130. this._renderId++;
  18131. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18132. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18133. }
  18134. }
  18135. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18136. this._intermediateRendering = false;
  18137. this._renderId++;
  18138. needsRestoreFrameBuffer = true; // Restore back buffer
  18139. }
  18140. // Render HighlightLayer Texture
  18141. var stencilState = this._engine.getStencilBuffer();
  18142. var renderhighlights = false;
  18143. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18144. this._intermediateRendering = true;
  18145. for (var i = 0; i < this.highlightLayers.length; i++) {
  18146. var highlightLayer = this.highlightLayers[i];
  18147. if (highlightLayer.shouldRender() &&
  18148. (!highlightLayer.camera ||
  18149. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18150. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18151. renderhighlights = true;
  18152. var renderTarget = highlightLayer._mainTexture;
  18153. if (renderTarget._shouldRender()) {
  18154. this._renderId++;
  18155. renderTarget.render(false, false);
  18156. needsRestoreFrameBuffer = true;
  18157. }
  18158. }
  18159. }
  18160. this._intermediateRendering = false;
  18161. this._renderId++;
  18162. }
  18163. if (needsRestoreFrameBuffer) {
  18164. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18165. }
  18166. this._renderTargetsDuration.endMonitoring(false);
  18167. // Prepare Frame
  18168. this.postProcessManager._prepareFrame();
  18169. this._renderDuration.beginMonitoring();
  18170. // Backgrounds
  18171. var layerIndex;
  18172. var layer;
  18173. if (this.layers.length) {
  18174. engine.setDepthBuffer(false);
  18175. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18176. layer = this.layers[layerIndex];
  18177. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18178. layer.render();
  18179. }
  18180. }
  18181. engine.setDepthBuffer(true);
  18182. }
  18183. // Render
  18184. BABYLON.Tools.StartPerformanceCounter("Main render");
  18185. // Activate HighlightLayer stencil
  18186. if (renderhighlights) {
  18187. this._engine.setStencilBuffer(true);
  18188. }
  18189. this._renderingManager.render(null, null, true, true);
  18190. // Restore HighlightLayer stencil
  18191. if (renderhighlights) {
  18192. this._engine.setStencilBuffer(stencilState);
  18193. }
  18194. BABYLON.Tools.EndPerformanceCounter("Main render");
  18195. // Bounding boxes
  18196. if (this._boundingBoxRenderer) {
  18197. this._boundingBoxRenderer.render();
  18198. }
  18199. // Lens flares
  18200. if (this.lensFlaresEnabled) {
  18201. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18202. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18203. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18204. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18205. lensFlareSystem.render();
  18206. }
  18207. }
  18208. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18209. }
  18210. // Foregrounds
  18211. if (this.layers.length) {
  18212. engine.setDepthBuffer(false);
  18213. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18214. layer = this.layers[layerIndex];
  18215. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18216. layer.render();
  18217. }
  18218. }
  18219. engine.setDepthBuffer(true);
  18220. }
  18221. // Highlight Layer
  18222. if (renderhighlights) {
  18223. engine.setDepthBuffer(false);
  18224. for (var i = 0; i < this.highlightLayers.length; i++) {
  18225. if (this.highlightLayers[i].shouldRender()) {
  18226. this.highlightLayers[i].render();
  18227. }
  18228. }
  18229. engine.setDepthBuffer(true);
  18230. }
  18231. this._renderDuration.endMonitoring(false);
  18232. // Finalize frame
  18233. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18234. // Update camera
  18235. this.activeCamera._updateFromScene();
  18236. // Reset some special arrays
  18237. this._renderTargets.reset();
  18238. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18239. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18240. };
  18241. Scene.prototype._processSubCameras = function (camera) {
  18242. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18243. this._renderForCamera(camera);
  18244. return;
  18245. }
  18246. // rig cameras
  18247. for (var index = 0; index < camera._rigCameras.length; index++) {
  18248. this._renderForCamera(camera._rigCameras[index]);
  18249. }
  18250. this.activeCamera = camera;
  18251. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18252. // Update camera
  18253. this.activeCamera._updateFromScene();
  18254. };
  18255. Scene.prototype._checkIntersections = function () {
  18256. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18257. var sourceMesh = this._meshesForIntersections.data[index];
  18258. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18259. var action = sourceMesh.actionManager.actions[actionIndex];
  18260. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18261. var parameters = action.getTriggerParameter();
  18262. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18263. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18264. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18265. if (areIntersecting && currentIntersectionInProgress === -1) {
  18266. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18267. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18268. sourceMesh._intersectionsInProgress.push(otherMesh);
  18269. }
  18270. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18271. sourceMesh._intersectionsInProgress.push(otherMesh);
  18272. }
  18273. }
  18274. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18275. //They intersected, and now they don't.
  18276. //is this trigger an exit trigger? execute an event.
  18277. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18278. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18279. }
  18280. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18281. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18282. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18283. }
  18284. }
  18285. }
  18286. }
  18287. }
  18288. };
  18289. Scene.prototype.render = function () {
  18290. if (this.isDisposed) {
  18291. return;
  18292. }
  18293. this._lastFrameDuration.beginMonitoring();
  18294. this._particlesDuration.fetchNewFrame();
  18295. this._spritesDuration.fetchNewFrame();
  18296. this._activeParticles.fetchNewFrame();
  18297. this._renderDuration.fetchNewFrame();
  18298. this._renderTargetsDuration.fetchNewFrame();
  18299. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18300. this._totalVertices.fetchNewFrame();
  18301. this._activeIndices.fetchNewFrame();
  18302. this._activeBones.fetchNewFrame();
  18303. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18304. this._meshesForIntersections.reset();
  18305. this.resetCachedMaterial();
  18306. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18307. // Actions
  18308. if (this.actionManager) {
  18309. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18310. }
  18311. //Simplification Queue
  18312. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18313. this.simplificationQueue.executeNext();
  18314. }
  18315. if (this._engine.isDeterministicLockStep()) {
  18316. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18317. var defaultTimeStep = (60.0 / 1000.0);
  18318. if (this._physicsEngine) {
  18319. defaultTimeStep = this._physicsEngine.getTimeStep();
  18320. }
  18321. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18322. this._timeAccumulator += deltaTime;
  18323. // compute the amount of fixed steps we should have taken since the last step
  18324. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18325. internalSteps = Math.min(internalSteps, maxSubSteps);
  18326. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  18327. this.onBeforeStepObservable.notifyObservers(this);
  18328. // Animations
  18329. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  18330. this._animate();
  18331. // Physics
  18332. if (this._physicsEngine) {
  18333. BABYLON.Tools.StartPerformanceCounter("Physics");
  18334. this._physicsEngine._step(defaultTimeStep);
  18335. BABYLON.Tools.EndPerformanceCounter("Physics");
  18336. }
  18337. this._timeAccumulator -= defaultTimeStep;
  18338. this.onAfterStepObservable.notifyObservers(this);
  18339. this._currentStepId++;
  18340. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  18341. // Q: can this be optimized by putting some code in the afterStep callback?
  18342. // I had to put this code here, otherwise mesh attached to bones of another mesh skeleton,
  18343. // would return incorrect positions for internal stepIds (non-rendered steps)
  18344. this._evaluateActiveMeshes();
  18345. }
  18346. }
  18347. }
  18348. else {
  18349. // Animations
  18350. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18351. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18352. this._animate();
  18353. // Physics
  18354. if (this._physicsEngine) {
  18355. BABYLON.Tools.StartPerformanceCounter("Physics");
  18356. this._physicsEngine._step(deltaTime / 1000.0);
  18357. BABYLON.Tools.EndPerformanceCounter("Physics");
  18358. }
  18359. }
  18360. // Before render
  18361. this.onBeforeRenderObservable.notifyObservers(this);
  18362. // Customs render targets
  18363. this._renderTargetsDuration.beginMonitoring();
  18364. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18365. var engine = this.getEngine();
  18366. var currentActiveCamera = this.activeCamera;
  18367. if (this.renderTargetsEnabled) {
  18368. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18369. this._intermediateRendering = true;
  18370. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18371. var renderTarget = this.customRenderTargets[customIndex];
  18372. if (renderTarget._shouldRender()) {
  18373. this._renderId++;
  18374. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18375. if (!this.activeCamera)
  18376. throw new Error("Active camera not set");
  18377. // Viewport
  18378. engine.setViewport(this.activeCamera.viewport);
  18379. // Camera
  18380. this.updateTransformMatrix();
  18381. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18382. }
  18383. }
  18384. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18385. this._intermediateRendering = false;
  18386. this._renderId++;
  18387. }
  18388. // Restore back buffer
  18389. if (this.customRenderTargets.length > 0) {
  18390. engine.restoreDefaultFramebuffer();
  18391. }
  18392. this._renderTargetsDuration.endMonitoring();
  18393. this.activeCamera = currentActiveCamera;
  18394. // Procedural textures
  18395. if (this.proceduralTexturesEnabled) {
  18396. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18397. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18398. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18399. if (proceduralTexture._shouldRender()) {
  18400. proceduralTexture.render();
  18401. }
  18402. }
  18403. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18404. }
  18405. // Clear
  18406. if (this.autoClearDepthAndStencil || this.autoClear) {
  18407. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18408. }
  18409. // Shadows
  18410. if (this.shadowsEnabled) {
  18411. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18412. var light = this.lights[lightIndex];
  18413. var shadowGenerator = light.getShadowGenerator();
  18414. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18415. var shadowMap = shadowGenerator.getShadowMap();
  18416. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18417. this._renderTargets.push(shadowMap);
  18418. }
  18419. }
  18420. }
  18421. }
  18422. // Depth renderer
  18423. if (this._depthRenderer) {
  18424. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18425. }
  18426. // Geometry renderer
  18427. if (this._geometryBufferRenderer) {
  18428. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  18429. }
  18430. // RenderPipeline
  18431. if (this._postProcessRenderPipelineManager) {
  18432. this._postProcessRenderPipelineManager.update();
  18433. }
  18434. // Multi-cameras?
  18435. if (this.activeCameras.length > 0) {
  18436. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18437. if (cameraIndex > 0) {
  18438. this._engine.clear(null, false, true, true);
  18439. }
  18440. this._processSubCameras(this.activeCameras[cameraIndex]);
  18441. }
  18442. }
  18443. else {
  18444. if (!this.activeCamera) {
  18445. throw new Error("No camera defined");
  18446. }
  18447. this._processSubCameras(this.activeCamera);
  18448. }
  18449. // Intersection checks
  18450. this._checkIntersections();
  18451. // Update the audio listener attached to the camera
  18452. if (BABYLON.AudioEngine) {
  18453. this._updateAudioParameters();
  18454. }
  18455. // After render
  18456. if (this.afterRender) {
  18457. this.afterRender();
  18458. }
  18459. this.onAfterRenderObservable.notifyObservers(this);
  18460. // Cleaning
  18461. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18462. this._toBeDisposed.data[index].dispose();
  18463. this._toBeDisposed[index] = null;
  18464. }
  18465. this._toBeDisposed.reset();
  18466. if (this.dumpNextRenderTargets) {
  18467. this.dumpNextRenderTargets = false;
  18468. }
  18469. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18470. this._lastFrameDuration.endMonitoring();
  18471. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18472. this._totalLightsCounter.addCount(this.lights.length, true);
  18473. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18474. this._totalTexturesCounter.addCount(this.textures.length, true);
  18475. this._activeBones.addCount(0, true);
  18476. this._activeIndices.addCount(0, true);
  18477. this._activeParticles.addCount(0, true);
  18478. };
  18479. Scene.prototype._updateAudioParameters = function () {
  18480. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18481. return;
  18482. }
  18483. var listeningCamera;
  18484. var audioEngine = BABYLON.Engine.audioEngine;
  18485. if (this.activeCameras.length > 0) {
  18486. listeningCamera = this.activeCameras[0];
  18487. }
  18488. else {
  18489. listeningCamera = this.activeCamera;
  18490. }
  18491. if (listeningCamera && audioEngine.canUseWebAudio) {
  18492. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18493. // for VR cameras
  18494. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  18495. listeningCamera = listeningCamera.rigCameras[0];
  18496. }
  18497. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18498. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18499. cameraDirection.normalize();
  18500. // To avoid some errors on GearVR
  18501. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  18502. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18503. }
  18504. var i;
  18505. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18506. var sound = this.mainSoundTrack.soundCollection[i];
  18507. if (sound.useCustomAttenuation) {
  18508. sound.updateDistanceFromListener();
  18509. }
  18510. }
  18511. for (i = 0; i < this.soundTracks.length; i++) {
  18512. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18513. sound = this.soundTracks[i].soundCollection[j];
  18514. if (sound.useCustomAttenuation) {
  18515. sound.updateDistanceFromListener();
  18516. }
  18517. }
  18518. }
  18519. }
  18520. };
  18521. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18522. // Audio
  18523. get: function () {
  18524. return this._audioEnabled;
  18525. },
  18526. set: function (value) {
  18527. this._audioEnabled = value;
  18528. if (BABYLON.AudioEngine) {
  18529. if (this._audioEnabled) {
  18530. this._enableAudio();
  18531. }
  18532. else {
  18533. this._disableAudio();
  18534. }
  18535. }
  18536. },
  18537. enumerable: true,
  18538. configurable: true
  18539. });
  18540. Scene.prototype._disableAudio = function () {
  18541. var i;
  18542. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18543. this.mainSoundTrack.soundCollection[i].pause();
  18544. }
  18545. for (i = 0; i < this.soundTracks.length; i++) {
  18546. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18547. this.soundTracks[i].soundCollection[j].pause();
  18548. }
  18549. }
  18550. };
  18551. Scene.prototype._enableAudio = function () {
  18552. var i;
  18553. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18554. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18555. this.mainSoundTrack.soundCollection[i].play();
  18556. }
  18557. }
  18558. for (i = 0; i < this.soundTracks.length; i++) {
  18559. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18560. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18561. this.soundTracks[i].soundCollection[j].play();
  18562. }
  18563. }
  18564. }
  18565. };
  18566. Object.defineProperty(Scene.prototype, "headphone", {
  18567. get: function () {
  18568. return this._headphone;
  18569. },
  18570. set: function (value) {
  18571. this._headphone = value;
  18572. if (BABYLON.AudioEngine) {
  18573. if (this._headphone) {
  18574. this._switchAudioModeForHeadphones();
  18575. }
  18576. else {
  18577. this._switchAudioModeForNormalSpeakers();
  18578. }
  18579. }
  18580. },
  18581. enumerable: true,
  18582. configurable: true
  18583. });
  18584. Scene.prototype._switchAudioModeForHeadphones = function () {
  18585. this.mainSoundTrack.switchPanningModelToHRTF();
  18586. for (var i = 0; i < this.soundTracks.length; i++) {
  18587. this.soundTracks[i].switchPanningModelToHRTF();
  18588. }
  18589. };
  18590. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18591. this.mainSoundTrack.switchPanningModelToEqualPower();
  18592. for (var i = 0; i < this.soundTracks.length; i++) {
  18593. this.soundTracks[i].switchPanningModelToEqualPower();
  18594. }
  18595. };
  18596. Scene.prototype.enableDepthRenderer = function () {
  18597. if (this._depthRenderer) {
  18598. return this._depthRenderer;
  18599. }
  18600. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18601. return this._depthRenderer;
  18602. };
  18603. Scene.prototype.disableDepthRenderer = function () {
  18604. if (!this._depthRenderer) {
  18605. return;
  18606. }
  18607. this._depthRenderer.dispose();
  18608. this._depthRenderer = null;
  18609. };
  18610. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  18611. if (ratio === void 0) { ratio = 1; }
  18612. if (this._geometryBufferRenderer) {
  18613. return this._geometryBufferRenderer;
  18614. }
  18615. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18616. if (!this._geometryBufferRenderer.isSupported) {
  18617. this._geometryBufferRenderer = null;
  18618. }
  18619. return this._geometryBufferRenderer;
  18620. };
  18621. Scene.prototype.disableGeometryBufferRenderer = function () {
  18622. if (!this._geometryBufferRenderer) {
  18623. return;
  18624. }
  18625. this._geometryBufferRenderer.dispose();
  18626. this._geometryBufferRenderer = null;
  18627. };
  18628. Scene.prototype.freezeMaterials = function () {
  18629. for (var i = 0; i < this.materials.length; i++) {
  18630. this.materials[i].freeze();
  18631. }
  18632. };
  18633. Scene.prototype.unfreezeMaterials = function () {
  18634. for (var i = 0; i < this.materials.length; i++) {
  18635. this.materials[i].unfreeze();
  18636. }
  18637. };
  18638. Scene.prototype.dispose = function () {
  18639. this.beforeRender = null;
  18640. this.afterRender = null;
  18641. this.skeletons = [];
  18642. this.morphTargetManagers = [];
  18643. this.importedMeshesFiles = new Array();
  18644. this.resetCachedMaterial();
  18645. if (this._depthRenderer) {
  18646. this._depthRenderer.dispose();
  18647. }
  18648. // Smart arrays
  18649. if (this.activeCamera) {
  18650. this.activeCamera._activeMeshes.dispose();
  18651. this.activeCamera = null;
  18652. }
  18653. this._activeMeshes.dispose();
  18654. this._renderingManager.dispose();
  18655. this._processedMaterials.dispose();
  18656. this._activeParticleSystems.dispose();
  18657. this._activeSkeletons.dispose();
  18658. this._softwareSkinnedMeshes.dispose();
  18659. this._renderTargets.dispose();
  18660. if (this._boundingBoxRenderer) {
  18661. this._boundingBoxRenderer.dispose();
  18662. }
  18663. this._meshesForIntersections.dispose();
  18664. this._toBeDisposed.dispose();
  18665. // Debug layer
  18666. if (this._debugLayer) {
  18667. this._debugLayer.hide();
  18668. }
  18669. // Events
  18670. this.onDisposeObservable.notifyObservers(this);
  18671. this.onDisposeObservable.clear();
  18672. this.onBeforeRenderObservable.clear();
  18673. this.onAfterRenderObservable.clear();
  18674. this.detachControl();
  18675. // Release sounds & sounds tracks
  18676. if (BABYLON.AudioEngine) {
  18677. this.disposeSounds();
  18678. }
  18679. // VR Helper
  18680. if (this.VRHelper) {
  18681. this.VRHelper.dispose();
  18682. }
  18683. // Detach cameras
  18684. var canvas = this._engine.getRenderingCanvas();
  18685. var index;
  18686. for (index = 0; index < this.cameras.length; index++) {
  18687. this.cameras[index].detachControl(canvas);
  18688. }
  18689. // Release lights
  18690. while (this.lights.length) {
  18691. this.lights[0].dispose();
  18692. }
  18693. // Release meshes
  18694. while (this.meshes.length) {
  18695. this.meshes[0].dispose(true);
  18696. }
  18697. // Release cameras
  18698. while (this.cameras.length) {
  18699. this.cameras[0].dispose();
  18700. }
  18701. // Release materials
  18702. if (this.defaultMaterial) {
  18703. this.defaultMaterial.dispose();
  18704. }
  18705. while (this.multiMaterials.length) {
  18706. this.multiMaterials[0].dispose();
  18707. }
  18708. while (this.materials.length) {
  18709. this.materials[0].dispose();
  18710. }
  18711. // Release particles
  18712. while (this.particleSystems.length) {
  18713. this.particleSystems[0].dispose();
  18714. }
  18715. // Release sprites
  18716. while (this.spriteManagers.length) {
  18717. this.spriteManagers[0].dispose();
  18718. }
  18719. // Release layers
  18720. while (this.layers.length) {
  18721. this.layers[0].dispose();
  18722. }
  18723. while (this.highlightLayers.length) {
  18724. this.highlightLayers[0].dispose();
  18725. }
  18726. // Release textures
  18727. while (this.textures.length) {
  18728. this.textures[0].dispose();
  18729. }
  18730. // Release UBO
  18731. this._sceneUbo.dispose();
  18732. // Post-processes
  18733. this.postProcessManager.dispose();
  18734. // Physics
  18735. if (this._physicsEngine) {
  18736. this.disablePhysicsEngine();
  18737. }
  18738. // Remove from engine
  18739. index = this._engine.scenes.indexOf(this);
  18740. if (index > -1) {
  18741. this._engine.scenes.splice(index, 1);
  18742. }
  18743. this._engine.wipeCaches();
  18744. this._engine = null;
  18745. this.defaultMaterial = null;
  18746. this.multiMaterials = null;
  18747. this.materials = null;
  18748. };
  18749. Object.defineProperty(Scene.prototype, "isDisposed", {
  18750. get: function () {
  18751. return !this._engine;
  18752. },
  18753. enumerable: true,
  18754. configurable: true
  18755. });
  18756. // Release sounds & sounds tracks
  18757. Scene.prototype.disposeSounds = function () {
  18758. this.mainSoundTrack.dispose();
  18759. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18760. this.soundTracks[scIndex].dispose();
  18761. }
  18762. };
  18763. // Octrees
  18764. Scene.prototype.getWorldExtends = function () {
  18765. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18766. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18767. for (var index = 0; index < this.meshes.length; index++) {
  18768. var mesh = this.meshes[index];
  18769. mesh.computeWorldMatrix(true);
  18770. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18771. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18772. BABYLON.Tools.CheckExtends(minBox, min, max);
  18773. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18774. }
  18775. return {
  18776. min: min,
  18777. max: max
  18778. };
  18779. };
  18780. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18781. if (maxCapacity === void 0) { maxCapacity = 64; }
  18782. if (maxDepth === void 0) { maxDepth = 2; }
  18783. if (!this._selectionOctree) {
  18784. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18785. }
  18786. var worldExtends = this.getWorldExtends();
  18787. // Update octree
  18788. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18789. return this._selectionOctree;
  18790. };
  18791. // Picking
  18792. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18793. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18794. var engine = this._engine;
  18795. if (!camera) {
  18796. if (!this.activeCamera)
  18797. throw new Error("Active camera not set");
  18798. camera = this.activeCamera;
  18799. }
  18800. var cameraViewport = camera.viewport;
  18801. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18802. // Moving coordinates to local viewport world
  18803. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18804. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18805. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18806. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18807. };
  18808. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18809. if (!BABYLON.PickingInfo) {
  18810. return null;
  18811. }
  18812. var engine = this._engine;
  18813. if (!camera) {
  18814. if (!this.activeCamera)
  18815. throw new Error("Active camera not set");
  18816. camera = this.activeCamera;
  18817. }
  18818. var cameraViewport = camera.viewport;
  18819. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18820. var identity = BABYLON.Matrix.Identity();
  18821. // Moving coordinates to local viewport world
  18822. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18823. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18824. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18825. };
  18826. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18827. if (!BABYLON.PickingInfo) {
  18828. return null;
  18829. }
  18830. var pickingInfo = null;
  18831. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18832. var mesh = this.meshes[meshIndex];
  18833. if (predicate) {
  18834. if (!predicate(mesh)) {
  18835. continue;
  18836. }
  18837. }
  18838. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18839. continue;
  18840. }
  18841. var world = mesh.getWorldMatrix();
  18842. var ray = rayFunction(world);
  18843. var result = mesh.intersects(ray, fastCheck);
  18844. if (!result || !result.hit)
  18845. continue;
  18846. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18847. continue;
  18848. pickingInfo = result;
  18849. if (fastCheck) {
  18850. break;
  18851. }
  18852. }
  18853. return pickingInfo || new BABYLON.PickingInfo();
  18854. };
  18855. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18856. if (!BABYLON.PickingInfo) {
  18857. return null;
  18858. }
  18859. var pickingInfos = new Array();
  18860. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18861. var mesh = this.meshes[meshIndex];
  18862. if (predicate) {
  18863. if (!predicate(mesh)) {
  18864. continue;
  18865. }
  18866. }
  18867. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18868. continue;
  18869. }
  18870. var world = mesh.getWorldMatrix();
  18871. var ray = rayFunction(world);
  18872. var result = mesh.intersects(ray, false);
  18873. if (!result || !result.hit)
  18874. continue;
  18875. pickingInfos.push(result);
  18876. }
  18877. return pickingInfos;
  18878. };
  18879. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18880. if (!BABYLON.PickingInfo) {
  18881. return null;
  18882. }
  18883. var pickingInfo = null;
  18884. camera = camera || this.activeCamera;
  18885. if (this.spriteManagers.length > 0) {
  18886. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18887. var spriteManager = this.spriteManagers[spriteIndex];
  18888. if (!spriteManager.isPickable) {
  18889. continue;
  18890. }
  18891. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18892. if (!result || !result.hit)
  18893. continue;
  18894. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18895. continue;
  18896. pickingInfo = result;
  18897. if (fastCheck) {
  18898. break;
  18899. }
  18900. }
  18901. }
  18902. return pickingInfo || new BABYLON.PickingInfo();
  18903. };
  18904. /** Launch a ray to try to pick a mesh in the scene
  18905. * @param x position on screen
  18906. * @param y position on screen
  18907. * @param 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
  18908. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  18909. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  18910. */
  18911. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18912. var _this = this;
  18913. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18914. };
  18915. /** Launch a ray to try to pick a sprite in the scene
  18916. * @param x position on screen
  18917. * @param y position on screen
  18918. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  18919. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  18920. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  18921. */
  18922. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18923. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18924. };
  18925. /** Use the given ray to pick a mesh in the scene
  18926. * @param ray The ray to use to pick meshes
  18927. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  18928. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  18929. */
  18930. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18931. var _this = this;
  18932. return this._internalPick(function (world) {
  18933. if (!_this._pickWithRayInverseMatrix) {
  18934. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18935. }
  18936. world.invertToRef(_this._pickWithRayInverseMatrix);
  18937. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18938. }, predicate, fastCheck);
  18939. };
  18940. /**
  18941. * Launch a ray to try to pick a mesh in the scene
  18942. * @param x X position on screen
  18943. * @param y Y position on screen
  18944. * @param 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
  18945. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  18946. */
  18947. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18948. var _this = this;
  18949. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18950. };
  18951. /**
  18952. * Launch a ray to try to pick a mesh in the scene
  18953. * @param ray Ray to use
  18954. * @param 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
  18955. */
  18956. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18957. var _this = this;
  18958. return this._internalMultiPick(function (world) {
  18959. if (!_this._pickWithRayInverseMatrix) {
  18960. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18961. }
  18962. world.invertToRef(_this._pickWithRayInverseMatrix);
  18963. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18964. }, predicate);
  18965. };
  18966. Scene.prototype.setPointerOverMesh = function (mesh) {
  18967. if (this._pointerOverMesh === mesh) {
  18968. return;
  18969. }
  18970. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18971. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18972. }
  18973. this._pointerOverMesh = mesh;
  18974. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18975. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18976. }
  18977. };
  18978. Scene.prototype.getPointerOverMesh = function () {
  18979. return this._pointerOverMesh;
  18980. };
  18981. Scene.prototype.setPointerOverSprite = function (sprite) {
  18982. if (this._pointerOverSprite === sprite) {
  18983. return;
  18984. }
  18985. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18986. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18987. }
  18988. this._pointerOverSprite = sprite;
  18989. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18990. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18991. }
  18992. };
  18993. Scene.prototype.getPointerOverSprite = function () {
  18994. return this._pointerOverSprite;
  18995. };
  18996. // Physics
  18997. Scene.prototype.getPhysicsEngine = function () {
  18998. return this._physicsEngine;
  18999. };
  19000. /**
  19001. * Enables physics to the current scene
  19002. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19003. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19004. * @return {boolean} was the physics engine initialized
  19005. */
  19006. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19007. if (this._physicsEngine) {
  19008. return true;
  19009. }
  19010. try {
  19011. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19012. return true;
  19013. }
  19014. catch (e) {
  19015. BABYLON.Tools.Error(e.message);
  19016. return false;
  19017. }
  19018. };
  19019. Scene.prototype.disablePhysicsEngine = function () {
  19020. if (!this._physicsEngine) {
  19021. return;
  19022. }
  19023. this._physicsEngine.dispose();
  19024. this._physicsEngine = undefined;
  19025. };
  19026. Scene.prototype.isPhysicsEnabled = function () {
  19027. return this._physicsEngine !== undefined;
  19028. };
  19029. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19030. var mesh = compound.parts[0].mesh;
  19031. mesh.physicsImpostor.dispose();
  19032. mesh.physicsImpostor = null;
  19033. };
  19034. // Misc.
  19035. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19036. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19037. if (replace === void 0) { replace = false; }
  19038. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19039. // Dispose existing camera or light in replace mode.
  19040. if (replace) {
  19041. if (this.activeCamera) {
  19042. this.activeCamera.dispose();
  19043. this.activeCamera = null;
  19044. }
  19045. if (this.lights) {
  19046. for (var i = 0; i < this.lights.length; i++) {
  19047. this.lights[i].dispose();
  19048. }
  19049. }
  19050. }
  19051. // Light
  19052. if (this.lights.length === 0) {
  19053. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19054. }
  19055. // Camera
  19056. if (!this.activeCamera) {
  19057. var worldExtends = this.getWorldExtends();
  19058. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19059. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19060. var camera;
  19061. var radius = worldSize.length() * 1.5;
  19062. if (createArcRotateCamera) {
  19063. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19064. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19065. arcRotateCamera.wheelPrecision = 100 / radius;
  19066. camera = arcRotateCamera;
  19067. }
  19068. else {
  19069. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19070. freeCamera.setTarget(worldCenter);
  19071. camera = freeCamera;
  19072. }
  19073. camera.minZ = radius * 0.01;
  19074. camera.maxZ = radius * 100;
  19075. camera.speed = radius * 0.2;
  19076. this.activeCamera = camera;
  19077. if (attachCameraControls) {
  19078. camera.attachControl(this.getEngine().getRenderingCanvas());
  19079. }
  19080. }
  19081. };
  19082. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19083. if (pbr === void 0) { pbr = false; }
  19084. if (scale === void 0) { scale = 1000; }
  19085. if (blur === void 0) { blur = 0; }
  19086. if (environmentTexture) {
  19087. this.environmentTexture = environmentTexture;
  19088. }
  19089. if (!this.environmentTexture) {
  19090. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19091. return;
  19092. }
  19093. // Skybox
  19094. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19095. if (pbr) {
  19096. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19097. hdrSkyboxMaterial.backFaceCulling = false;
  19098. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19099. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19100. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19101. hdrSkyboxMaterial.disableLighting = true;
  19102. hdrSkyboxMaterial.twoSidedLighting = true;
  19103. hdrSkybox.infiniteDistance = true;
  19104. hdrSkybox.material = hdrSkyboxMaterial;
  19105. }
  19106. else {
  19107. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19108. skyboxMaterial.backFaceCulling = false;
  19109. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19110. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19111. skyboxMaterial.disableLighting = true;
  19112. hdrSkybox.infiniteDistance = true;
  19113. hdrSkybox.material = skyboxMaterial;
  19114. }
  19115. return hdrSkybox;
  19116. };
  19117. Scene.prototype.createDefaultVRExperience = function () {
  19118. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19119. };
  19120. // Tags
  19121. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19122. if (tagsQuery === undefined) {
  19123. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19124. return list;
  19125. }
  19126. var listByTags = [];
  19127. forEach = forEach || (function (item) { return; });
  19128. for (var i in list) {
  19129. var item = list[i];
  19130. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19131. listByTags.push(item);
  19132. forEach(item);
  19133. }
  19134. }
  19135. return listByTags;
  19136. };
  19137. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19138. return this._getByTags(this.meshes, tagsQuery, forEach);
  19139. };
  19140. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19141. return this._getByTags(this.cameras, tagsQuery, forEach);
  19142. };
  19143. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19144. return this._getByTags(this.lights, tagsQuery, forEach);
  19145. };
  19146. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19147. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19148. };
  19149. /**
  19150. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19151. * This allowed control for front to back rendering or reversly depending of the special needs.
  19152. *
  19153. * @param renderingGroupId The rendering group id corresponding to its index
  19154. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19155. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19156. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19157. */
  19158. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19159. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19160. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19161. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19162. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19163. };
  19164. /**
  19165. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19166. *
  19167. * @param renderingGroupId The rendering group id corresponding to its index
  19168. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19169. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19170. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19171. */
  19172. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19173. if (depth === void 0) { depth = true; }
  19174. if (stencil === void 0) { stencil = true; }
  19175. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19176. };
  19177. /**
  19178. * Will flag all materials as dirty to trigger new shader compilation
  19179. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19180. */
  19181. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19182. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19183. var material = _a[_i];
  19184. if (predicate && !predicate(material)) {
  19185. continue;
  19186. }
  19187. material.markAsDirty(flag);
  19188. }
  19189. };
  19190. // Statics
  19191. Scene._FOGMODE_NONE = 0;
  19192. Scene._FOGMODE_EXP = 1;
  19193. Scene._FOGMODE_EXP2 = 2;
  19194. Scene._FOGMODE_LINEAR = 3;
  19195. Scene.MinDeltaTime = 1.0;
  19196. Scene.MaxDeltaTime = 1000.0;
  19197. /** The distance in pixel that you have to move to prevent some events */
  19198. Scene.DragMovementThreshold = 10; // in pixels
  19199. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19200. Scene.LongPressDelay = 500; // in milliseconds
  19201. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19202. Scene.DoubleClickDelay = 300; // in milliseconds
  19203. /** If you need to check double click without raising a single click at first click, enable this flag */
  19204. Scene.ExclusiveDoubleClickMode = false;
  19205. return Scene;
  19206. }());
  19207. BABYLON.Scene = Scene;
  19208. })(BABYLON || (BABYLON = {}));
  19209. //# sourceMappingURL=babylon.scene.js.map
  19210. var BABYLON;
  19211. (function (BABYLON) {
  19212. var Buffer = (function () {
  19213. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19214. if (engine instanceof BABYLON.Mesh) {
  19215. this._engine = engine.getScene().getEngine();
  19216. }
  19217. else {
  19218. this._engine = engine;
  19219. }
  19220. this._updatable = updatable;
  19221. this._data = data;
  19222. this._strideSize = stride;
  19223. if (!postponeInternalCreation) {
  19224. this.create();
  19225. }
  19226. this._instanced = instanced;
  19227. this._instanceDivisor = instanced ? 1 : 0;
  19228. }
  19229. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19230. // a lot of these parameters are ignored as they are overriden by the buffer
  19231. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19232. };
  19233. // Properties
  19234. Buffer.prototype.isUpdatable = function () {
  19235. return this._updatable;
  19236. };
  19237. Buffer.prototype.getData = function () {
  19238. return this._data;
  19239. };
  19240. Buffer.prototype.getBuffer = function () {
  19241. return this._buffer;
  19242. };
  19243. Buffer.prototype.getStrideSize = function () {
  19244. return this._strideSize;
  19245. };
  19246. Buffer.prototype.getIsInstanced = function () {
  19247. return this._instanced;
  19248. };
  19249. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19250. get: function () {
  19251. return this._instanceDivisor;
  19252. },
  19253. set: function (value) {
  19254. this._instanceDivisor = value;
  19255. if (value == 0) {
  19256. this._instanced = false;
  19257. }
  19258. else {
  19259. this._instanced = true;
  19260. }
  19261. },
  19262. enumerable: true,
  19263. configurable: true
  19264. });
  19265. // Methods
  19266. Buffer.prototype.create = function (data) {
  19267. if (!data && this._buffer) {
  19268. return; // nothing to do
  19269. }
  19270. data = data || this._data;
  19271. if (!this._buffer) {
  19272. if (this._updatable) {
  19273. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19274. this._data = data;
  19275. }
  19276. else {
  19277. this._buffer = this._engine.createVertexBuffer(data);
  19278. }
  19279. }
  19280. else if (this._updatable) {
  19281. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19282. this._data = data;
  19283. }
  19284. };
  19285. Buffer.prototype.update = function (data) {
  19286. this.create(data);
  19287. };
  19288. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19289. if (!this._buffer) {
  19290. return;
  19291. }
  19292. if (this._updatable) {
  19293. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19294. this._data = null;
  19295. }
  19296. };
  19297. Buffer.prototype.dispose = function () {
  19298. if (!this._buffer) {
  19299. return;
  19300. }
  19301. if (this._engine._releaseBuffer(this._buffer)) {
  19302. this._buffer = null;
  19303. }
  19304. };
  19305. return Buffer;
  19306. }());
  19307. BABYLON.Buffer = Buffer;
  19308. })(BABYLON || (BABYLON = {}));
  19309. //# sourceMappingURL=babylon.buffer.js.map
  19310. var BABYLON;
  19311. (function (BABYLON) {
  19312. var VertexBuffer = (function () {
  19313. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19314. if (!stride) {
  19315. // Deduce stride from kind
  19316. switch (kind) {
  19317. case VertexBuffer.PositionKind:
  19318. stride = 3;
  19319. break;
  19320. case VertexBuffer.NormalKind:
  19321. stride = 3;
  19322. break;
  19323. case VertexBuffer.UVKind:
  19324. case VertexBuffer.UV2Kind:
  19325. case VertexBuffer.UV3Kind:
  19326. case VertexBuffer.UV4Kind:
  19327. case VertexBuffer.UV5Kind:
  19328. case VertexBuffer.UV6Kind:
  19329. stride = 2;
  19330. break;
  19331. case VertexBuffer.TangentKind:
  19332. case VertexBuffer.ColorKind:
  19333. stride = 4;
  19334. break;
  19335. case VertexBuffer.MatricesIndicesKind:
  19336. case VertexBuffer.MatricesIndicesExtraKind:
  19337. stride = 4;
  19338. break;
  19339. case VertexBuffer.MatricesWeightsKind:
  19340. case VertexBuffer.MatricesWeightsExtraKind:
  19341. stride = 4;
  19342. break;
  19343. }
  19344. }
  19345. if (data instanceof BABYLON.Buffer) {
  19346. if (!stride) {
  19347. stride = data.getStrideSize();
  19348. }
  19349. this._buffer = data;
  19350. this._ownsBuffer = false;
  19351. }
  19352. else {
  19353. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19354. this._ownsBuffer = true;
  19355. }
  19356. this._stride = stride;
  19357. this._offset = offset ? offset : 0;
  19358. this._size = size ? size : stride;
  19359. this._kind = kind;
  19360. }
  19361. /**
  19362. * Returns the kind of the VertexBuffer (string).
  19363. */
  19364. VertexBuffer.prototype.getKind = function () {
  19365. return this._kind;
  19366. };
  19367. // Properties
  19368. /**
  19369. * Boolean : is the VertexBuffer updatable ?
  19370. */
  19371. VertexBuffer.prototype.isUpdatable = function () {
  19372. return this._buffer.isUpdatable();
  19373. };
  19374. /**
  19375. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  19376. */
  19377. VertexBuffer.prototype.getData = function () {
  19378. return this._buffer.getData();
  19379. };
  19380. /**
  19381. * Returns the WebGLBuffer associated to the VertexBuffer.
  19382. */
  19383. VertexBuffer.prototype.getBuffer = function () {
  19384. return this._buffer.getBuffer();
  19385. };
  19386. /**
  19387. * Returns the stride of the VertexBuffer (integer).
  19388. */
  19389. VertexBuffer.prototype.getStrideSize = function () {
  19390. return this._stride;
  19391. };
  19392. /**
  19393. * Returns the offset (integer).
  19394. */
  19395. VertexBuffer.prototype.getOffset = function () {
  19396. return this._offset;
  19397. };
  19398. /**
  19399. * Returns the VertexBuffer total size (integer).
  19400. */
  19401. VertexBuffer.prototype.getSize = function () {
  19402. return this._size;
  19403. };
  19404. /**
  19405. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  19406. */
  19407. VertexBuffer.prototype.getIsInstanced = function () {
  19408. return this._buffer.getIsInstanced();
  19409. };
  19410. /**
  19411. * Returns the instancing divisor, zero for non-instanced (integer).
  19412. */
  19413. VertexBuffer.prototype.getInstanceDivisor = function () {
  19414. return this._buffer.instanceDivisor;
  19415. };
  19416. // Methods
  19417. /**
  19418. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  19419. * Returns the created WebGLBuffer.
  19420. */
  19421. VertexBuffer.prototype.create = function (data) {
  19422. return this._buffer.create(data);
  19423. };
  19424. /**
  19425. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19426. * Returns the updated WebGLBuffer.
  19427. */
  19428. VertexBuffer.prototype.update = function (data) {
  19429. return this._buffer.update(data);
  19430. };
  19431. /**
  19432. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19433. * Returns the directly updated WebGLBuffer.
  19434. */
  19435. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19436. return this._buffer.updateDirectly(data, offset);
  19437. };
  19438. /**
  19439. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  19440. */
  19441. VertexBuffer.prototype.dispose = function () {
  19442. if (this._ownsBuffer) {
  19443. this._buffer.dispose();
  19444. }
  19445. };
  19446. Object.defineProperty(VertexBuffer, "PositionKind", {
  19447. get: function () {
  19448. return VertexBuffer._PositionKind;
  19449. },
  19450. enumerable: true,
  19451. configurable: true
  19452. });
  19453. Object.defineProperty(VertexBuffer, "NormalKind", {
  19454. get: function () {
  19455. return VertexBuffer._NormalKind;
  19456. },
  19457. enumerable: true,
  19458. configurable: true
  19459. });
  19460. Object.defineProperty(VertexBuffer, "TangentKind", {
  19461. get: function () {
  19462. return VertexBuffer._TangentKind;
  19463. },
  19464. enumerable: true,
  19465. configurable: true
  19466. });
  19467. Object.defineProperty(VertexBuffer, "UVKind", {
  19468. get: function () {
  19469. return VertexBuffer._UVKind;
  19470. },
  19471. enumerable: true,
  19472. configurable: true
  19473. });
  19474. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19475. get: function () {
  19476. return VertexBuffer._UV2Kind;
  19477. },
  19478. enumerable: true,
  19479. configurable: true
  19480. });
  19481. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19482. get: function () {
  19483. return VertexBuffer._UV3Kind;
  19484. },
  19485. enumerable: true,
  19486. configurable: true
  19487. });
  19488. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19489. get: function () {
  19490. return VertexBuffer._UV4Kind;
  19491. },
  19492. enumerable: true,
  19493. configurable: true
  19494. });
  19495. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19496. get: function () {
  19497. return VertexBuffer._UV5Kind;
  19498. },
  19499. enumerable: true,
  19500. configurable: true
  19501. });
  19502. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19503. get: function () {
  19504. return VertexBuffer._UV6Kind;
  19505. },
  19506. enumerable: true,
  19507. configurable: true
  19508. });
  19509. Object.defineProperty(VertexBuffer, "ColorKind", {
  19510. get: function () {
  19511. return VertexBuffer._ColorKind;
  19512. },
  19513. enumerable: true,
  19514. configurable: true
  19515. });
  19516. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19517. get: function () {
  19518. return VertexBuffer._MatricesIndicesKind;
  19519. },
  19520. enumerable: true,
  19521. configurable: true
  19522. });
  19523. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19524. get: function () {
  19525. return VertexBuffer._MatricesWeightsKind;
  19526. },
  19527. enumerable: true,
  19528. configurable: true
  19529. });
  19530. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19531. get: function () {
  19532. return VertexBuffer._MatricesIndicesExtraKind;
  19533. },
  19534. enumerable: true,
  19535. configurable: true
  19536. });
  19537. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19538. get: function () {
  19539. return VertexBuffer._MatricesWeightsExtraKind;
  19540. },
  19541. enumerable: true,
  19542. configurable: true
  19543. });
  19544. // Enums
  19545. VertexBuffer._PositionKind = "position";
  19546. VertexBuffer._NormalKind = "normal";
  19547. VertexBuffer._TangentKind = "tangent";
  19548. VertexBuffer._UVKind = "uv";
  19549. VertexBuffer._UV2Kind = "uv2";
  19550. VertexBuffer._UV3Kind = "uv3";
  19551. VertexBuffer._UV4Kind = "uv4";
  19552. VertexBuffer._UV5Kind = "uv5";
  19553. VertexBuffer._UV6Kind = "uv6";
  19554. VertexBuffer._ColorKind = "color";
  19555. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19556. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19557. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19558. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19559. return VertexBuffer;
  19560. }());
  19561. BABYLON.VertexBuffer = VertexBuffer;
  19562. })(BABYLON || (BABYLON = {}));
  19563. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19564. var BABYLON;
  19565. (function (BABYLON) {
  19566. var BaseTexture = (function () {
  19567. function BaseTexture(scene) {
  19568. this._hasAlpha = false;
  19569. this.getAlphaFromRGB = false;
  19570. this.level = 1;
  19571. this.coordinatesIndex = 0;
  19572. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  19573. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  19574. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  19575. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  19576. this.isCube = false;
  19577. this.gammaSpace = true;
  19578. this.invertZ = false;
  19579. this.lodLevelInAlpha = false;
  19580. this.lodGenerationOffset = 0.0;
  19581. this.lodGenerationScale = 0.8;
  19582. this.isRenderTarget = false;
  19583. this.animations = new Array();
  19584. /**
  19585. * An event triggered when the texture is disposed.
  19586. * @type {BABYLON.Observable}
  19587. */
  19588. this.onDisposeObservable = new BABYLON.Observable();
  19589. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19590. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  19591. this._scene.textures.push(this);
  19592. this._uid = null;
  19593. }
  19594. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  19595. get: function () {
  19596. return this._hasAlpha;
  19597. },
  19598. set: function (value) {
  19599. if (this._hasAlpha === value) {
  19600. return;
  19601. }
  19602. this._hasAlpha = value;
  19603. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19604. },
  19605. enumerable: true,
  19606. configurable: true
  19607. });
  19608. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  19609. get: function () {
  19610. return this._coordinatesMode;
  19611. },
  19612. set: function (value) {
  19613. if (this._coordinatesMode === value) {
  19614. return;
  19615. }
  19616. this._coordinatesMode = value;
  19617. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19618. },
  19619. enumerable: true,
  19620. configurable: true
  19621. });
  19622. Object.defineProperty(BaseTexture.prototype, "uid", {
  19623. get: function () {
  19624. if (!this._uid) {
  19625. this._uid = BABYLON.Tools.RandomId();
  19626. }
  19627. return this._uid;
  19628. },
  19629. enumerable: true,
  19630. configurable: true
  19631. });
  19632. BaseTexture.prototype.toString = function () {
  19633. return this.name;
  19634. };
  19635. BaseTexture.prototype.getClassName = function () {
  19636. return "BaseTexture";
  19637. };
  19638. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  19639. set: function (callback) {
  19640. if (this._onDisposeObserver) {
  19641. this.onDisposeObservable.remove(this._onDisposeObserver);
  19642. }
  19643. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19644. },
  19645. enumerable: true,
  19646. configurable: true
  19647. });
  19648. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  19649. get: function () {
  19650. return true;
  19651. },
  19652. enumerable: true,
  19653. configurable: true
  19654. });
  19655. BaseTexture.prototype.getScene = function () {
  19656. return this._scene;
  19657. };
  19658. BaseTexture.prototype.getTextureMatrix = function () {
  19659. return null;
  19660. };
  19661. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  19662. return null;
  19663. };
  19664. BaseTexture.prototype.getInternalTexture = function () {
  19665. return this._texture;
  19666. };
  19667. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  19668. return !this.isBlocking || this.isReady();
  19669. };
  19670. BaseTexture.prototype.isReady = function () {
  19671. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19672. this.delayLoad();
  19673. return false;
  19674. }
  19675. if (this._texture) {
  19676. return this._texture.isReady;
  19677. }
  19678. return false;
  19679. };
  19680. BaseTexture.prototype.getSize = function () {
  19681. if (this._texture._width) {
  19682. return new BABYLON.Size(this._texture._width, this._texture._height);
  19683. }
  19684. if (this._texture._size) {
  19685. return new BABYLON.Size(this._texture._size, this._texture._size);
  19686. }
  19687. return BABYLON.Size.Zero();
  19688. };
  19689. BaseTexture.prototype.getBaseSize = function () {
  19690. if (!this.isReady() || !this._texture)
  19691. return BABYLON.Size.Zero();
  19692. if (this._texture._size) {
  19693. return new BABYLON.Size(this._texture._size, this._texture._size);
  19694. }
  19695. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  19696. };
  19697. BaseTexture.prototype.scale = function (ratio) {
  19698. };
  19699. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  19700. get: function () {
  19701. return false;
  19702. },
  19703. enumerable: true,
  19704. configurable: true
  19705. });
  19706. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  19707. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19708. for (var index = 0; index < texturesCache.length; index++) {
  19709. var texturesCacheEntry = texturesCache[index];
  19710. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  19711. texturesCache.splice(index, 1);
  19712. return;
  19713. }
  19714. }
  19715. };
  19716. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  19717. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19718. for (var index = 0; index < texturesCache.length; index++) {
  19719. var texturesCacheEntry = texturesCache[index];
  19720. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  19721. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  19722. texturesCacheEntry.references++;
  19723. return texturesCacheEntry;
  19724. }
  19725. }
  19726. }
  19727. return null;
  19728. };
  19729. BaseTexture.prototype.delayLoad = function () {
  19730. };
  19731. BaseTexture.prototype.clone = function () {
  19732. return null;
  19733. };
  19734. Object.defineProperty(BaseTexture.prototype, "textureType", {
  19735. get: function () {
  19736. if (!this._texture) {
  19737. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19738. }
  19739. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19740. },
  19741. enumerable: true,
  19742. configurable: true
  19743. });
  19744. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  19745. get: function () {
  19746. if (!this._texture) {
  19747. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  19748. }
  19749. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  19750. },
  19751. enumerable: true,
  19752. configurable: true
  19753. });
  19754. BaseTexture.prototype.readPixels = function (faceIndex) {
  19755. if (faceIndex === void 0) { faceIndex = 0; }
  19756. if (!this._texture) {
  19757. return null;
  19758. }
  19759. var size = this.getSize();
  19760. var engine = this.getScene().getEngine();
  19761. if (this._texture.isCube) {
  19762. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  19763. }
  19764. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  19765. };
  19766. BaseTexture.prototype.releaseInternalTexture = function () {
  19767. if (this._texture) {
  19768. this._scene.getEngine().releaseInternalTexture(this._texture);
  19769. delete this._texture;
  19770. }
  19771. };
  19772. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  19773. get: function () {
  19774. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  19775. return null;
  19776. }
  19777. if (!this._texture._sphericalPolynomial) {
  19778. this._texture._sphericalPolynomial =
  19779. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  19780. }
  19781. return this._texture._sphericalPolynomial;
  19782. },
  19783. set: function (value) {
  19784. if (this._texture) {
  19785. this._texture._sphericalPolynomial = value;
  19786. }
  19787. },
  19788. enumerable: true,
  19789. configurable: true
  19790. });
  19791. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  19792. get: function () {
  19793. if (this._texture) {
  19794. return this._texture._lodTextureHigh;
  19795. }
  19796. return null;
  19797. },
  19798. enumerable: true,
  19799. configurable: true
  19800. });
  19801. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  19802. get: function () {
  19803. if (this._texture) {
  19804. return this._texture._lodTextureMid;
  19805. }
  19806. return null;
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  19812. get: function () {
  19813. if (this._texture) {
  19814. return this._texture._lodTextureLow;
  19815. }
  19816. return null;
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. BaseTexture.prototype.dispose = function () {
  19822. // Animations
  19823. this.getScene().stopAnimation(this);
  19824. // Remove from scene
  19825. this._scene._removePendingData(this);
  19826. var index = this._scene.textures.indexOf(this);
  19827. if (index >= 0) {
  19828. this._scene.textures.splice(index, 1);
  19829. }
  19830. if (this._texture === undefined) {
  19831. return;
  19832. }
  19833. // Release
  19834. this.releaseInternalTexture();
  19835. // Callback
  19836. this.onDisposeObservable.notifyObservers(this);
  19837. this.onDisposeObservable.clear();
  19838. };
  19839. BaseTexture.prototype.serialize = function () {
  19840. if (!this.name) {
  19841. return null;
  19842. }
  19843. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19844. // Animations
  19845. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19846. return serializationObject;
  19847. };
  19848. BaseTexture.WhenAllReady = function (textures, callback) {
  19849. var numRemaining = textures.length;
  19850. if (numRemaining === 0) {
  19851. callback();
  19852. return;
  19853. }
  19854. var _loop_1 = function () {
  19855. texture = textures[i];
  19856. if (texture.isReady()) {
  19857. if (--numRemaining === 0) {
  19858. callback();
  19859. }
  19860. }
  19861. else {
  19862. onLoadObservable = texture.onLoadObservable;
  19863. var onLoadCallback_1 = function () {
  19864. onLoadObservable.removeCallback(onLoadCallback_1);
  19865. if (--numRemaining === 0) {
  19866. callback();
  19867. }
  19868. };
  19869. onLoadObservable.add(onLoadCallback_1);
  19870. }
  19871. };
  19872. var texture, onLoadObservable;
  19873. for (var i = 0; i < textures.length; i++) {
  19874. _loop_1();
  19875. }
  19876. };
  19877. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  19878. __decorate([
  19879. BABYLON.serialize()
  19880. ], BaseTexture.prototype, "name", void 0);
  19881. __decorate([
  19882. BABYLON.serialize("hasAlpha")
  19883. ], BaseTexture.prototype, "_hasAlpha", void 0);
  19884. __decorate([
  19885. BABYLON.serialize()
  19886. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  19887. __decorate([
  19888. BABYLON.serialize()
  19889. ], BaseTexture.prototype, "level", void 0);
  19890. __decorate([
  19891. BABYLON.serialize()
  19892. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  19893. __decorate([
  19894. BABYLON.serialize("coordinatesMode")
  19895. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  19896. __decorate([
  19897. BABYLON.serialize()
  19898. ], BaseTexture.prototype, "wrapU", void 0);
  19899. __decorate([
  19900. BABYLON.serialize()
  19901. ], BaseTexture.prototype, "wrapV", void 0);
  19902. __decorate([
  19903. BABYLON.serialize()
  19904. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  19905. __decorate([
  19906. BABYLON.serialize()
  19907. ], BaseTexture.prototype, "isCube", void 0);
  19908. __decorate([
  19909. BABYLON.serialize()
  19910. ], BaseTexture.prototype, "gammaSpace", void 0);
  19911. __decorate([
  19912. BABYLON.serialize()
  19913. ], BaseTexture.prototype, "invertZ", void 0);
  19914. __decorate([
  19915. BABYLON.serialize()
  19916. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  19917. __decorate([
  19918. BABYLON.serialize()
  19919. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  19920. __decorate([
  19921. BABYLON.serialize()
  19922. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  19923. __decorate([
  19924. BABYLON.serialize()
  19925. ], BaseTexture.prototype, "isRenderTarget", void 0);
  19926. return BaseTexture;
  19927. }());
  19928. BABYLON.BaseTexture = BaseTexture;
  19929. })(BABYLON || (BABYLON = {}));
  19930. //# sourceMappingURL=babylon.baseTexture.js.map
  19931. var BABYLON;
  19932. (function (BABYLON) {
  19933. var Texture = (function (_super) {
  19934. __extends(Texture, _super);
  19935. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19936. if (noMipmap === void 0) { noMipmap = false; }
  19937. if (invertY === void 0) { invertY = true; }
  19938. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19939. if (onLoad === void 0) { onLoad = null; }
  19940. if (onError === void 0) { onError = null; }
  19941. if (buffer === void 0) { buffer = null; }
  19942. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19943. var _this = _super.call(this, scene) || this;
  19944. _this.uOffset = 0;
  19945. _this.vOffset = 0;
  19946. _this.uScale = 1.0;
  19947. _this.vScale = 1.0;
  19948. _this.uAng = 0;
  19949. _this.vAng = 0;
  19950. _this.wAng = 0;
  19951. _this._isBlocking = true;
  19952. _this.name = url;
  19953. _this.url = url;
  19954. _this._noMipmap = noMipmap;
  19955. _this._invertY = invertY;
  19956. _this._samplingMode = samplingMode;
  19957. _this._buffer = buffer;
  19958. _this._deleteBuffer = deleteBuffer;
  19959. _this._format = format;
  19960. scene = _this.getScene();
  19961. var load = function () {
  19962. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  19963. _this.onLoadObservable.notifyObservers(_this);
  19964. }
  19965. if (onLoad) {
  19966. onLoad();
  19967. }
  19968. if (!_this.isBlocking) {
  19969. scene.resetCachedMaterial();
  19970. }
  19971. };
  19972. if (!url) {
  19973. _this._delayedOnLoad = load;
  19974. _this._delayedOnError = onError;
  19975. return _this;
  19976. }
  19977. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19978. if (!_this._texture) {
  19979. if (!scene.useDelayedTextureLoading) {
  19980. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19981. if (deleteBuffer) {
  19982. delete _this._buffer;
  19983. }
  19984. }
  19985. else {
  19986. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19987. _this._delayedOnLoad = load;
  19988. _this._delayedOnError = onError;
  19989. }
  19990. }
  19991. else {
  19992. if (_this._texture.isReady) {
  19993. BABYLON.Tools.SetImmediate(function () { return load(); });
  19994. }
  19995. else {
  19996. _this._texture.onLoadedCallbacks.push(load);
  19997. }
  19998. }
  19999. return _this;
  20000. }
  20001. Object.defineProperty(Texture.prototype, "noMipmap", {
  20002. get: function () {
  20003. return this._noMipmap;
  20004. },
  20005. enumerable: true,
  20006. configurable: true
  20007. });
  20008. Object.defineProperty(Texture.prototype, "isBlocking", {
  20009. get: function () {
  20010. return this._isBlocking;
  20011. },
  20012. set: function (value) {
  20013. this._isBlocking = value;
  20014. },
  20015. enumerable: true,
  20016. configurable: true
  20017. });
  20018. Object.defineProperty(Texture.prototype, "samplingMode", {
  20019. get: function () {
  20020. return this._samplingMode;
  20021. },
  20022. enumerable: true,
  20023. configurable: true
  20024. });
  20025. Texture.prototype.updateURL = function (url) {
  20026. this.url = url;
  20027. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20028. this.delayLoad();
  20029. };
  20030. Texture.prototype.delayLoad = function () {
  20031. var _this = this;
  20032. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20033. return;
  20034. }
  20035. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20036. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20037. if (!this._texture) {
  20038. 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);
  20039. if (this._deleteBuffer) {
  20040. delete this._buffer;
  20041. }
  20042. }
  20043. else {
  20044. if (this._texture.isReady) {
  20045. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20046. }
  20047. else {
  20048. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  20049. }
  20050. }
  20051. };
  20052. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20053. if (!this._texture) {
  20054. return;
  20055. }
  20056. this._samplingMode = samplingMode;
  20057. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20058. };
  20059. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20060. x *= this.uScale;
  20061. y *= this.vScale;
  20062. x -= 0.5 * this.uScale;
  20063. y -= 0.5 * this.vScale;
  20064. z -= 0.5;
  20065. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20066. t.x += 0.5 * this.uScale + this.uOffset;
  20067. t.y += 0.5 * this.vScale + this.vOffset;
  20068. t.z += 0.5;
  20069. };
  20070. Texture.prototype.getTextureMatrix = function () {
  20071. var _this = this;
  20072. if (this.uOffset === this._cachedUOffset &&
  20073. this.vOffset === this._cachedVOffset &&
  20074. this.uScale === this._cachedUScale &&
  20075. this.vScale === this._cachedVScale &&
  20076. this.uAng === this._cachedUAng &&
  20077. this.vAng === this._cachedVAng &&
  20078. this.wAng === this._cachedWAng) {
  20079. return this._cachedTextureMatrix;
  20080. }
  20081. this._cachedUOffset = this.uOffset;
  20082. this._cachedVOffset = this.vOffset;
  20083. this._cachedUScale = this.uScale;
  20084. this._cachedVScale = this.vScale;
  20085. this._cachedUAng = this.uAng;
  20086. this._cachedVAng = this.vAng;
  20087. this._cachedWAng = this.wAng;
  20088. if (!this._cachedTextureMatrix) {
  20089. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20090. this._rowGenerationMatrix = new BABYLON.Matrix();
  20091. this._t0 = BABYLON.Vector3.Zero();
  20092. this._t1 = BABYLON.Vector3.Zero();
  20093. this._t2 = BABYLON.Vector3.Zero();
  20094. }
  20095. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20096. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20097. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20098. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20099. this._t1.subtractInPlace(this._t0);
  20100. this._t2.subtractInPlace(this._t0);
  20101. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20102. this._cachedTextureMatrix.m[0] = this._t1.x;
  20103. this._cachedTextureMatrix.m[1] = this._t1.y;
  20104. this._cachedTextureMatrix.m[2] = this._t1.z;
  20105. this._cachedTextureMatrix.m[4] = this._t2.x;
  20106. this._cachedTextureMatrix.m[5] = this._t2.y;
  20107. this._cachedTextureMatrix.m[6] = this._t2.z;
  20108. this._cachedTextureMatrix.m[8] = this._t0.x;
  20109. this._cachedTextureMatrix.m[9] = this._t0.y;
  20110. this._cachedTextureMatrix.m[10] = this._t0.z;
  20111. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20112. return mat.hasTexture(_this);
  20113. });
  20114. return this._cachedTextureMatrix;
  20115. };
  20116. Texture.prototype.getReflectionTextureMatrix = function () {
  20117. var _this = this;
  20118. var scene = this.getScene();
  20119. if (this.uOffset === this._cachedUOffset &&
  20120. this.vOffset === this._cachedVOffset &&
  20121. this.uScale === this._cachedUScale &&
  20122. this.vScale === this._cachedVScale &&
  20123. this.coordinatesMode === this._cachedCoordinatesMode) {
  20124. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  20125. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  20126. return this._cachedTextureMatrix;
  20127. }
  20128. }
  20129. else {
  20130. return this._cachedTextureMatrix;
  20131. }
  20132. }
  20133. if (!this._cachedTextureMatrix) {
  20134. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20135. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20136. }
  20137. this._cachedUOffset = this.uOffset;
  20138. this._cachedVOffset = this.vOffset;
  20139. this._cachedUScale = this.uScale;
  20140. this._cachedVScale = this.vScale;
  20141. this._cachedCoordinatesMode = this.coordinatesMode;
  20142. switch (this.coordinatesMode) {
  20143. case Texture.PLANAR_MODE:
  20144. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20145. this._cachedTextureMatrix[0] = this.uScale;
  20146. this._cachedTextureMatrix[5] = this.vScale;
  20147. this._cachedTextureMatrix[12] = this.uOffset;
  20148. this._cachedTextureMatrix[13] = this.vOffset;
  20149. break;
  20150. case Texture.PROJECTION_MODE:
  20151. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20152. this._projectionModeMatrix.m[0] = 0.5;
  20153. this._projectionModeMatrix.m[5] = -0.5;
  20154. this._projectionModeMatrix.m[10] = 0.0;
  20155. this._projectionModeMatrix.m[12] = 0.5;
  20156. this._projectionModeMatrix.m[13] = 0.5;
  20157. this._projectionModeMatrix.m[14] = 1.0;
  20158. this._projectionModeMatrix.m[15] = 1.0;
  20159. var projectionMatrix = scene.getProjectionMatrix();
  20160. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  20161. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20162. break;
  20163. default:
  20164. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20165. break;
  20166. }
  20167. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20168. return (mat.getActiveTextures().indexOf(_this) !== -1);
  20169. });
  20170. return this._cachedTextureMatrix;
  20171. };
  20172. Texture.prototype.clone = function () {
  20173. var _this = this;
  20174. return BABYLON.SerializationHelper.Clone(function () {
  20175. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20176. }, this);
  20177. };
  20178. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  20179. get: function () {
  20180. if (!this._onLoadObservable) {
  20181. this._onLoadObservable = new BABYLON.Observable();
  20182. }
  20183. return this._onLoadObservable;
  20184. },
  20185. enumerable: true,
  20186. configurable: true
  20187. });
  20188. Texture.prototype.serialize = function () {
  20189. var serializationObject = _super.prototype.serialize.call(this);
  20190. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  20191. serializationObject.base64String = this._buffer;
  20192. serializationObject.name = serializationObject.name.replace("data:", "");
  20193. }
  20194. return serializationObject;
  20195. };
  20196. Texture.prototype.getClassName = function () {
  20197. return "Texture";
  20198. };
  20199. Texture.prototype.dispose = function () {
  20200. _super.prototype.dispose.call(this);
  20201. if (this.onLoadObservable) {
  20202. this.onLoadObservable.clear();
  20203. this._onLoadObservable = null;
  20204. }
  20205. this._delayedOnLoad = null;
  20206. this._delayedOnError = null;
  20207. };
  20208. // Statics
  20209. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20210. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20211. if (onLoad === void 0) { onLoad = null; }
  20212. if (onError === void 0) { onError = null; }
  20213. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20214. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  20215. };
  20216. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20217. if (parsedTexture.customType) {
  20218. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  20219. // Update Sampling Mode
  20220. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  20221. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  20222. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  20223. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  20224. }
  20225. }
  20226. return parsedCustomTexture;
  20227. }
  20228. if (parsedTexture.isCube) {
  20229. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20230. }
  20231. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20232. return null;
  20233. }
  20234. var texture = BABYLON.SerializationHelper.Parse(function () {
  20235. if (parsedTexture.mirrorPlane) {
  20236. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20237. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20238. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20239. return mirrorTexture;
  20240. }
  20241. else if (parsedTexture.isRenderTarget) {
  20242. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20243. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20244. return renderTargetTexture;
  20245. }
  20246. else {
  20247. var texture;
  20248. if (parsedTexture.base64String) {
  20249. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20250. }
  20251. else {
  20252. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20253. }
  20254. return texture;
  20255. }
  20256. }, parsedTexture, scene);
  20257. // Update Sampling Mode
  20258. if (parsedTexture.samplingMode) {
  20259. var sampling = parsedTexture.samplingMode;
  20260. if (texture._samplingMode !== sampling) {
  20261. texture.updateSamplingMode(sampling);
  20262. }
  20263. }
  20264. // Animations
  20265. if (parsedTexture.animations) {
  20266. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20267. var parsedAnimation = parsedTexture.animations[animationIndex];
  20268. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20269. }
  20270. }
  20271. return texture;
  20272. };
  20273. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20274. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20275. if (noMipmap === void 0) { noMipmap = false; }
  20276. if (invertY === void 0) { invertY = true; }
  20277. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20278. if (onLoad === void 0) { onLoad = null; }
  20279. if (onError === void 0) { onError = null; }
  20280. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20281. if (name.substr(0, 5) !== "data:") {
  20282. name = "data:" + name;
  20283. }
  20284. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  20285. };
  20286. // Constants
  20287. Texture.NEAREST_SAMPLINGMODE = 1;
  20288. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  20289. Texture.BILINEAR_SAMPLINGMODE = 2;
  20290. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  20291. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20292. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  20293. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  20294. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  20295. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  20296. Texture.NEAREST_LINEAR = 7;
  20297. Texture.NEAREST_NEAREST = 8;
  20298. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  20299. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  20300. Texture.LINEAR_LINEAR = 11;
  20301. Texture.LINEAR_NEAREST = 12;
  20302. Texture.EXPLICIT_MODE = 0;
  20303. Texture.SPHERICAL_MODE = 1;
  20304. Texture.PLANAR_MODE = 2;
  20305. Texture.CUBIC_MODE = 3;
  20306. Texture.PROJECTION_MODE = 4;
  20307. Texture.SKYBOX_MODE = 5;
  20308. Texture.INVCUBIC_MODE = 6;
  20309. Texture.EQUIRECTANGULAR_MODE = 7;
  20310. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20311. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  20312. Texture.CLAMP_ADDRESSMODE = 0;
  20313. Texture.WRAP_ADDRESSMODE = 1;
  20314. Texture.MIRROR_ADDRESSMODE = 2;
  20315. __decorate([
  20316. BABYLON.serialize()
  20317. ], Texture.prototype, "url", void 0);
  20318. __decorate([
  20319. BABYLON.serialize()
  20320. ], Texture.prototype, "uOffset", void 0);
  20321. __decorate([
  20322. BABYLON.serialize()
  20323. ], Texture.prototype, "vOffset", void 0);
  20324. __decorate([
  20325. BABYLON.serialize()
  20326. ], Texture.prototype, "uScale", void 0);
  20327. __decorate([
  20328. BABYLON.serialize()
  20329. ], Texture.prototype, "vScale", void 0);
  20330. __decorate([
  20331. BABYLON.serialize()
  20332. ], Texture.prototype, "uAng", void 0);
  20333. __decorate([
  20334. BABYLON.serialize()
  20335. ], Texture.prototype, "vAng", void 0);
  20336. __decorate([
  20337. BABYLON.serialize()
  20338. ], Texture.prototype, "wAng", void 0);
  20339. __decorate([
  20340. BABYLON.serialize()
  20341. ], Texture.prototype, "isBlocking", null);
  20342. return Texture;
  20343. }(BABYLON.BaseTexture));
  20344. BABYLON.Texture = Texture;
  20345. })(BABYLON || (BABYLON = {}));
  20346. //# sourceMappingURL=babylon.texture.js.map
  20347. var BABYLON;
  20348. (function (BABYLON) {
  20349. var _InstancesBatch = (function () {
  20350. function _InstancesBatch() {
  20351. this.mustReturn = false;
  20352. this.visibleInstances = new Array();
  20353. this.renderSelf = new Array();
  20354. }
  20355. return _InstancesBatch;
  20356. }());
  20357. BABYLON._InstancesBatch = _InstancesBatch;
  20358. var Mesh = (function (_super) {
  20359. __extends(Mesh, _super);
  20360. /**
  20361. * @constructor
  20362. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  20363. * @param {Scene} scene The scene to add this mesh to.
  20364. * @param {Node} parent The parent of this mesh, if it has one
  20365. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  20366. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  20367. * When false, achieved by calling a clone(), also passing False.
  20368. * This will make creation of children, recursive.
  20369. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  20370. */
  20371. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  20372. if (parent === void 0) { parent = null; }
  20373. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20374. var _this = _super.call(this, name, scene) || this;
  20375. // Events
  20376. /**
  20377. * An event triggered before rendering the mesh
  20378. * @type {BABYLON.Observable}
  20379. */
  20380. _this.onBeforeRenderObservable = new BABYLON.Observable();
  20381. /**
  20382. * An event triggered after rendering the mesh
  20383. * @type {BABYLON.Observable}
  20384. */
  20385. _this.onAfterRenderObservable = new BABYLON.Observable();
  20386. /**
  20387. * An event triggered before drawing the mesh
  20388. * @type {BABYLON.Observable}
  20389. */
  20390. _this.onBeforeDrawObservable = new BABYLON.Observable();
  20391. // Members
  20392. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20393. _this.instances = new Array();
  20394. _this._LODLevels = new Array();
  20395. _this._visibleInstances = {};
  20396. _this._renderIdForInstances = new Array();
  20397. _this._batchCache = new _InstancesBatch();
  20398. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  20399. _this._sideOrientation = Mesh._DEFAULTSIDE;
  20400. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  20401. // Will be used to save a source mesh reference, If any
  20402. _this._source = null;
  20403. if (source) {
  20404. // Source mesh
  20405. _this._source = source;
  20406. // Geometry
  20407. if (source._geometry) {
  20408. source._geometry.applyToMesh(_this);
  20409. }
  20410. // Deep copy
  20411. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  20412. // Parent
  20413. _this.parent = source.parent;
  20414. // Pivot
  20415. _this.setPivotMatrix(source.getPivotMatrix());
  20416. _this.id = name + "." + source.id;
  20417. // Material
  20418. _this.material = source.material;
  20419. var index;
  20420. if (!doNotCloneChildren) {
  20421. // Children
  20422. for (index = 0; index < scene.meshes.length; index++) {
  20423. var mesh = scene.meshes[index];
  20424. if (mesh.parent === source) {
  20425. // doNotCloneChildren is always going to be False
  20426. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20427. }
  20428. }
  20429. }
  20430. // Physics clone
  20431. var physicsEngine = _this.getScene().getPhysicsEngine();
  20432. if (clonePhysicsImpostor && physicsEngine) {
  20433. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20434. if (impostor) {
  20435. _this.physicsImpostor = impostor.clone(_this);
  20436. }
  20437. }
  20438. // Particles
  20439. for (index = 0; index < scene.particleSystems.length; index++) {
  20440. var system = scene.particleSystems[index];
  20441. if (system.emitter === source) {
  20442. system.clone(system.name, _this);
  20443. }
  20444. }
  20445. _this.computeWorldMatrix(true);
  20446. }
  20447. // Parent
  20448. if (parent !== null) {
  20449. _this.parent = parent;
  20450. }
  20451. return _this;
  20452. }
  20453. Object.defineProperty(Mesh, "FRONTSIDE", {
  20454. /**
  20455. * Mesh side orientation : usually the external or front surface
  20456. */
  20457. get: function () {
  20458. return Mesh._FRONTSIDE;
  20459. },
  20460. enumerable: true,
  20461. configurable: true
  20462. });
  20463. Object.defineProperty(Mesh, "BACKSIDE", {
  20464. /**
  20465. * Mesh side orientation : usually the internal or back surface
  20466. */
  20467. get: function () {
  20468. return Mesh._BACKSIDE;
  20469. },
  20470. enumerable: true,
  20471. configurable: true
  20472. });
  20473. Object.defineProperty(Mesh, "DOUBLESIDE", {
  20474. /**
  20475. * Mesh side orientation : both internal and external or front and back surfaces
  20476. */
  20477. get: function () {
  20478. return Mesh._DOUBLESIDE;
  20479. },
  20480. enumerable: true,
  20481. configurable: true
  20482. });
  20483. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  20484. /**
  20485. * Mesh side orientation : by default, `FRONTSIDE`
  20486. */
  20487. get: function () {
  20488. return Mesh._DEFAULTSIDE;
  20489. },
  20490. enumerable: true,
  20491. configurable: true
  20492. });
  20493. Object.defineProperty(Mesh, "NO_CAP", {
  20494. /**
  20495. * Mesh cap setting : no cap
  20496. */
  20497. get: function () {
  20498. return Mesh._NO_CAP;
  20499. },
  20500. enumerable: true,
  20501. configurable: true
  20502. });
  20503. Object.defineProperty(Mesh, "CAP_START", {
  20504. /**
  20505. * Mesh cap setting : one cap at the beginning of the mesh
  20506. */
  20507. get: function () {
  20508. return Mesh._CAP_START;
  20509. },
  20510. enumerable: true,
  20511. configurable: true
  20512. });
  20513. Object.defineProperty(Mesh, "CAP_END", {
  20514. /**
  20515. * Mesh cap setting : one cap at the end of the mesh
  20516. */
  20517. get: function () {
  20518. return Mesh._CAP_END;
  20519. },
  20520. enumerable: true,
  20521. configurable: true
  20522. });
  20523. Object.defineProperty(Mesh, "CAP_ALL", {
  20524. /**
  20525. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  20526. */
  20527. get: function () {
  20528. return Mesh._CAP_ALL;
  20529. },
  20530. enumerable: true,
  20531. configurable: true
  20532. });
  20533. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  20534. set: function (callback) {
  20535. if (this._onBeforeDrawObserver) {
  20536. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  20537. }
  20538. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  20539. },
  20540. enumerable: true,
  20541. configurable: true
  20542. });
  20543. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  20544. get: function () {
  20545. return this._morphTargetManager;
  20546. },
  20547. set: function (value) {
  20548. if (this._morphTargetManager === value) {
  20549. return;
  20550. }
  20551. this._morphTargetManager = value;
  20552. this._syncGeometryWithMorphTargetManager();
  20553. },
  20554. enumerable: true,
  20555. configurable: true
  20556. });
  20557. Object.defineProperty(Mesh.prototype, "source", {
  20558. get: function () {
  20559. return this._source;
  20560. },
  20561. enumerable: true,
  20562. configurable: true
  20563. });
  20564. // Methods
  20565. /**
  20566. * Returns the string "Mesh".
  20567. */
  20568. Mesh.prototype.getClassName = function () {
  20569. return "Mesh";
  20570. };
  20571. /**
  20572. * Returns a string.
  20573. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20574. */
  20575. Mesh.prototype.toString = function (fullDetails) {
  20576. var ret = _super.prototype.toString.call(this, fullDetails);
  20577. ret += ", n vertices: " + this.getTotalVertices();
  20578. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  20579. if (this.animations) {
  20580. for (var i = 0; i < this.animations.length; i++) {
  20581. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20582. }
  20583. }
  20584. if (fullDetails) {
  20585. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  20586. }
  20587. return ret;
  20588. };
  20589. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  20590. /**
  20591. * True if the mesh has some Levels Of Details (LOD).
  20592. * Returns a boolean.
  20593. */
  20594. get: function () {
  20595. return this._LODLevels.length > 0;
  20596. },
  20597. enumerable: true,
  20598. configurable: true
  20599. });
  20600. Mesh.prototype._sortLODLevels = function () {
  20601. this._LODLevels.sort(function (a, b) {
  20602. if (a.distance < b.distance) {
  20603. return 1;
  20604. }
  20605. if (a.distance > b.distance) {
  20606. return -1;
  20607. }
  20608. return 0;
  20609. });
  20610. };
  20611. /**
  20612. * Add a mesh as LOD level triggered at the given distance.
  20613. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20614. * @param {number} distance The distance from the center of the object to show this level
  20615. * @param {Mesh} mesh The mesh to be added as LOD level
  20616. * @return {Mesh} This mesh (for chaining)
  20617. */
  20618. Mesh.prototype.addLODLevel = function (distance, mesh) {
  20619. if (mesh && mesh._masterMesh) {
  20620. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  20621. return this;
  20622. }
  20623. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  20624. this._LODLevels.push(level);
  20625. if (mesh) {
  20626. mesh._masterMesh = this;
  20627. }
  20628. this._sortLODLevels();
  20629. return this;
  20630. };
  20631. /**
  20632. * Returns the LOD level mesh at the passed distance or null if not found.
  20633. * It is related to the method `addLODLevel(distance, mesh)`.
  20634. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20635. * Returns an object Mesh or `null`.
  20636. */
  20637. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  20638. for (var index = 0; index < this._LODLevels.length; index++) {
  20639. var level = this._LODLevels[index];
  20640. if (level.distance === distance) {
  20641. return level.mesh;
  20642. }
  20643. }
  20644. return null;
  20645. };
  20646. /**
  20647. * Remove a mesh from the LOD array
  20648. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20649. * @param {Mesh} mesh The mesh to be removed.
  20650. * @return {Mesh} This mesh (for chaining)
  20651. */
  20652. Mesh.prototype.removeLODLevel = function (mesh) {
  20653. for (var index = 0; index < this._LODLevels.length; index++) {
  20654. if (this._LODLevels[index].mesh === mesh) {
  20655. this._LODLevels.splice(index, 1);
  20656. if (mesh) {
  20657. mesh._masterMesh = null;
  20658. }
  20659. }
  20660. }
  20661. this._sortLODLevels();
  20662. return this;
  20663. };
  20664. /**
  20665. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  20666. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20667. */
  20668. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  20669. if (!this._LODLevels || this._LODLevels.length === 0) {
  20670. return this;
  20671. }
  20672. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  20673. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  20674. if (this.onLODLevelSelection) {
  20675. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  20676. }
  20677. return this;
  20678. }
  20679. for (var index = 0; index < this._LODLevels.length; index++) {
  20680. var level = this._LODLevels[index];
  20681. if (level.distance < distanceToCamera) {
  20682. if (level.mesh) {
  20683. level.mesh._preActivate();
  20684. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20685. }
  20686. if (this.onLODLevelSelection) {
  20687. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  20688. }
  20689. return level.mesh;
  20690. }
  20691. }
  20692. if (this.onLODLevelSelection) {
  20693. this.onLODLevelSelection(distanceToCamera, this, this);
  20694. }
  20695. return this;
  20696. };
  20697. Object.defineProperty(Mesh.prototype, "geometry", {
  20698. /**
  20699. * Returns the mesh internal Geometry object.
  20700. */
  20701. get: function () {
  20702. return this._geometry;
  20703. },
  20704. enumerable: true,
  20705. configurable: true
  20706. });
  20707. /**
  20708. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  20709. */
  20710. Mesh.prototype.getTotalVertices = function () {
  20711. if (!this._geometry) {
  20712. return 0;
  20713. }
  20714. return this._geometry.getTotalVertices();
  20715. };
  20716. /**
  20717. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  20718. * 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.
  20719. * You can force the copy with forceCopy === true
  20720. * Returns null if the mesh has no geometry or no vertex buffer.
  20721. * Possible `kind` values :
  20722. * - BABYLON.VertexBuffer.PositionKind
  20723. * - BABYLON.VertexBuffer.UVKind
  20724. * - BABYLON.VertexBuffer.UV2Kind
  20725. * - BABYLON.VertexBuffer.UV3Kind
  20726. * - BABYLON.VertexBuffer.UV4Kind
  20727. * - BABYLON.VertexBuffer.UV5Kind
  20728. * - BABYLON.VertexBuffer.UV6Kind
  20729. * - BABYLON.VertexBuffer.ColorKind
  20730. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20731. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20732. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20733. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20734. */
  20735. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  20736. if (!this._geometry) {
  20737. return null;
  20738. }
  20739. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  20740. };
  20741. /**
  20742. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  20743. * Returns `undefined` if the mesh has no geometry.
  20744. * Possible `kind` values :
  20745. * - BABYLON.VertexBuffer.PositionKind
  20746. * - BABYLON.VertexBuffer.UVKind
  20747. * - BABYLON.VertexBuffer.UV2Kind
  20748. * - BABYLON.VertexBuffer.UV3Kind
  20749. * - BABYLON.VertexBuffer.UV4Kind
  20750. * - BABYLON.VertexBuffer.UV5Kind
  20751. * - BABYLON.VertexBuffer.UV6Kind
  20752. * - BABYLON.VertexBuffer.ColorKind
  20753. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20754. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20755. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20756. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20757. */
  20758. Mesh.prototype.getVertexBuffer = function (kind) {
  20759. if (!this._geometry) {
  20760. return undefined;
  20761. }
  20762. return this._geometry.getVertexBuffer(kind);
  20763. };
  20764. /**
  20765. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  20766. * Possible `kind` values :
  20767. * - BABYLON.VertexBuffer.PositionKind
  20768. * - BABYLON.VertexBuffer.UVKind
  20769. * - BABYLON.VertexBuffer.UV2Kind
  20770. * - BABYLON.VertexBuffer.UV3Kind
  20771. * - BABYLON.VertexBuffer.UV4Kind
  20772. * - BABYLON.VertexBuffer.UV5Kind
  20773. * - BABYLON.VertexBuffer.UV6Kind
  20774. * - BABYLON.VertexBuffer.ColorKind
  20775. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20776. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20777. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20778. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20779. */
  20780. Mesh.prototype.isVerticesDataPresent = function (kind) {
  20781. if (!this._geometry) {
  20782. if (this._delayInfo) {
  20783. return this._delayInfo.indexOf(kind) !== -1;
  20784. }
  20785. return false;
  20786. }
  20787. return this._geometry.isVerticesDataPresent(kind);
  20788. };
  20789. /**
  20790. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20791. * Possible `kind` values :
  20792. * - BABYLON.VertexBuffer.PositionKind
  20793. * - BABYLON.VertexBuffer.UVKind
  20794. * - BABYLON.VertexBuffer.UV2Kind
  20795. * - BABYLON.VertexBuffer.UV3Kind
  20796. * - BABYLON.VertexBuffer.UV4Kind
  20797. * - BABYLON.VertexBuffer.UV5Kind
  20798. * - BABYLON.VertexBuffer.UV6Kind
  20799. * - BABYLON.VertexBuffer.ColorKind
  20800. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20801. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20802. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20803. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20804. */
  20805. Mesh.prototype.getVerticesDataKinds = function () {
  20806. if (!this._geometry) {
  20807. var result = [];
  20808. if (this._delayInfo) {
  20809. this._delayInfo.forEach(function (kind, index, array) {
  20810. result.push(kind);
  20811. });
  20812. }
  20813. return result;
  20814. }
  20815. return this._geometry.getVerticesDataKinds();
  20816. };
  20817. /**
  20818. * Returns a positive integer : the total number of indices in this mesh geometry.
  20819. * Returns zero if the mesh has no geometry.
  20820. */
  20821. Mesh.prototype.getTotalIndices = function () {
  20822. if (!this._geometry) {
  20823. return 0;
  20824. }
  20825. return this._geometry.getTotalIndices();
  20826. };
  20827. /**
  20828. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20829. * 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.
  20830. * Returns an empty array if the mesh has no geometry.
  20831. */
  20832. Mesh.prototype.getIndices = function (copyWhenShared) {
  20833. if (!this._geometry) {
  20834. return [];
  20835. }
  20836. return this._geometry.getIndices(copyWhenShared);
  20837. };
  20838. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20839. get: function () {
  20840. return this._masterMesh !== null && this._masterMesh !== undefined;
  20841. },
  20842. enumerable: true,
  20843. configurable: true
  20844. });
  20845. /**
  20846. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20847. */
  20848. Mesh.prototype.isReady = function () {
  20849. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20850. return false;
  20851. }
  20852. return _super.prototype.isReady.call(this);
  20853. };
  20854. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20855. get: function () {
  20856. return this._sideOrientation;
  20857. },
  20858. /**
  20859. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20860. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20861. */
  20862. set: function (sideO) {
  20863. this._sideOrientation = sideO;
  20864. },
  20865. enumerable: true,
  20866. configurable: true
  20867. });
  20868. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20869. /**
  20870. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20871. * This property is pertinent only for updatable parametric shapes.
  20872. */
  20873. get: function () {
  20874. return this._areNormalsFrozen;
  20875. },
  20876. enumerable: true,
  20877. configurable: true
  20878. });
  20879. /**
  20880. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20881. * It has no effect at all on other shapes.
  20882. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20883. * Returns the Mesh.
  20884. */
  20885. Mesh.prototype.freezeNormals = function () {
  20886. this._areNormalsFrozen = true;
  20887. return this;
  20888. };
  20889. /**
  20890. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20891. * It has no effect at all on other shapes.
  20892. * It reactivates the mesh normals computation if it was previously frozen.
  20893. * Returns the Mesh.
  20894. */
  20895. Mesh.prototype.unfreezeNormals = function () {
  20896. this._areNormalsFrozen = false;
  20897. return this;
  20898. };
  20899. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20900. /**
  20901. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20902. */
  20903. set: function (count) {
  20904. this._overridenInstanceCount = count;
  20905. },
  20906. enumerable: true,
  20907. configurable: true
  20908. });
  20909. // Methods
  20910. Mesh.prototype._preActivate = function () {
  20911. var sceneRenderId = this.getScene().getRenderId();
  20912. if (this._preActivateId === sceneRenderId) {
  20913. return this;
  20914. }
  20915. this._preActivateId = sceneRenderId;
  20916. this._visibleInstances = null;
  20917. return this;
  20918. };
  20919. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20920. if (this._visibleInstances) {
  20921. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20922. }
  20923. return this;
  20924. };
  20925. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20926. if (!this._visibleInstances) {
  20927. this._visibleInstances = {};
  20928. this._visibleInstances.defaultRenderId = renderId;
  20929. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20930. }
  20931. if (!this._visibleInstances[renderId]) {
  20932. this._visibleInstances[renderId] = new Array();
  20933. }
  20934. this._visibleInstances[renderId].push(instance);
  20935. return this;
  20936. };
  20937. /**
  20938. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20939. * This means the mesh underlying bounding box and sphere are recomputed.
  20940. * Returns the Mesh.
  20941. */
  20942. Mesh.prototype.refreshBoundingInfo = function () {
  20943. if (this._boundingInfo.isLocked) {
  20944. return;
  20945. }
  20946. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20947. if (data) {
  20948. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20949. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20950. }
  20951. if (this.subMeshes) {
  20952. for (var index = 0; index < this.subMeshes.length; index++) {
  20953. this.subMeshes[index].refreshBoundingInfo();
  20954. }
  20955. }
  20956. this._updateBoundingInfo();
  20957. return this;
  20958. };
  20959. Mesh.prototype._createGlobalSubMesh = function (force) {
  20960. var totalVertices = this.getTotalVertices();
  20961. if (!totalVertices || !this.getIndices()) {
  20962. return null;
  20963. }
  20964. // Check if we need to recreate the submeshes
  20965. if (this.subMeshes && this.subMeshes.length > 0) {
  20966. var totalIndices = this.getIndices().length;
  20967. var needToRecreate = false;
  20968. if (force) {
  20969. needToRecreate = true;
  20970. }
  20971. else {
  20972. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20973. var submesh = _a[_i];
  20974. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  20975. needToRecreate = true;
  20976. break;
  20977. }
  20978. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  20979. needToRecreate = true;
  20980. break;
  20981. }
  20982. }
  20983. }
  20984. if (!needToRecreate) {
  20985. return;
  20986. }
  20987. }
  20988. this.releaseSubMeshes();
  20989. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20990. };
  20991. Mesh.prototype.subdivide = function (count) {
  20992. if (count < 1) {
  20993. return;
  20994. }
  20995. var totalIndices = this.getTotalIndices();
  20996. var subdivisionSize = (totalIndices / count) | 0;
  20997. var offset = 0;
  20998. // Ensure that subdivisionSize is a multiple of 3
  20999. while (subdivisionSize % 3 !== 0) {
  21000. subdivisionSize++;
  21001. }
  21002. this.releaseSubMeshes();
  21003. for (var index = 0; index < count; index++) {
  21004. if (offset >= totalIndices) {
  21005. break;
  21006. }
  21007. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21008. offset += subdivisionSize;
  21009. }
  21010. this.synchronizeInstances();
  21011. };
  21012. /**
  21013. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21014. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21015. * The `data` are either a numeric array either a Float32Array.
  21016. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21017. * 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).
  21018. * Note that a new underlying VertexBuffer object is created each call.
  21019. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21020. *
  21021. * Possible `kind` values :
  21022. * - BABYLON.VertexBuffer.PositionKind
  21023. * - BABYLON.VertexBuffer.UVKind
  21024. * - BABYLON.VertexBuffer.UV2Kind
  21025. * - BABYLON.VertexBuffer.UV3Kind
  21026. * - BABYLON.VertexBuffer.UV4Kind
  21027. * - BABYLON.VertexBuffer.UV5Kind
  21028. * - BABYLON.VertexBuffer.UV6Kind
  21029. * - BABYLON.VertexBuffer.ColorKind
  21030. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21031. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21032. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21033. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21034. *
  21035. * Returns the Mesh.
  21036. */
  21037. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21038. if (!this._geometry) {
  21039. var vertexData = new BABYLON.VertexData();
  21040. vertexData.set(data, kind);
  21041. var scene = this.getScene();
  21042. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21043. }
  21044. else {
  21045. this._geometry.setVerticesData(kind, data, updatable, stride);
  21046. }
  21047. return this;
  21048. };
  21049. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21050. if (updatable === void 0) { updatable = true; }
  21051. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21052. return;
  21053. }
  21054. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21055. };
  21056. /**
  21057. * Sets the mesh VertexBuffer.
  21058. * Returns the Mesh.
  21059. */
  21060. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21061. if (!this._geometry) {
  21062. var scene = this.getScene();
  21063. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21064. }
  21065. this._geometry.setVerticesBuffer(buffer);
  21066. return this;
  21067. };
  21068. /**
  21069. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21070. * If the mesh has no geometry, it is simply returned as it is.
  21071. * The `data` are either a numeric array either a Float32Array.
  21072. * No new underlying VertexBuffer object is created.
  21073. * 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.
  21074. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21075. *
  21076. * Possible `kind` values :
  21077. * - BABYLON.VertexBuffer.PositionKind
  21078. * - BABYLON.VertexBuffer.UVKind
  21079. * - BABYLON.VertexBuffer.UV2Kind
  21080. * - BABYLON.VertexBuffer.UV3Kind
  21081. * - BABYLON.VertexBuffer.UV4Kind
  21082. * - BABYLON.VertexBuffer.UV5Kind
  21083. * - BABYLON.VertexBuffer.UV6Kind
  21084. * - BABYLON.VertexBuffer.ColorKind
  21085. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21086. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21087. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21088. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21089. *
  21090. * Returns the Mesh.
  21091. */
  21092. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21093. if (!this._geometry) {
  21094. return;
  21095. }
  21096. if (!makeItUnique) {
  21097. this._geometry.updateVerticesData(kind, data, updateExtends);
  21098. }
  21099. else {
  21100. this.makeGeometryUnique();
  21101. this.updateVerticesData(kind, data, updateExtends, false);
  21102. }
  21103. return this;
  21104. };
  21105. /**
  21106. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21107. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21108. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21109. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21110. * Returns the Mesh.
  21111. */
  21112. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21113. if (computeNormals === void 0) { computeNormals = true; }
  21114. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21115. positionFunction(positions);
  21116. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21117. if (computeNormals) {
  21118. var indices = this.getIndices();
  21119. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21120. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21121. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21122. }
  21123. return this;
  21124. };
  21125. /**
  21126. * Creates a un-shared specific occurence of the geometry for the mesh.
  21127. * Returns the Mesh.
  21128. */
  21129. Mesh.prototype.makeGeometryUnique = function () {
  21130. if (!this._geometry) {
  21131. return;
  21132. }
  21133. var oldGeometry = this._geometry;
  21134. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21135. oldGeometry.releaseForMesh(this, true);
  21136. geometry.applyToMesh(this);
  21137. return this;
  21138. };
  21139. /**
  21140. * Sets the mesh indices.
  21141. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21142. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21143. * This method creates a new index buffer each call.
  21144. * Returns the Mesh.
  21145. */
  21146. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21147. if (!this._geometry) {
  21148. var vertexData = new BABYLON.VertexData();
  21149. vertexData.indices = indices;
  21150. var scene = this.getScene();
  21151. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21152. }
  21153. else {
  21154. this._geometry.setIndices(indices, totalVertices);
  21155. }
  21156. return this;
  21157. };
  21158. /**
  21159. * Invert the geometry to move from a right handed system to a left handed one.
  21160. * Returns the Mesh.
  21161. */
  21162. Mesh.prototype.toLeftHanded = function () {
  21163. if (!this._geometry) {
  21164. return;
  21165. }
  21166. this._geometry.toLeftHanded();
  21167. return this;
  21168. };
  21169. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21170. var engine = this.getScene().getEngine();
  21171. // Wireframe
  21172. var indexToBind;
  21173. if (this._unIndexed) {
  21174. indexToBind = null;
  21175. }
  21176. else {
  21177. switch (fillMode) {
  21178. case BABYLON.Material.PointFillMode:
  21179. indexToBind = null;
  21180. break;
  21181. case BABYLON.Material.WireFrameFillMode:
  21182. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21183. break;
  21184. default:
  21185. case BABYLON.Material.TriangleFillMode:
  21186. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21187. break;
  21188. }
  21189. }
  21190. // VBOs
  21191. this._geometry._bind(effect, indexToBind);
  21192. return this;
  21193. };
  21194. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21195. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21196. return this;
  21197. }
  21198. this.onBeforeDrawObservable.notifyObservers(this);
  21199. var engine = this.getScene().getEngine();
  21200. // Draw order
  21201. switch (fillMode) {
  21202. case BABYLON.Material.PointFillMode:
  21203. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21204. break;
  21205. case BABYLON.Material.WireFrameFillMode:
  21206. if (this._unIndexed) {
  21207. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21208. }
  21209. else {
  21210. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  21211. }
  21212. break;
  21213. default:
  21214. if (this._unIndexed) {
  21215. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21216. }
  21217. else {
  21218. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21219. }
  21220. }
  21221. return this;
  21222. };
  21223. /**
  21224. * Registers for this mesh a javascript function called just before the rendering process.
  21225. * This function is passed the current mesh.
  21226. * Return the Mesh.
  21227. */
  21228. Mesh.prototype.registerBeforeRender = function (func) {
  21229. this.onBeforeRenderObservable.add(func);
  21230. return this;
  21231. };
  21232. /**
  21233. * Disposes a previously registered javascript function called before the rendering.
  21234. * This function is passed the current mesh.
  21235. * Returns the Mesh.
  21236. */
  21237. Mesh.prototype.unregisterBeforeRender = function (func) {
  21238. this.onBeforeRenderObservable.removeCallback(func);
  21239. return this;
  21240. };
  21241. /**
  21242. * Registers for this mesh a javascript function called just after the rendering is complete.
  21243. * This function is passed the current mesh.
  21244. * Returns the Mesh.
  21245. */
  21246. Mesh.prototype.registerAfterRender = function (func) {
  21247. this.onAfterRenderObservable.add(func);
  21248. return this;
  21249. };
  21250. /**
  21251. * Disposes a previously registered javascript function called after the rendering.
  21252. * This function is passed the current mesh.
  21253. * Return the Mesh.
  21254. */
  21255. Mesh.prototype.unregisterAfterRender = function (func) {
  21256. this.onAfterRenderObservable.removeCallback(func);
  21257. return this;
  21258. };
  21259. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21260. var scene = this.getScene();
  21261. this._batchCache.mustReturn = false;
  21262. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21263. this._batchCache.visibleInstances[subMeshId] = null;
  21264. if (this._visibleInstances) {
  21265. var currentRenderId = scene.getRenderId();
  21266. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21267. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21268. var selfRenderId = this._renderId;
  21269. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21270. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21271. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21272. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21273. }
  21274. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21275. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21276. this._batchCache.mustReturn = true;
  21277. return this._batchCache;
  21278. }
  21279. if (currentRenderId !== selfRenderId) {
  21280. this._batchCache.renderSelf[subMeshId] = false;
  21281. }
  21282. }
  21283. this._renderIdForInstances[subMeshId] = currentRenderId;
  21284. }
  21285. return this._batchCache;
  21286. };
  21287. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21288. var visibleInstances = batch.visibleInstances[subMesh._id];
  21289. var matricesCount = visibleInstances.length + 1;
  21290. var bufferSize = matricesCount * 16 * 4;
  21291. var currentInstancesBufferSize = this._instancesBufferSize;
  21292. var instancesBuffer = this._instancesBuffer;
  21293. while (this._instancesBufferSize < bufferSize) {
  21294. this._instancesBufferSize *= 2;
  21295. }
  21296. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21297. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21298. }
  21299. var offset = 0;
  21300. var instancesCount = 0;
  21301. var world = this.getWorldMatrix();
  21302. if (batch.renderSelf[subMesh._id]) {
  21303. world.copyToArray(this._instancesData, offset);
  21304. offset += 16;
  21305. instancesCount++;
  21306. }
  21307. if (visibleInstances) {
  21308. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21309. var instance = visibleInstances[instanceIndex];
  21310. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21311. offset += 16;
  21312. instancesCount++;
  21313. }
  21314. }
  21315. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21316. if (instancesBuffer) {
  21317. instancesBuffer.dispose();
  21318. }
  21319. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21320. this._instancesBuffer = instancesBuffer;
  21321. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21322. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21323. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21324. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21325. }
  21326. else {
  21327. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21328. }
  21329. this.geometry._bind(effect);
  21330. this._draw(subMesh, fillMode, instancesCount);
  21331. engine.unbindInstanceAttributes();
  21332. return this;
  21333. };
  21334. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21335. var scene = this.getScene();
  21336. var engine = scene.getEngine();
  21337. if (hardwareInstancedRendering) {
  21338. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21339. }
  21340. else {
  21341. if (batch.renderSelf[subMesh._id]) {
  21342. // Draw
  21343. if (onBeforeDraw) {
  21344. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21345. }
  21346. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  21347. }
  21348. if (batch.visibleInstances[subMesh._id]) {
  21349. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21350. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21351. // World
  21352. var world = instance.getWorldMatrix();
  21353. if (onBeforeDraw) {
  21354. onBeforeDraw(true, world, effectiveMaterial);
  21355. }
  21356. // Draw
  21357. this._draw(subMesh, fillMode);
  21358. }
  21359. }
  21360. }
  21361. return this;
  21362. };
  21363. /**
  21364. * Triggers the draw call for the mesh.
  21365. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  21366. * Returns the Mesh.
  21367. */
  21368. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  21369. var scene = this.getScene();
  21370. // Managing instances
  21371. var batch = this._getInstancesRenderList(subMesh._id);
  21372. if (batch.mustReturn) {
  21373. return this;
  21374. }
  21375. // Checking geometry state
  21376. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21377. return this;
  21378. }
  21379. var callbackIndex;
  21380. this.onBeforeRenderObservable.notifyObservers(this);
  21381. var engine = scene.getEngine();
  21382. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  21383. // Material
  21384. var effectiveMaterial = subMesh.getMaterial();
  21385. if (!effectiveMaterial) {
  21386. return this;
  21387. }
  21388. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21389. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  21390. return this;
  21391. }
  21392. }
  21393. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  21394. return this;
  21395. }
  21396. // Alpha mode
  21397. if (enableAlphaMode) {
  21398. engine.setAlphaMode(effectiveMaterial.alphaMode);
  21399. }
  21400. // Outline - step 1
  21401. var savedDepthWrite = engine.getDepthWrite();
  21402. if (this.renderOutline) {
  21403. engine.setDepthWrite(false);
  21404. scene.getOutlineRenderer().render(subMesh, batch);
  21405. engine.setDepthWrite(savedDepthWrite);
  21406. }
  21407. var effect;
  21408. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21409. effect = subMesh.effect;
  21410. }
  21411. else {
  21412. effect = effectiveMaterial.getEffect();
  21413. }
  21414. effectiveMaterial._preBind(effect);
  21415. // Bind
  21416. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  21417. this._bind(subMesh, effect, fillMode);
  21418. var world = this.getWorldMatrix();
  21419. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21420. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  21421. }
  21422. else {
  21423. effectiveMaterial.bind(world, this);
  21424. }
  21425. // Draw
  21426. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  21427. // Unbind
  21428. effectiveMaterial.unbind();
  21429. // Outline - step 2
  21430. if (this.renderOutline && savedDepthWrite) {
  21431. engine.setDepthWrite(true);
  21432. engine.setColorWrite(false);
  21433. scene.getOutlineRenderer().render(subMesh, batch);
  21434. engine.setColorWrite(true);
  21435. }
  21436. // Overlay
  21437. if (this.renderOverlay) {
  21438. var currentMode = engine.getAlphaMode();
  21439. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21440. scene.getOutlineRenderer().render(subMesh, batch, true);
  21441. engine.setAlphaMode(currentMode);
  21442. }
  21443. this.onAfterRenderObservable.notifyObservers(this);
  21444. return this;
  21445. };
  21446. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  21447. if (isInstance) {
  21448. effectiveMaterial.bindOnlyWorldMatrix(world);
  21449. }
  21450. return this;
  21451. };
  21452. /**
  21453. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  21454. */
  21455. Mesh.prototype.getEmittedParticleSystems = function () {
  21456. var results = new Array();
  21457. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21458. var particleSystem = this.getScene().particleSystems[index];
  21459. if (particleSystem.emitter === this) {
  21460. results.push(particleSystem);
  21461. }
  21462. }
  21463. return results;
  21464. };
  21465. /**
  21466. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  21467. */
  21468. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  21469. var results = new Array();
  21470. var descendants = this.getDescendants();
  21471. descendants.push(this);
  21472. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21473. var particleSystem = this.getScene().particleSystems[index];
  21474. var emitter = particleSystem.emitter;
  21475. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  21476. results.push(particleSystem);
  21477. }
  21478. }
  21479. return results;
  21480. };
  21481. Mesh.prototype._checkDelayState = function () {
  21482. var scene = this.getScene();
  21483. if (this._geometry) {
  21484. this._geometry.load(scene);
  21485. }
  21486. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21487. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21488. this._queueLoad(this, scene);
  21489. }
  21490. return this;
  21491. };
  21492. Mesh.prototype._queueLoad = function (mesh, scene) {
  21493. var _this = this;
  21494. scene._addPendingData(mesh);
  21495. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  21496. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21497. if (data instanceof ArrayBuffer) {
  21498. _this._delayLoadingFunction(data, _this);
  21499. }
  21500. else {
  21501. _this._delayLoadingFunction(JSON.parse(data), _this);
  21502. }
  21503. _this.instances.forEach(function (instance) {
  21504. instance._syncSubMeshes();
  21505. });
  21506. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21507. scene._removePendingData(_this);
  21508. }, function () { }, scene.database, getBinaryData);
  21509. return this;
  21510. };
  21511. /**
  21512. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  21513. */
  21514. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  21515. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21516. return false;
  21517. }
  21518. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  21519. return false;
  21520. }
  21521. this._checkDelayState();
  21522. return true;
  21523. };
  21524. /**
  21525. * Sets the mesh material by the material or multiMaterial `id` property.
  21526. * The material `id` is a string identifying the material or the multiMaterial.
  21527. * This method returns the Mesh.
  21528. */
  21529. Mesh.prototype.setMaterialByID = function (id) {
  21530. var materials = this.getScene().materials;
  21531. var index;
  21532. for (index = materials.length - 1; index > -1; index--) {
  21533. if (materials[index].id === id) {
  21534. this.material = materials[index];
  21535. return this;
  21536. }
  21537. }
  21538. // Multi
  21539. var multiMaterials = this.getScene().multiMaterials;
  21540. for (index = multiMaterials.length - 1; index > -1; index--) {
  21541. if (multiMaterials[index].id === id) {
  21542. this.material = multiMaterials[index];
  21543. return this;
  21544. }
  21545. }
  21546. return this;
  21547. };
  21548. /**
  21549. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  21550. */
  21551. Mesh.prototype.getAnimatables = function () {
  21552. var results = [];
  21553. if (this.material) {
  21554. results.push(this.material);
  21555. }
  21556. if (this.skeleton) {
  21557. results.push(this.skeleton);
  21558. }
  21559. return results;
  21560. };
  21561. /**
  21562. * Modifies the mesh geometry according to the passed transformation matrix.
  21563. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  21564. * The mesh normals are modified accordingly the same transformation.
  21565. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21566. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21567. * Returns the Mesh.
  21568. */
  21569. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  21570. // Position
  21571. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21572. return this;
  21573. }
  21574. var submeshes = this.subMeshes.splice(0);
  21575. this._resetPointsArrayCache();
  21576. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21577. var temp = [];
  21578. var index;
  21579. for (index = 0; index < data.length; index += 3) {
  21580. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  21581. }
  21582. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  21583. // Normals
  21584. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21585. return this;
  21586. }
  21587. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21588. temp = [];
  21589. for (index = 0; index < data.length; index += 3) {
  21590. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  21591. }
  21592. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  21593. // flip faces?
  21594. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  21595. this.flipFaces();
  21596. }
  21597. // Restore submeshes
  21598. this.releaseSubMeshes();
  21599. this.subMeshes = submeshes;
  21600. return this;
  21601. };
  21602. /**
  21603. * Modifies the mesh geometry according to its own current World Matrix.
  21604. * The mesh World Matrix is then reset.
  21605. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  21606. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21607. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21608. * Returns the Mesh.
  21609. */
  21610. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  21611. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  21612. this.scaling.copyFromFloats(1, 1, 1);
  21613. this.position.copyFromFloats(0, 0, 0);
  21614. this.rotation.copyFromFloats(0, 0, 0);
  21615. //only if quaternion is already set
  21616. if (this.rotationQuaternion) {
  21617. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  21618. }
  21619. this._worldMatrix = BABYLON.Matrix.Identity();
  21620. return this;
  21621. };
  21622. Object.defineProperty(Mesh.prototype, "_positions", {
  21623. // Cache
  21624. get: function () {
  21625. if (this._geometry) {
  21626. return this._geometry._positions;
  21627. }
  21628. return null;
  21629. },
  21630. enumerable: true,
  21631. configurable: true
  21632. });
  21633. Mesh.prototype._resetPointsArrayCache = function () {
  21634. if (this._geometry) {
  21635. this._geometry._resetPointsArrayCache();
  21636. }
  21637. return this;
  21638. };
  21639. Mesh.prototype._generatePointsArray = function () {
  21640. if (this._geometry) {
  21641. return this._geometry._generatePointsArray();
  21642. }
  21643. return false;
  21644. };
  21645. /**
  21646. * Returns a new Mesh object generated from the current mesh properties.
  21647. * This method must not get confused with createInstance().
  21648. * The parameter `name` is a string, the name given to the new mesh.
  21649. * The optional parameter `newParent` can be any Node object (default `null`).
  21650. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  21651. * 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.
  21652. */
  21653. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  21654. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21655. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  21656. };
  21657. /**
  21658. * Disposes the mesh.
  21659. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  21660. */
  21661. Mesh.prototype.dispose = function (doNotRecurse) {
  21662. var _this = this;
  21663. this.morphTargetManager = undefined;
  21664. if (this._geometry) {
  21665. this._geometry.releaseForMesh(this, true);
  21666. }
  21667. // Sources
  21668. var meshes = this.getScene().meshes;
  21669. meshes.forEach(function (mesh) {
  21670. if (mesh._source && mesh._source === _this) {
  21671. mesh._source = null;
  21672. }
  21673. });
  21674. this._source = null;
  21675. // Instances
  21676. if (this._instancesBuffer) {
  21677. this._instancesBuffer.dispose();
  21678. this._instancesBuffer = null;
  21679. }
  21680. while (this.instances.length) {
  21681. this.instances[0].dispose();
  21682. }
  21683. // Highlight layers.
  21684. var highlightLayers = this.getScene().highlightLayers;
  21685. for (var i = 0; i < highlightLayers.length; i++) {
  21686. var highlightLayer = highlightLayers[i];
  21687. if (highlightLayer) {
  21688. highlightLayer.removeMesh(this);
  21689. highlightLayer.removeExcludedMesh(this);
  21690. }
  21691. }
  21692. _super.prototype.dispose.call(this, doNotRecurse);
  21693. };
  21694. /**
  21695. * Modifies the mesh geometry according to a displacement map.
  21696. * 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.
  21697. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21698. * This method returns nothing.
  21699. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  21700. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21701. * 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.
  21702. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21703. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21704. *
  21705. * Returns the Mesh.
  21706. */
  21707. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  21708. var _this = this;
  21709. var scene = this.getScene();
  21710. var onload = function (img) {
  21711. // Getting height map data
  21712. var canvas = document.createElement("canvas");
  21713. var context = canvas.getContext("2d");
  21714. var heightMapWidth = img.width;
  21715. var heightMapHeight = img.height;
  21716. canvas.width = heightMapWidth;
  21717. canvas.height = heightMapHeight;
  21718. context.drawImage(img, 0, 0);
  21719. // Create VertexData from map data
  21720. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21721. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  21722. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  21723. //execute success callback, if set
  21724. if (onSuccess) {
  21725. onSuccess(_this);
  21726. }
  21727. };
  21728. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21729. return this;
  21730. };
  21731. /**
  21732. * Modifies the mesh geometry according to a displacementMap buffer.
  21733. * 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.
  21734. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21735. * This method returns nothing.
  21736. * 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.
  21737. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  21738. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21739. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21740. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21741. *
  21742. * Returns the Mesh.
  21743. */
  21744. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  21745. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  21746. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  21747. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21748. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  21749. return this;
  21750. }
  21751. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21752. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21753. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21754. var position = BABYLON.Vector3.Zero();
  21755. var normal = BABYLON.Vector3.Zero();
  21756. var uv = BABYLON.Vector2.Zero();
  21757. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  21758. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  21759. for (var index = 0; index < positions.length; index += 3) {
  21760. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  21761. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  21762. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  21763. // Compute height
  21764. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  21765. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  21766. var pos = (u + v * heightMapWidth) * 4;
  21767. var r = buffer[pos] / 255.0;
  21768. var g = buffer[pos + 1] / 255.0;
  21769. var b = buffer[pos + 2] / 255.0;
  21770. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21771. normal.normalize();
  21772. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  21773. position = position.add(normal);
  21774. position.toArray(positions, index);
  21775. }
  21776. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  21777. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  21778. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21779. return this;
  21780. };
  21781. /**
  21782. * Modify the mesh to get a flat shading rendering.
  21783. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  21784. * This method returns the Mesh.
  21785. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  21786. */
  21787. Mesh.prototype.convertToFlatShadedMesh = function () {
  21788. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  21789. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21790. var kinds = this.getVerticesDataKinds();
  21791. var vbs = [];
  21792. var data = [];
  21793. var newdata = [];
  21794. var updatableNormals = false;
  21795. var kindIndex;
  21796. var kind;
  21797. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21798. kind = kinds[kindIndex];
  21799. var vertexBuffer = this.getVertexBuffer(kind);
  21800. if (kind === BABYLON.VertexBuffer.NormalKind) {
  21801. updatableNormals = vertexBuffer.isUpdatable();
  21802. kinds.splice(kindIndex, 1);
  21803. kindIndex--;
  21804. continue;
  21805. }
  21806. vbs[kind] = vertexBuffer;
  21807. data[kind] = vbs[kind].getData();
  21808. newdata[kind] = [];
  21809. }
  21810. // Save previous submeshes
  21811. var previousSubmeshes = this.subMeshes.slice(0);
  21812. var indices = this.getIndices();
  21813. var totalIndices = this.getTotalIndices();
  21814. // Generating unique vertices per face
  21815. var index;
  21816. for (index = 0; index < totalIndices; index++) {
  21817. var vertexIndex = indices[index];
  21818. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21819. kind = kinds[kindIndex];
  21820. var stride = vbs[kind].getStrideSize();
  21821. for (var offset = 0; offset < stride; offset++) {
  21822. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21823. }
  21824. }
  21825. }
  21826. // Updating faces & normal
  21827. var normals = [];
  21828. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  21829. for (index = 0; index < totalIndices; index += 3) {
  21830. indices[index] = index;
  21831. indices[index + 1] = index + 1;
  21832. indices[index + 2] = index + 2;
  21833. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  21834. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  21835. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  21836. var p1p2 = p1.subtract(p2);
  21837. var p3p2 = p3.subtract(p2);
  21838. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21839. // Store same normals for every vertex
  21840. for (var localIndex = 0; localIndex < 3; localIndex++) {
  21841. normals.push(normal.x);
  21842. normals.push(normal.y);
  21843. normals.push(normal.z);
  21844. }
  21845. }
  21846. this.setIndices(indices);
  21847. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21848. // Updating vertex buffers
  21849. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21850. kind = kinds[kindIndex];
  21851. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21852. }
  21853. // Updating submeshes
  21854. this.releaseSubMeshes();
  21855. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21856. var previousOne = previousSubmeshes[submeshIndex];
  21857. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21858. }
  21859. this.synchronizeInstances();
  21860. return this;
  21861. };
  21862. /**
  21863. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21864. * In other words, more vertices, no more indices and a single bigger VBO.
  21865. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21866. * Returns the Mesh.
  21867. */
  21868. Mesh.prototype.convertToUnIndexedMesh = function () {
  21869. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21870. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21871. var kinds = this.getVerticesDataKinds();
  21872. var vbs = [];
  21873. var data = [];
  21874. var newdata = [];
  21875. var updatableNormals = false;
  21876. var kindIndex;
  21877. var kind;
  21878. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21879. kind = kinds[kindIndex];
  21880. var vertexBuffer = this.getVertexBuffer(kind);
  21881. vbs[kind] = vertexBuffer;
  21882. data[kind] = vbs[kind].getData();
  21883. newdata[kind] = [];
  21884. }
  21885. // Save previous submeshes
  21886. var previousSubmeshes = this.subMeshes.slice(0);
  21887. var indices = this.getIndices();
  21888. var totalIndices = this.getTotalIndices();
  21889. // Generating unique vertices per face
  21890. var index;
  21891. for (index = 0; index < totalIndices; index++) {
  21892. var vertexIndex = indices[index];
  21893. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21894. kind = kinds[kindIndex];
  21895. var stride = vbs[kind].getStrideSize();
  21896. for (var offset = 0; offset < stride; offset++) {
  21897. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21898. }
  21899. }
  21900. }
  21901. // Updating indices
  21902. for (index = 0; index < totalIndices; index += 3) {
  21903. indices[index] = index;
  21904. indices[index + 1] = index + 1;
  21905. indices[index + 2] = index + 2;
  21906. }
  21907. this.setIndices(indices);
  21908. // Updating vertex buffers
  21909. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21910. kind = kinds[kindIndex];
  21911. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21912. }
  21913. // Updating submeshes
  21914. this.releaseSubMeshes();
  21915. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21916. var previousOne = previousSubmeshes[submeshIndex];
  21917. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21918. }
  21919. this._unIndexed = true;
  21920. this.synchronizeInstances();
  21921. return this;
  21922. };
  21923. /**
  21924. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21925. * This method returns the Mesh.
  21926. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21927. */
  21928. Mesh.prototype.flipFaces = function (flipNormals) {
  21929. if (flipNormals === void 0) { flipNormals = false; }
  21930. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21931. var i;
  21932. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21933. for (i = 0; i < vertex_data.normals.length; i++) {
  21934. vertex_data.normals[i] *= -1;
  21935. }
  21936. }
  21937. var temp;
  21938. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21939. // reassign indices
  21940. temp = vertex_data.indices[i + 1];
  21941. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21942. vertex_data.indices[i + 2] = temp;
  21943. }
  21944. vertex_data.applyToMesh(this);
  21945. return this;
  21946. };
  21947. // Instances
  21948. /**
  21949. * Creates a new InstancedMesh object from the mesh model.
  21950. * An instance shares the same properties and the same material than its model.
  21951. * Only these properties of each instance can then be set individually :
  21952. * - position
  21953. * - rotation
  21954. * - rotationQuaternion
  21955. * - setPivotMatrix
  21956. * - scaling
  21957. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21958. * Warning : this method is not supported for Line mesh and LineSystem
  21959. */
  21960. Mesh.prototype.createInstance = function (name) {
  21961. return new BABYLON.InstancedMesh(name, this);
  21962. };
  21963. /**
  21964. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21965. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21966. * This method returns the Mesh.
  21967. */
  21968. Mesh.prototype.synchronizeInstances = function () {
  21969. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21970. var instance = this.instances[instanceIndex];
  21971. instance._syncSubMeshes();
  21972. }
  21973. return this;
  21974. };
  21975. /**
  21976. * Simplify the mesh according to the given array of settings.
  21977. * Function will return immediately and will simplify async. It returns the Mesh.
  21978. * @param settings a collection of simplification settings.
  21979. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21980. * @param type the type of simplification to run.
  21981. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21982. */
  21983. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21984. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21985. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21986. this.getScene().simplificationQueue.addTask({
  21987. settings: settings,
  21988. parallelProcessing: parallelProcessing,
  21989. mesh: this,
  21990. simplificationType: simplificationType,
  21991. successCallback: successCallback
  21992. });
  21993. return this;
  21994. };
  21995. /**
  21996. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21997. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21998. * This should be used together with the simplification to avoid disappearing triangles.
  21999. * Returns the Mesh.
  22000. * @param successCallback an optional success callback to be called after the optimization finished.
  22001. */
  22002. Mesh.prototype.optimizeIndices = function (successCallback) {
  22003. var _this = this;
  22004. var indices = this.getIndices();
  22005. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22006. var vectorPositions = [];
  22007. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22008. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22009. }
  22010. var dupes = [];
  22011. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22012. var realPos = vectorPositions.length - 1 - iteration;
  22013. var testedPosition = vectorPositions[realPos];
  22014. for (var j = 0; j < realPos; ++j) {
  22015. var againstPosition = vectorPositions[j];
  22016. if (testedPosition.equals(againstPosition)) {
  22017. dupes[realPos] = j;
  22018. break;
  22019. }
  22020. }
  22021. }, function () {
  22022. for (var i = 0; i < indices.length; ++i) {
  22023. indices[i] = dupes[indices[i]] || indices[i];
  22024. }
  22025. //indices are now reordered
  22026. var originalSubMeshes = _this.subMeshes.slice(0);
  22027. _this.setIndices(indices);
  22028. _this.subMeshes = originalSubMeshes;
  22029. if (successCallback) {
  22030. successCallback(_this);
  22031. }
  22032. });
  22033. return this;
  22034. };
  22035. Mesh.prototype.serialize = function (serializationObject) {
  22036. serializationObject.name = this.name;
  22037. serializationObject.id = this.id;
  22038. serializationObject.type = this.getClassName();
  22039. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22040. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22041. }
  22042. serializationObject.position = this.position.asArray();
  22043. if (this.rotationQuaternion) {
  22044. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22045. }
  22046. else if (this.rotation) {
  22047. serializationObject.rotation = this.rotation.asArray();
  22048. }
  22049. serializationObject.scaling = this.scaling.asArray();
  22050. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22051. serializationObject.isEnabled = this.isEnabled();
  22052. serializationObject.isVisible = this.isVisible;
  22053. serializationObject.infiniteDistance = this.infiniteDistance;
  22054. serializationObject.pickable = this.isPickable;
  22055. serializationObject.receiveShadows = this.receiveShadows;
  22056. serializationObject.billboardMode = this.billboardMode;
  22057. serializationObject.visibility = this.visibility;
  22058. serializationObject.checkCollisions = this.checkCollisions;
  22059. serializationObject.isBlocker = this.isBlocker;
  22060. // Parent
  22061. if (this.parent) {
  22062. serializationObject.parentId = this.parent.id;
  22063. }
  22064. // Geometry
  22065. var geometry = this._geometry;
  22066. if (geometry) {
  22067. var geometryId = geometry.id;
  22068. serializationObject.geometryId = geometryId;
  22069. // SubMeshes
  22070. serializationObject.subMeshes = [];
  22071. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22072. var subMesh = this.subMeshes[subIndex];
  22073. serializationObject.subMeshes.push({
  22074. materialIndex: subMesh.materialIndex,
  22075. verticesStart: subMesh.verticesStart,
  22076. verticesCount: subMesh.verticesCount,
  22077. indexStart: subMesh.indexStart,
  22078. indexCount: subMesh.indexCount
  22079. });
  22080. }
  22081. }
  22082. // Material
  22083. if (this.material) {
  22084. serializationObject.materialId = this.material.id;
  22085. }
  22086. else {
  22087. this.material = null;
  22088. }
  22089. // Morph targets
  22090. if (this.morphTargetManager) {
  22091. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22092. }
  22093. // Skeleton
  22094. if (this.skeleton) {
  22095. serializationObject.skeletonId = this.skeleton.id;
  22096. }
  22097. // Physics
  22098. //TODO implement correct serialization for physics impostors.
  22099. if (this.getPhysicsImpostor()) {
  22100. var impostor = this.getPhysicsImpostor();
  22101. serializationObject.physicsMass = impostor.getParam("mass");
  22102. serializationObject.physicsFriction = impostor.getParam("friction");
  22103. serializationObject.physicsRestitution = impostor.getParam("mass");
  22104. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  22105. }
  22106. // Metadata
  22107. if (this.metadata) {
  22108. serializationObject.metadata = this.metadata;
  22109. }
  22110. // Instances
  22111. serializationObject.instances = [];
  22112. for (var index = 0; index < this.instances.length; index++) {
  22113. var instance = this.instances[index];
  22114. var serializationInstance = {
  22115. name: instance.name,
  22116. position: instance.position.asArray(),
  22117. scaling: instance.scaling.asArray()
  22118. };
  22119. if (instance.rotationQuaternion) {
  22120. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  22121. }
  22122. else if (instance.rotation) {
  22123. serializationInstance.rotation = instance.rotation.asArray();
  22124. }
  22125. serializationObject.instances.push(serializationInstance);
  22126. // Animations
  22127. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  22128. serializationInstance.ranges = instance.serializeAnimationRanges();
  22129. }
  22130. //
  22131. // Animations
  22132. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22133. serializationObject.ranges = this.serializeAnimationRanges();
  22134. // Layer mask
  22135. serializationObject.layerMask = this.layerMask;
  22136. // Alpha
  22137. serializationObject.alphaIndex = this.alphaIndex;
  22138. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  22139. // Overlay
  22140. serializationObject.overlayAlpha = this.overlayAlpha;
  22141. serializationObject.overlayColor = this.overlayColor.asArray();
  22142. serializationObject.renderOverlay = this.renderOverlay;
  22143. // Fog
  22144. serializationObject.applyFog = this.applyFog;
  22145. // Action Manager
  22146. if (this.actionManager) {
  22147. serializationObject.actions = this.actionManager.serialize(this.name);
  22148. }
  22149. };
  22150. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  22151. if (!this.geometry) {
  22152. return;
  22153. }
  22154. this._markSubMeshesAsAttributesDirty();
  22155. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  22156. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  22157. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  22158. this.morphTargetManager = undefined;
  22159. return;
  22160. }
  22161. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  22162. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  22163. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  22164. if (morphTarget.hasNormals) {
  22165. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  22166. }
  22167. if (morphTarget.hasTangents) {
  22168. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  22169. }
  22170. }
  22171. }
  22172. else {
  22173. var index = 0;
  22174. // Positions
  22175. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  22176. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  22177. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  22178. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  22179. }
  22180. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  22181. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  22182. }
  22183. index++;
  22184. }
  22185. }
  22186. };
  22187. // Statics
  22188. /**
  22189. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22190. * The parameter `parsedMesh` is the mesh to be copied.
  22191. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22192. */
  22193. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22194. var mesh;
  22195. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  22196. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  22197. }
  22198. else {
  22199. mesh = new Mesh(parsedMesh.name, scene);
  22200. }
  22201. mesh.id = parsedMesh.id;
  22202. if (BABYLON.Tags) {
  22203. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  22204. }
  22205. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  22206. if (parsedMesh.metadata !== undefined) {
  22207. mesh.metadata = parsedMesh.metadata;
  22208. }
  22209. if (parsedMesh.rotationQuaternion) {
  22210. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  22211. }
  22212. else if (parsedMesh.rotation) {
  22213. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  22214. }
  22215. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  22216. if (parsedMesh.localMatrix) {
  22217. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  22218. }
  22219. else if (parsedMesh.pivotMatrix) {
  22220. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  22221. }
  22222. mesh.setEnabled(parsedMesh.isEnabled);
  22223. mesh.isVisible = parsedMesh.isVisible;
  22224. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  22225. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  22226. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  22227. if (parsedMesh.applyFog !== undefined) {
  22228. mesh.applyFog = parsedMesh.applyFog;
  22229. }
  22230. if (parsedMesh.pickable !== undefined) {
  22231. mesh.isPickable = parsedMesh.pickable;
  22232. }
  22233. if (parsedMesh.alphaIndex !== undefined) {
  22234. mesh.alphaIndex = parsedMesh.alphaIndex;
  22235. }
  22236. mesh.receiveShadows = parsedMesh.receiveShadows;
  22237. mesh.billboardMode = parsedMesh.billboardMode;
  22238. if (parsedMesh.visibility !== undefined) {
  22239. mesh.visibility = parsedMesh.visibility;
  22240. }
  22241. mesh.checkCollisions = parsedMesh.checkCollisions;
  22242. if (parsedMesh.isBlocker !== undefined) {
  22243. mesh.isBlocker = parsedMesh.isBlocker;
  22244. }
  22245. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  22246. // freezeWorldMatrix
  22247. if (parsedMesh.freezeWorldMatrix) {
  22248. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  22249. }
  22250. // Parent
  22251. if (parsedMesh.parentId) {
  22252. mesh._waitingParentId = parsedMesh.parentId;
  22253. }
  22254. // Actions
  22255. if (parsedMesh.actions !== undefined) {
  22256. mesh._waitingActions = parsedMesh.actions;
  22257. }
  22258. // Overlay
  22259. if (parsedMesh.overlayAlpha !== undefined) {
  22260. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22261. }
  22262. if (parsedMesh.overlayColor !== undefined) {
  22263. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22264. }
  22265. if (parsedMesh.renderOverlay !== undefined) {
  22266. mesh.renderOverlay = parsedMesh.renderOverlay;
  22267. }
  22268. // Geometry
  22269. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22270. if (parsedMesh.delayLoadingFile) {
  22271. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22272. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22273. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22274. if (parsedMesh._binaryInfo) {
  22275. mesh._binaryInfo = parsedMesh._binaryInfo;
  22276. }
  22277. mesh._delayInfo = [];
  22278. if (parsedMesh.hasUVs) {
  22279. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22280. }
  22281. if (parsedMesh.hasUVs2) {
  22282. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22283. }
  22284. if (parsedMesh.hasUVs3) {
  22285. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22286. }
  22287. if (parsedMesh.hasUVs4) {
  22288. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22289. }
  22290. if (parsedMesh.hasUVs5) {
  22291. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22292. }
  22293. if (parsedMesh.hasUVs6) {
  22294. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22295. }
  22296. if (parsedMesh.hasColors) {
  22297. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22298. }
  22299. if (parsedMesh.hasMatricesIndices) {
  22300. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22301. }
  22302. if (parsedMesh.hasMatricesWeights) {
  22303. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22304. }
  22305. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22306. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22307. mesh._checkDelayState();
  22308. }
  22309. }
  22310. else {
  22311. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22312. }
  22313. // Material
  22314. if (parsedMesh.materialId) {
  22315. mesh.setMaterialByID(parsedMesh.materialId);
  22316. }
  22317. else {
  22318. mesh.material = null;
  22319. }
  22320. // Morph targets
  22321. if (parsedMesh.morphTargetManagerId > -1) {
  22322. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  22323. }
  22324. // Skeleton
  22325. if (parsedMesh.skeletonId > -1) {
  22326. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22327. if (parsedMesh.numBoneInfluencers) {
  22328. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22329. }
  22330. }
  22331. // Animations
  22332. if (parsedMesh.animations) {
  22333. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22334. var parsedAnimation = parsedMesh.animations[animationIndex];
  22335. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22336. }
  22337. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  22338. }
  22339. if (parsedMesh.autoAnimate) {
  22340. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  22341. }
  22342. // Layer Mask
  22343. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  22344. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  22345. }
  22346. else {
  22347. mesh.layerMask = 0x0FFFFFFF;
  22348. }
  22349. // Physics
  22350. if (parsedMesh.physicsImpostor) {
  22351. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  22352. mass: parsedMesh.physicsMass,
  22353. friction: parsedMesh.physicsFriction,
  22354. restitution: parsedMesh.physicsRestitution
  22355. }, scene);
  22356. }
  22357. // Instances
  22358. if (parsedMesh.instances) {
  22359. for (var index = 0; index < parsedMesh.instances.length; index++) {
  22360. var parsedInstance = parsedMesh.instances[index];
  22361. var instance = mesh.createInstance(parsedInstance.name);
  22362. if (BABYLON.Tags) {
  22363. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  22364. }
  22365. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  22366. if (parsedInstance.parentId) {
  22367. instance._waitingParentId = parsedInstance.parentId;
  22368. }
  22369. if (parsedInstance.rotationQuaternion) {
  22370. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  22371. }
  22372. else if (parsedInstance.rotation) {
  22373. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  22374. }
  22375. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  22376. instance.checkCollisions = mesh.checkCollisions;
  22377. if (parsedMesh.animations) {
  22378. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22379. parsedAnimation = parsedMesh.animations[animationIndex];
  22380. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22381. }
  22382. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  22383. }
  22384. }
  22385. }
  22386. return mesh;
  22387. };
  22388. /**
  22389. * Creates a ribbon mesh.
  22390. * Please consider using the same method from the MeshBuilder class instead.
  22391. * 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.
  22392. *
  22393. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22394. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22395. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22396. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22397. * 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.
  22398. * 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.
  22399. * 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
  22400. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22401. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22402. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22403. */
  22404. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  22405. return BABYLON.MeshBuilder.CreateRibbon(name, {
  22406. pathArray: pathArray,
  22407. closeArray: closeArray,
  22408. closePath: closePath,
  22409. offset: offset,
  22410. updatable: updatable,
  22411. sideOrientation: sideOrientation,
  22412. instance: instance
  22413. }, scene);
  22414. };
  22415. /**
  22416. * Creates a plane polygonal mesh. By default, this is a disc.
  22417. * Please consider using the same method from the MeshBuilder class instead.
  22418. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22419. * 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.
  22420. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22421. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22422. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22423. */
  22424. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22425. var options = {
  22426. radius: radius,
  22427. tessellation: tessellation,
  22428. sideOrientation: sideOrientation,
  22429. updatable: updatable
  22430. };
  22431. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22432. };
  22433. /**
  22434. * Creates a box mesh.
  22435. * Please consider using the same method from the MeshBuilder class instead.
  22436. * The parameter `size` sets the size (float) of each box side (default 1).
  22437. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22438. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22439. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22440. */
  22441. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22442. var options = {
  22443. size: size,
  22444. sideOrientation: sideOrientation,
  22445. updatable: updatable
  22446. };
  22447. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22448. };
  22449. /**
  22450. * Creates a sphere mesh.
  22451. * Please consider using the same method from the MeshBuilder class instead.
  22452. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22453. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22454. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22455. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22456. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22457. */
  22458. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22459. var options = {
  22460. segments: segments,
  22461. diameterX: diameter,
  22462. diameterY: diameter,
  22463. diameterZ: diameter,
  22464. sideOrientation: sideOrientation,
  22465. updatable: updatable
  22466. };
  22467. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  22468. };
  22469. /**
  22470. * Creates a cylinder or a cone mesh.
  22471. * Please consider using the same method from the MeshBuilder class instead.
  22472. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22473. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22474. * 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.
  22475. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22476. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22477. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22478. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22479. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22480. */
  22481. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  22482. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  22483. if (scene !== undefined) {
  22484. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  22485. updatable = scene;
  22486. }
  22487. scene = subdivisions;
  22488. subdivisions = 1;
  22489. }
  22490. var options = {
  22491. height: height,
  22492. diameterTop: diameterTop,
  22493. diameterBottom: diameterBottom,
  22494. tessellation: tessellation,
  22495. subdivisions: subdivisions,
  22496. sideOrientation: sideOrientation,
  22497. updatable: updatable
  22498. };
  22499. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  22500. };
  22501. // Torus (Code from SharpDX.org)
  22502. /**
  22503. * Creates a torus mesh.
  22504. * Please consider using the same method from the MeshBuilder class instead.
  22505. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22506. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22507. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22508. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22509. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22510. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22511. */
  22512. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  22513. var options = {
  22514. diameter: diameter,
  22515. thickness: thickness,
  22516. tessellation: tessellation,
  22517. sideOrientation: sideOrientation,
  22518. updatable: updatable
  22519. };
  22520. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  22521. };
  22522. /**
  22523. * Creates a torus knot mesh.
  22524. * Please consider using the same method from the MeshBuilder class instead.
  22525. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22526. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22527. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22528. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22529. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22530. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22531. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22532. */
  22533. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  22534. var options = {
  22535. radius: radius,
  22536. tube: tube,
  22537. radialSegments: radialSegments,
  22538. tubularSegments: tubularSegments,
  22539. p: p,
  22540. q: q,
  22541. sideOrientation: sideOrientation,
  22542. updatable: updatable
  22543. };
  22544. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  22545. };
  22546. /**
  22547. * Creates a line mesh.
  22548. * Please consider using the same method from the MeshBuilder class instead.
  22549. * 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.
  22550. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22551. * The parameter `points` is an array successive Vector3.
  22552. * 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
  22553. * When updating an instance, remember that only point positions can change, not the number of points.
  22554. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22555. */
  22556. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  22557. var options = {
  22558. points: points,
  22559. updatable: updatable,
  22560. instance: instance
  22561. };
  22562. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  22563. };
  22564. /**
  22565. * Creates a dashed line mesh.
  22566. * Please consider using the same method from the MeshBuilder class instead.
  22567. * 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.
  22568. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22569. * The parameter `points` is an array successive Vector3.
  22570. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22571. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22572. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22573. * 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
  22574. * When updating an instance, remember that only point positions can change, not the number of points.
  22575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22576. */
  22577. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  22578. var options = {
  22579. points: points,
  22580. dashSize: dashSize,
  22581. gapSize: gapSize,
  22582. dashNb: dashNb,
  22583. updatable: updatable,
  22584. instance: instance
  22585. };
  22586. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  22587. };
  22588. /**
  22589. * Creates a polygon mesh.
  22590. * Please consider using the same method from the MeshBuilder class instead.
  22591. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  22592. * 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.
  22593. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22594. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22595. * Remember you can only change the shape positions, not their number when updating a polygon.
  22596. */
  22597. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  22598. var options = {
  22599. shape: shape,
  22600. holes: holes,
  22601. updatable: updatable,
  22602. sideOrientation: sideOrientation
  22603. };
  22604. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  22605. };
  22606. /**
  22607. * Creates an extruded polygon mesh, with depth in the Y direction.
  22608. * Please consider using the same method from the MeshBuilder class instead.
  22609. */
  22610. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  22611. var options = {
  22612. shape: shape,
  22613. holes: holes,
  22614. depth: depth,
  22615. updatable: updatable,
  22616. sideOrientation: sideOrientation
  22617. };
  22618. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  22619. };
  22620. /**
  22621. * Creates an extruded shape mesh.
  22622. * 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.
  22623. * Please consider using the same method from the MeshBuilder class instead.
  22624. *
  22625. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22626. * 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
  22627. * extruded along the Z axis.
  22628. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22629. * 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.
  22630. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22631. * 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
  22632. * 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
  22633. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22634. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22635. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22636. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22637. */
  22638. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  22639. var options = {
  22640. shape: shape,
  22641. path: path,
  22642. scale: scale,
  22643. rotation: rotation,
  22644. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22645. sideOrientation: sideOrientation,
  22646. instance: instance,
  22647. updatable: updatable
  22648. };
  22649. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  22650. };
  22651. /**
  22652. * Creates an custom extruded shape mesh.
  22653. * 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.
  22654. * Please consider using the same method from the MeshBuilder class instead.
  22655. *
  22656. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22657. * 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
  22658. * extruded along the Z axis.
  22659. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22660. * 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
  22661. * and the distance of this point from the begining of the path :
  22662. * ```javascript
  22663. * var rotationFunction = function(i, distance) {
  22664. * // do things
  22665. * return rotationValue; }
  22666. * ```
  22667. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22668. * 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
  22669. * and the distance of this point from the begining of the path :
  22670. * ```javascript
  22671. * var scaleFunction = function(i, distance) {
  22672. * // do things
  22673. * return scaleValue;}
  22674. * ```
  22675. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22676. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22677. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22678. * 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
  22679. * 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
  22680. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22681. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22682. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22683. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22684. */
  22685. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  22686. var options = {
  22687. shape: shape,
  22688. path: path,
  22689. scaleFunction: scaleFunction,
  22690. rotationFunction: rotationFunction,
  22691. ribbonCloseArray: ribbonCloseArray,
  22692. ribbonClosePath: ribbonClosePath,
  22693. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22694. sideOrientation: sideOrientation,
  22695. instance: instance,
  22696. updatable: updatable
  22697. };
  22698. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  22699. };
  22700. /**
  22701. * Creates lathe mesh.
  22702. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22703. * Please consider using the same method from the MeshBuilder class instead.
  22704. * 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
  22705. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22706. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22707. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22708. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22709. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22710. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22711. */
  22712. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  22713. var options = {
  22714. shape: shape,
  22715. radius: radius,
  22716. tessellation: tessellation,
  22717. sideOrientation: sideOrientation,
  22718. updatable: updatable
  22719. };
  22720. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  22721. };
  22722. /**
  22723. * Creates a plane mesh.
  22724. * Please consider using the same method from the MeshBuilder class instead.
  22725. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22726. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22727. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22728. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22729. */
  22730. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  22731. var options = {
  22732. size: size,
  22733. width: size,
  22734. height: size,
  22735. sideOrientation: sideOrientation,
  22736. updatable: updatable
  22737. };
  22738. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  22739. };
  22740. /**
  22741. * Creates a ground mesh.
  22742. * Please consider using the same method from the MeshBuilder class instead.
  22743. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22744. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22745. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22746. */
  22747. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  22748. var options = {
  22749. width: width,
  22750. height: height,
  22751. subdivisions: subdivisions,
  22752. updatable: updatable
  22753. };
  22754. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  22755. };
  22756. /**
  22757. * Creates a tiled ground mesh.
  22758. * Please consider using the same method from the MeshBuilder class instead.
  22759. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22760. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22761. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22762. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22763. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22764. * numbers of subdivisions on the ground width and height of each tile.
  22765. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22766. */
  22767. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  22768. var options = {
  22769. xmin: xmin,
  22770. zmin: zmin,
  22771. xmax: xmax,
  22772. zmax: zmax,
  22773. subdivisions: subdivisions,
  22774. precision: precision,
  22775. updatable: updatable
  22776. };
  22777. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  22778. };
  22779. /**
  22780. * Creates a ground mesh from a height map.
  22781. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22782. * Please consider using the same method from the MeshBuilder class instead.
  22783. * The parameter `url` sets the URL of the height map image resource.
  22784. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22785. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22786. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22787. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22788. * 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).
  22789. * This function is passed the newly built mesh :
  22790. * ```javascript
  22791. * function(mesh) { // do things
  22792. * return; }
  22793. * ```
  22794. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22795. */
  22796. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  22797. var options = {
  22798. width: width,
  22799. height: height,
  22800. subdivisions: subdivisions,
  22801. minHeight: minHeight,
  22802. maxHeight: maxHeight,
  22803. updatable: updatable,
  22804. onReady: onReady
  22805. };
  22806. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  22807. };
  22808. /**
  22809. * Creates a tube mesh.
  22810. * 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.
  22811. * Please consider using the same method from the MeshBuilder class instead.
  22812. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22813. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22814. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22815. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22816. * 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.
  22817. * It must return a radius value (positive float) :
  22818. * ```javascript
  22819. * var radiusFunction = function(i, distance) {
  22820. * // do things
  22821. * return radius; }
  22822. * ```
  22823. * 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
  22824. * 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
  22825. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22826. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22827. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22828. */
  22829. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  22830. var options = {
  22831. path: path,
  22832. radius: radius,
  22833. tessellation: tessellation,
  22834. radiusFunction: radiusFunction,
  22835. arc: 1,
  22836. cap: cap,
  22837. updatable: updatable,
  22838. sideOrientation: sideOrientation,
  22839. instance: instance
  22840. };
  22841. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  22842. };
  22843. /**
  22844. * Creates a polyhedron mesh.
  22845. * Please consider using the same method from the MeshBuilder class instead.
  22846. * 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
  22847. * to choose the wanted type.
  22848. * The parameter `size` (positive float, default 1) sets the polygon size.
  22849. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22850. * 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`.
  22851. * 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
  22852. * 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)`).
  22853. * 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
  22854. * 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.
  22855. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22856. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22857. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22858. */
  22859. Mesh.CreatePolyhedron = function (name, options, scene) {
  22860. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22861. };
  22862. /**
  22863. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22864. * Please consider using the same method from the MeshBuilder class instead.
  22865. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22866. * 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`).
  22867. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22868. * 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.
  22869. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22870. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22871. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22872. */
  22873. Mesh.CreateIcoSphere = function (name, options, scene) {
  22874. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22875. };
  22876. /**
  22877. * Creates a decal mesh.
  22878. * Please consider using the same method from the MeshBuilder class instead.
  22879. * 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.
  22880. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22881. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22882. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22883. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22884. */
  22885. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22886. var options = {
  22887. position: position,
  22888. normal: normal,
  22889. size: size,
  22890. angle: angle
  22891. };
  22892. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22893. };
  22894. // Skeletons
  22895. /**
  22896. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22897. */
  22898. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22899. var source;
  22900. if (!this._sourcePositions) {
  22901. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22902. this._sourcePositions = new Float32Array(source);
  22903. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22904. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22905. }
  22906. }
  22907. return this._sourcePositions;
  22908. };
  22909. /**
  22910. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22911. */
  22912. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22913. var source;
  22914. if (!this._sourceNormals) {
  22915. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22916. this._sourceNormals = new Float32Array(source);
  22917. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22918. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22919. }
  22920. }
  22921. return this._sourceNormals;
  22922. };
  22923. /**
  22924. * Updates the vertex buffer by applying transformation from the bones.
  22925. * Returns the Mesh.
  22926. *
  22927. * @param {skeleton} skeleton to apply
  22928. */
  22929. Mesh.prototype.applySkeleton = function (skeleton) {
  22930. if (!this.geometry) {
  22931. return this;
  22932. }
  22933. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22934. return this;
  22935. }
  22936. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22937. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22938. return this;
  22939. }
  22940. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22941. return this;
  22942. }
  22943. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22944. return this;
  22945. }
  22946. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22947. return this;
  22948. }
  22949. if (!this._sourcePositions) {
  22950. var submeshes = this.subMeshes.slice();
  22951. this.setPositionsForCPUSkinning();
  22952. this.subMeshes = submeshes;
  22953. }
  22954. if (!this._sourceNormals) {
  22955. this.setNormalsForCPUSkinning();
  22956. }
  22957. // positionsData checks for not being Float32Array will only pass at most once
  22958. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22959. if (!(positionsData instanceof Float32Array)) {
  22960. positionsData = new Float32Array(positionsData);
  22961. }
  22962. // normalsData checks for not being Float32Array will only pass at most once
  22963. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22964. if (!(normalsData instanceof Float32Array)) {
  22965. normalsData = new Float32Array(normalsData);
  22966. }
  22967. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22968. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22969. var needExtras = this.numBoneInfluencers > 4;
  22970. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22971. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22972. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22973. var tempVector3 = BABYLON.Vector3.Zero();
  22974. var finalMatrix = new BABYLON.Matrix();
  22975. var tempMatrix = new BABYLON.Matrix();
  22976. var matWeightIdx = 0;
  22977. var inf;
  22978. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22979. var weight;
  22980. for (inf = 0; inf < 4; inf++) {
  22981. weight = matricesWeightsData[matWeightIdx + inf];
  22982. if (weight > 0) {
  22983. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22984. finalMatrix.addToSelf(tempMatrix);
  22985. }
  22986. else
  22987. break;
  22988. }
  22989. if (needExtras) {
  22990. for (inf = 0; inf < 4; inf++) {
  22991. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22992. if (weight > 0) {
  22993. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22994. finalMatrix.addToSelf(tempMatrix);
  22995. }
  22996. else
  22997. break;
  22998. }
  22999. }
  23000. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23001. tempVector3.toArray(positionsData, index);
  23002. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23003. tempVector3.toArray(normalsData, index);
  23004. finalMatrix.reset();
  23005. }
  23006. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23007. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23008. return this;
  23009. };
  23010. // Tools
  23011. /**
  23012. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23013. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23014. */
  23015. Mesh.MinMax = function (meshes) {
  23016. var minVector = null;
  23017. var maxVector = null;
  23018. meshes.forEach(function (mesh, index, array) {
  23019. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23020. if (!minVector) {
  23021. minVector = boundingBox.minimumWorld;
  23022. maxVector = boundingBox.maximumWorld;
  23023. }
  23024. else {
  23025. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23026. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23027. }
  23028. });
  23029. return {
  23030. min: minVector,
  23031. max: maxVector
  23032. };
  23033. };
  23034. /**
  23035. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23036. */
  23037. Mesh.Center = function (meshesOrMinMaxVector) {
  23038. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23039. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23040. };
  23041. /**
  23042. * Merge the array of meshes into a single mesh for performance reasons.
  23043. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23044. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23045. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23046. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23047. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23048. */
  23049. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23050. if (disposeSource === void 0) { disposeSource = true; }
  23051. var index;
  23052. if (!allow32BitsIndices) {
  23053. var totalVertices = 0;
  23054. // Counting vertices
  23055. for (index = 0; index < meshes.length; index++) {
  23056. if (meshes[index]) {
  23057. totalVertices += meshes[index].getTotalVertices();
  23058. if (totalVertices > 65536) {
  23059. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23060. return null;
  23061. }
  23062. }
  23063. }
  23064. }
  23065. // Merge
  23066. var vertexData;
  23067. var otherVertexData;
  23068. var indiceArray = new Array();
  23069. var source;
  23070. for (index = 0; index < meshes.length; index++) {
  23071. if (meshes[index]) {
  23072. meshes[index].computeWorldMatrix(true);
  23073. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23074. otherVertexData.transform(meshes[index].getWorldMatrix());
  23075. if (vertexData) {
  23076. vertexData.merge(otherVertexData);
  23077. }
  23078. else {
  23079. vertexData = otherVertexData;
  23080. source = meshes[index];
  23081. }
  23082. if (subdivideWithSubMeshes) {
  23083. indiceArray.push(meshes[index].getTotalIndices());
  23084. }
  23085. }
  23086. }
  23087. if (!meshSubclass) {
  23088. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23089. }
  23090. vertexData.applyToMesh(meshSubclass);
  23091. // Setting properties
  23092. meshSubclass.material = source.material;
  23093. meshSubclass.checkCollisions = source.checkCollisions;
  23094. // Cleaning
  23095. if (disposeSource) {
  23096. for (index = 0; index < meshes.length; index++) {
  23097. if (meshes[index]) {
  23098. meshes[index].dispose();
  23099. }
  23100. }
  23101. }
  23102. // Subdivide
  23103. if (subdivideWithSubMeshes) {
  23104. //-- Suppresions du submesh global
  23105. meshSubclass.releaseSubMeshes();
  23106. index = 0;
  23107. var offset = 0;
  23108. //-- aplique la subdivision en fonction du tableau d'indices
  23109. while (index < indiceArray.length) {
  23110. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  23111. offset += indiceArray[index];
  23112. index++;
  23113. }
  23114. }
  23115. return meshSubclass;
  23116. };
  23117. // Consts
  23118. Mesh._FRONTSIDE = 0;
  23119. Mesh._BACKSIDE = 1;
  23120. Mesh._DOUBLESIDE = 2;
  23121. Mesh._DEFAULTSIDE = 0;
  23122. Mesh._NO_CAP = 0;
  23123. Mesh._CAP_START = 1;
  23124. Mesh._CAP_END = 2;
  23125. Mesh._CAP_ALL = 3;
  23126. return Mesh;
  23127. }(BABYLON.AbstractMesh));
  23128. BABYLON.Mesh = Mesh;
  23129. })(BABYLON || (BABYLON = {}));
  23130. //# sourceMappingURL=babylon.mesh.js.map
  23131. var BABYLON;
  23132. (function (BABYLON) {
  23133. var BaseSubMesh = (function () {
  23134. function BaseSubMesh() {
  23135. }
  23136. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  23137. get: function () {
  23138. return this._materialEffect;
  23139. },
  23140. enumerable: true,
  23141. configurable: true
  23142. });
  23143. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  23144. if (this._materialEffect === effect) {
  23145. if (!effect) {
  23146. this._materialDefines = undefined;
  23147. }
  23148. return;
  23149. }
  23150. this._materialDefines = defines;
  23151. this._materialEffect = effect;
  23152. };
  23153. return BaseSubMesh;
  23154. }());
  23155. BABYLON.BaseSubMesh = BaseSubMesh;
  23156. var SubMesh = (function (_super) {
  23157. __extends(SubMesh, _super);
  23158. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  23159. if (createBoundingBox === void 0) { createBoundingBox = true; }
  23160. var _this = _super.call(this) || this;
  23161. _this.materialIndex = materialIndex;
  23162. _this.verticesStart = verticesStart;
  23163. _this.verticesCount = verticesCount;
  23164. _this.indexStart = indexStart;
  23165. _this.indexCount = indexCount;
  23166. _this._renderId = 0;
  23167. _this._mesh = mesh;
  23168. _this._renderingMesh = renderingMesh || mesh;
  23169. mesh.subMeshes.push(_this);
  23170. _this._trianglePlanes = [];
  23171. _this._id = mesh.subMeshes.length - 1;
  23172. if (createBoundingBox) {
  23173. _this.refreshBoundingInfo();
  23174. mesh.computeWorldMatrix(true);
  23175. }
  23176. return _this;
  23177. }
  23178. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  23179. get: function () {
  23180. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  23181. },
  23182. enumerable: true,
  23183. configurable: true
  23184. });
  23185. /**
  23186. * Returns the submesh BoudingInfo object.
  23187. */
  23188. SubMesh.prototype.getBoundingInfo = function () {
  23189. if (this.IsGlobal) {
  23190. return this._mesh.getBoundingInfo();
  23191. }
  23192. return this._boundingInfo;
  23193. };
  23194. /**
  23195. * Sets the submesh BoundingInfo.
  23196. * Return the SubMesh.
  23197. */
  23198. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  23199. this._boundingInfo = boundingInfo;
  23200. return this;
  23201. };
  23202. /**
  23203. * Returns the mesh of the current submesh.
  23204. */
  23205. SubMesh.prototype.getMesh = function () {
  23206. return this._mesh;
  23207. };
  23208. /**
  23209. * Returns the rendering mesh of the submesh.
  23210. */
  23211. SubMesh.prototype.getRenderingMesh = function () {
  23212. return this._renderingMesh;
  23213. };
  23214. /**
  23215. * Returns the submesh material.
  23216. */
  23217. SubMesh.prototype.getMaterial = function () {
  23218. var rootMaterial = this._renderingMesh.material;
  23219. if (rootMaterial && rootMaterial.getSubMaterial) {
  23220. var multiMaterial = rootMaterial;
  23221. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  23222. if (this._currentMaterial !== effectiveMaterial) {
  23223. this._currentMaterial = effectiveMaterial;
  23224. this._materialDefines = undefined;
  23225. }
  23226. return effectiveMaterial;
  23227. }
  23228. if (!rootMaterial) {
  23229. return this._mesh.getScene().defaultMaterial;
  23230. }
  23231. return rootMaterial;
  23232. };
  23233. // Methods
  23234. /**
  23235. * Sets a new updated BoundingInfo object to the submesh.
  23236. * Returns the SubMesh.
  23237. */
  23238. SubMesh.prototype.refreshBoundingInfo = function () {
  23239. this._lastColliderWorldVertices = null;
  23240. if (this.IsGlobal) {
  23241. return;
  23242. }
  23243. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23244. if (!data) {
  23245. this._boundingInfo = this._mesh._boundingInfo;
  23246. return;
  23247. }
  23248. var indices = this._renderingMesh.getIndices();
  23249. var extend;
  23250. //is this the only submesh?
  23251. if (this.indexStart === 0 && this.indexCount === indices.length) {
  23252. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  23253. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  23254. }
  23255. else {
  23256. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  23257. }
  23258. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23259. return this;
  23260. };
  23261. SubMesh.prototype._checkCollision = function (collider) {
  23262. return this.getBoundingInfo()._checkCollision(collider);
  23263. };
  23264. /**
  23265. * Updates the submesh BoundingInfo.
  23266. * Returns the Submesh.
  23267. */
  23268. SubMesh.prototype.updateBoundingInfo = function (world) {
  23269. if (!this.getBoundingInfo()) {
  23270. this.refreshBoundingInfo();
  23271. }
  23272. this.getBoundingInfo().update(world);
  23273. return this;
  23274. };
  23275. /**
  23276. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  23277. * Boolean returned.
  23278. */
  23279. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  23280. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  23281. };
  23282. /**
  23283. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  23284. * Boolean returned.
  23285. */
  23286. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  23287. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  23288. };
  23289. /**
  23290. * Renders the submesh.
  23291. * Returns it.
  23292. */
  23293. SubMesh.prototype.render = function (enableAlphaMode) {
  23294. this._renderingMesh.render(this, enableAlphaMode);
  23295. return this;
  23296. };
  23297. /**
  23298. * Returns a new Index Buffer.
  23299. * Type returned : WebGLBuffer.
  23300. */
  23301. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  23302. if (!this._linesIndexBuffer) {
  23303. var linesIndices = [];
  23304. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23305. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  23306. }
  23307. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  23308. this.linesIndexCount = linesIndices.length;
  23309. }
  23310. return this._linesIndexBuffer;
  23311. };
  23312. /**
  23313. * True is the passed Ray intersects the submesh bounding box.
  23314. * Boolean returned.
  23315. */
  23316. SubMesh.prototype.canIntersects = function (ray) {
  23317. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  23318. };
  23319. /**
  23320. * Returns an object IntersectionInfo.
  23321. */
  23322. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  23323. var intersectInfo = null;
  23324. // LineMesh first as it's also a Mesh...
  23325. if (this._mesh instanceof BABYLON.LinesMesh) {
  23326. var lineMesh = this._mesh;
  23327. // Line test
  23328. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  23329. var p0 = positions[indices[index]];
  23330. var p1 = positions[indices[index + 1]];
  23331. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  23332. if (length < 0) {
  23333. continue;
  23334. }
  23335. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  23336. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  23337. if (fastCheck) {
  23338. break;
  23339. }
  23340. }
  23341. }
  23342. }
  23343. else {
  23344. // Triangles test
  23345. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23346. var p0 = positions[indices[index]];
  23347. var p1 = positions[indices[index + 1]];
  23348. var p2 = positions[indices[index + 2]];
  23349. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  23350. if (currentIntersectInfo) {
  23351. if (currentIntersectInfo.distance < 0) {
  23352. continue;
  23353. }
  23354. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  23355. intersectInfo = currentIntersectInfo;
  23356. intersectInfo.faceId = index / 3;
  23357. if (fastCheck) {
  23358. break;
  23359. }
  23360. }
  23361. }
  23362. }
  23363. }
  23364. return intersectInfo;
  23365. };
  23366. // Clone
  23367. /**
  23368. * Creates a new Submesh from the passed Mesh.
  23369. */
  23370. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  23371. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  23372. if (!this.IsGlobal) {
  23373. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  23374. }
  23375. return result;
  23376. };
  23377. // Dispose
  23378. /**
  23379. * Disposes the Submesh.
  23380. * Returns nothing.
  23381. */
  23382. SubMesh.prototype.dispose = function () {
  23383. if (this._linesIndexBuffer) {
  23384. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  23385. this._linesIndexBuffer = null;
  23386. }
  23387. // Remove from mesh
  23388. var index = this._mesh.subMeshes.indexOf(this);
  23389. this._mesh.subMeshes.splice(index, 1);
  23390. };
  23391. // Statics
  23392. /**
  23393. * Creates a new Submesh from the passed parameters :
  23394. * - materialIndex (integer) : the index of the main mesh material.
  23395. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  23396. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  23397. * - mesh (Mesh) : the main mesh to create the submesh from.
  23398. * - renderingMesh (optional Mesh) : rendering mesh.
  23399. */
  23400. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  23401. var minVertexIndex = Number.MAX_VALUE;
  23402. var maxVertexIndex = -Number.MAX_VALUE;
  23403. renderingMesh = renderingMesh || mesh;
  23404. var indices = renderingMesh.getIndices();
  23405. for (var index = startIndex; index < startIndex + indexCount; index++) {
  23406. var vertexIndex = indices[index];
  23407. if (vertexIndex < minVertexIndex)
  23408. minVertexIndex = vertexIndex;
  23409. if (vertexIndex > maxVertexIndex)
  23410. maxVertexIndex = vertexIndex;
  23411. }
  23412. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  23413. };
  23414. return SubMesh;
  23415. }(BaseSubMesh));
  23416. BABYLON.SubMesh = SubMesh;
  23417. })(BABYLON || (BABYLON = {}));
  23418. //# sourceMappingURL=babylon.subMesh.js.map
  23419. var BABYLON;
  23420. (function (BABYLON) {
  23421. var EffectFallbacks = (function () {
  23422. function EffectFallbacks() {
  23423. this._defines = {};
  23424. this._currentRank = 32;
  23425. this._maxRank = -1;
  23426. }
  23427. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23428. if (!this._defines[rank]) {
  23429. if (rank < this._currentRank) {
  23430. this._currentRank = rank;
  23431. }
  23432. if (rank > this._maxRank) {
  23433. this._maxRank = rank;
  23434. }
  23435. this._defines[rank] = new Array();
  23436. }
  23437. this._defines[rank].push(define);
  23438. };
  23439. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23440. this._meshRank = rank;
  23441. this._mesh = mesh;
  23442. if (rank < this._currentRank) {
  23443. this._currentRank = rank;
  23444. }
  23445. if (rank > this._maxRank) {
  23446. this._maxRank = rank;
  23447. }
  23448. };
  23449. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23450. get: function () {
  23451. return this._currentRank <= this._maxRank;
  23452. },
  23453. enumerable: true,
  23454. configurable: true
  23455. });
  23456. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23457. // First we try to switch to CPU skinning
  23458. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  23459. this._mesh.computeBonesUsingShaders = false;
  23460. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23461. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23462. var scene = this._mesh.getScene();
  23463. for (var index = 0; index < scene.meshes.length; index++) {
  23464. var otherMesh = scene.meshes[index];
  23465. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  23466. otherMesh.computeBonesUsingShaders = false;
  23467. }
  23468. }
  23469. }
  23470. else {
  23471. var currentFallbacks = this._defines[this._currentRank];
  23472. if (currentFallbacks) {
  23473. for (var index = 0; index < currentFallbacks.length; index++) {
  23474. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23475. }
  23476. }
  23477. this._currentRank++;
  23478. }
  23479. return currentDefines;
  23480. };
  23481. return EffectFallbacks;
  23482. }());
  23483. BABYLON.EffectFallbacks = EffectFallbacks;
  23484. var EffectCreationOptions = (function () {
  23485. function EffectCreationOptions() {
  23486. }
  23487. return EffectCreationOptions;
  23488. }());
  23489. BABYLON.EffectCreationOptions = EffectCreationOptions;
  23490. var Effect = (function () {
  23491. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23492. var _this = this;
  23493. this.uniqueId = 0;
  23494. this.onCompileObservable = new BABYLON.Observable();
  23495. this.onErrorObservable = new BABYLON.Observable();
  23496. this.onBindObservable = new BABYLON.Observable();
  23497. this._uniformBuffersNames = {};
  23498. this._isReady = false;
  23499. this._compilationError = "";
  23500. this._valueCache = {};
  23501. this.name = baseName;
  23502. if (attributesNamesOrOptions.attributes) {
  23503. var options = attributesNamesOrOptions;
  23504. this._engine = uniformsNamesOrEngine;
  23505. this._attributesNames = options.attributes;
  23506. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  23507. this._samplers = options.samplers;
  23508. this.defines = options.defines;
  23509. this.onError = options.onError;
  23510. this.onCompiled = options.onCompiled;
  23511. this._fallbacks = options.fallbacks;
  23512. this._indexParameters = options.indexParameters;
  23513. if (options.uniformBuffersNames) {
  23514. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  23515. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  23516. }
  23517. }
  23518. }
  23519. else {
  23520. this._engine = engine;
  23521. this.defines = defines;
  23522. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  23523. this._samplers = samplers;
  23524. this._attributesNames = attributesNamesOrOptions;
  23525. this.onError = onError;
  23526. this.onCompiled = onCompiled;
  23527. this._indexParameters = indexParameters;
  23528. this._fallbacks = fallbacks;
  23529. }
  23530. this.uniqueId = Effect._uniqueIdSeed++;
  23531. var vertexSource;
  23532. var fragmentSource;
  23533. if (baseName.vertexElement) {
  23534. vertexSource = document.getElementById(baseName.vertexElement);
  23535. if (!vertexSource) {
  23536. vertexSource = baseName.vertexElement;
  23537. }
  23538. }
  23539. else {
  23540. vertexSource = baseName.vertex || baseName;
  23541. }
  23542. if (baseName.fragmentElement) {
  23543. fragmentSource = document.getElementById(baseName.fragmentElement);
  23544. if (!fragmentSource) {
  23545. fragmentSource = baseName.fragmentElement;
  23546. }
  23547. }
  23548. else {
  23549. fragmentSource = baseName.fragment || baseName;
  23550. }
  23551. this._loadVertexShader(vertexSource, function (vertexCode) {
  23552. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23553. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  23554. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23555. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23556. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  23557. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks, baseName);
  23558. });
  23559. });
  23560. });
  23561. });
  23562. });
  23563. });
  23564. }
  23565. Object.defineProperty(Effect.prototype, "key", {
  23566. get: function () {
  23567. return this._key;
  23568. },
  23569. enumerable: true,
  23570. configurable: true
  23571. });
  23572. // Properties
  23573. Effect.prototype.isReady = function () {
  23574. return this._isReady;
  23575. };
  23576. Effect.prototype.getEngine = function () {
  23577. return this._engine;
  23578. };
  23579. Effect.prototype.getProgram = function () {
  23580. return this._program;
  23581. };
  23582. Effect.prototype.getAttributesNames = function () {
  23583. return this._attributesNames;
  23584. };
  23585. Effect.prototype.getAttributeLocation = function (index) {
  23586. return this._attributes[index];
  23587. };
  23588. Effect.prototype.getAttributeLocationByName = function (name) {
  23589. var index = this._attributesNames.indexOf(name);
  23590. return this._attributes[index];
  23591. };
  23592. Effect.prototype.getAttributesCount = function () {
  23593. return this._attributes.length;
  23594. };
  23595. Effect.prototype.getUniformIndex = function (uniformName) {
  23596. return this._uniformsNames.indexOf(uniformName);
  23597. };
  23598. Effect.prototype.getUniform = function (uniformName) {
  23599. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  23600. };
  23601. Effect.prototype.getSamplers = function () {
  23602. return this._samplers;
  23603. };
  23604. Effect.prototype.getCompilationError = function () {
  23605. return this._compilationError;
  23606. };
  23607. Effect.prototype.getVertexShaderSource = function () {
  23608. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  23609. };
  23610. Effect.prototype.getFragmentShaderSource = function () {
  23611. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  23612. };
  23613. // Methods
  23614. Effect.prototype.executeWhenCompiled = function (func) {
  23615. if (this.isReady()) {
  23616. func(this);
  23617. return;
  23618. }
  23619. this.onCompileObservable.add(function (effect) {
  23620. func(effect);
  23621. });
  23622. };
  23623. Effect.prototype._loadVertexShader = function (vertex, callback) {
  23624. // DOM element ?
  23625. if (vertex instanceof HTMLElement) {
  23626. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  23627. callback(vertexCode);
  23628. return;
  23629. }
  23630. // Base64 encoded ?
  23631. if (vertex.substr(0, 7) === "base64:") {
  23632. var vertexBinary = window.atob(vertex.substr(7));
  23633. callback(vertexBinary);
  23634. return;
  23635. }
  23636. // Is in local store ?
  23637. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  23638. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  23639. return;
  23640. }
  23641. var vertexShaderUrl;
  23642. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  23643. vertexShaderUrl = vertex;
  23644. }
  23645. else {
  23646. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  23647. }
  23648. // Vertex shader
  23649. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  23650. };
  23651. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  23652. // DOM element ?
  23653. if (fragment instanceof HTMLElement) {
  23654. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  23655. callback(fragmentCode);
  23656. return;
  23657. }
  23658. // Base64 encoded ?
  23659. if (fragment.substr(0, 7) === "base64:") {
  23660. var fragmentBinary = window.atob(fragment.substr(7));
  23661. callback(fragmentBinary);
  23662. return;
  23663. }
  23664. // Is in local store ?
  23665. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  23666. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  23667. return;
  23668. }
  23669. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  23670. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  23671. return;
  23672. }
  23673. var fragmentShaderUrl;
  23674. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  23675. fragmentShaderUrl = fragment;
  23676. }
  23677. else {
  23678. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  23679. }
  23680. // Fragment shader
  23681. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  23682. };
  23683. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  23684. // Rebuild shaders source code
  23685. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  23686. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  23687. vertexCode = prefix + vertexCode;
  23688. fragmentCode = prefix + fragmentCode;
  23689. // Number lines of shaders source code
  23690. var i = 2;
  23691. var regex = /\n/gm;
  23692. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  23693. i = 2;
  23694. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  23695. // Dump shaders name and formatted source code
  23696. if (this.name.vertexElement) {
  23697. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  23698. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  23699. }
  23700. else if (this.name.vertex) {
  23701. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  23702. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  23703. }
  23704. else {
  23705. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  23706. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  23707. }
  23708. };
  23709. ;
  23710. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  23711. var preparedSourceCode = this._processPrecision(sourceCode);
  23712. if (this._engine.webGLVersion == 1) {
  23713. callback(preparedSourceCode);
  23714. return;
  23715. }
  23716. // Already converted
  23717. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  23718. callback(preparedSourceCode.replace("#version 300 es", ""));
  23719. return;
  23720. }
  23721. // Remove extensions
  23722. // #extension GL_OES_standard_derivatives : enable
  23723. // #extension GL_EXT_shader_texture_lod : enable
  23724. // #extension GL_EXT_frag_depth : enable
  23725. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  23726. var result = preparedSourceCode.replace(regex, "");
  23727. // Migrate to GLSL v300
  23728. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  23729. result = result.replace(/attribute[ \t]/g, "in ");
  23730. result = result.replace(/[ \t]attribute/g, " in");
  23731. if (isFragment) {
  23732. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  23733. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  23734. result = result.replace(/texture2D\(/g, "texture(");
  23735. result = result.replace(/textureCube\(/g, "texture(");
  23736. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  23737. result = result.replace(/gl_FragColor/g, "glFragColor");
  23738. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  23739. }
  23740. callback(result);
  23741. };
  23742. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23743. var _this = this;
  23744. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23745. var match = regex.exec(sourceCode);
  23746. var returnValue = new String(sourceCode);
  23747. while (match != null) {
  23748. var includeFile = match[1];
  23749. // Uniform declaration
  23750. if (includeFile.indexOf("__decl__") !== -1) {
  23751. includeFile = includeFile.replace(/__decl__/, "");
  23752. if (this._engine.webGLVersion != 1) {
  23753. includeFile = includeFile.replace(/Vertex/, "Ubo");
  23754. includeFile = includeFile.replace(/Fragment/, "Ubo");
  23755. }
  23756. includeFile = includeFile + "Declaration";
  23757. }
  23758. if (Effect.IncludesShadersStore[includeFile]) {
  23759. // Substitution
  23760. var includeContent = Effect.IncludesShadersStore[includeFile];
  23761. if (match[2]) {
  23762. var splits = match[3].split(",");
  23763. for (var index = 0; index < splits.length; index += 2) {
  23764. var source = new RegExp(splits[index], "g");
  23765. var dest = splits[index + 1];
  23766. includeContent = includeContent.replace(source, dest);
  23767. }
  23768. }
  23769. if (match[4]) {
  23770. var indexString = match[5];
  23771. if (indexString.indexOf("..") !== -1) {
  23772. var indexSplits = indexString.split("..");
  23773. var minIndex = parseInt(indexSplits[0]);
  23774. var maxIndex = parseInt(indexSplits[1]);
  23775. var sourceIncludeContent = includeContent.slice(0);
  23776. includeContent = "";
  23777. if (isNaN(maxIndex)) {
  23778. maxIndex = this._indexParameters[indexSplits[1]];
  23779. }
  23780. for (var i = minIndex; i < maxIndex; i++) {
  23781. if (this._engine.webGLVersion === 1) {
  23782. // Ubo replacement
  23783. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  23784. return p1 + "{X}";
  23785. });
  23786. }
  23787. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23788. }
  23789. }
  23790. else {
  23791. if (this._engine.webGLVersion === 1) {
  23792. // Ubo replacement
  23793. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  23794. return p1 + "{X}";
  23795. });
  23796. }
  23797. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23798. }
  23799. }
  23800. // Replace
  23801. returnValue = returnValue.replace(match[0], includeContent);
  23802. }
  23803. else {
  23804. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23805. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23806. Effect.IncludesShadersStore[includeFile] = fileContent;
  23807. _this._processIncludes(returnValue, callback);
  23808. });
  23809. return;
  23810. }
  23811. match = regex.exec(sourceCode);
  23812. }
  23813. callback(returnValue);
  23814. };
  23815. Effect.prototype._processPrecision = function (source) {
  23816. if (source.indexOf("precision highp float") === -1) {
  23817. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23818. source = "precision mediump float;\n" + source;
  23819. }
  23820. else {
  23821. source = "precision highp float;\n" + source;
  23822. }
  23823. }
  23824. else {
  23825. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23826. source = source.replace("precision highp float", "precision mediump float");
  23827. }
  23828. }
  23829. return source;
  23830. };
  23831. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks, baseName) {
  23832. try {
  23833. var engine = this._engine;
  23834. if (baseName) {
  23835. vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + vertexSourceCode;
  23836. fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + fragmentSourceCode;
  23837. }
  23838. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23839. if (engine.webGLVersion > 1) {
  23840. for (var name in this._uniformBuffersNames) {
  23841. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  23842. }
  23843. }
  23844. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23845. this._attributes = engine.getAttributes(this._program, attributesNames);
  23846. var index;
  23847. for (index = 0; index < this._samplers.length; index++) {
  23848. var sampler = this.getUniform(this._samplers[index]);
  23849. if (sampler == null) {
  23850. this._samplers.splice(index, 1);
  23851. index--;
  23852. }
  23853. }
  23854. engine.bindSamplers(this);
  23855. this._compilationError = "";
  23856. this._isReady = true;
  23857. if (this.onCompiled) {
  23858. this.onCompiled(this);
  23859. }
  23860. this.onCompileObservable.notifyObservers(this);
  23861. this.onCompileObservable.clear();
  23862. }
  23863. catch (e) {
  23864. this._compilationError = e.message;
  23865. // Let's go through fallbacks then
  23866. BABYLON.Tools.Error("Unable to compile effect:");
  23867. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  23868. return " " + uniform;
  23869. }));
  23870. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  23871. return " " + attribute;
  23872. }));
  23873. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  23874. BABYLON.Tools.Error("Error: " + this._compilationError);
  23875. if (fallbacks && fallbacks.isMoreFallbacks) {
  23876. BABYLON.Tools.Error("Trying next fallback.");
  23877. defines = fallbacks.reduce(defines);
  23878. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23879. }
  23880. else {
  23881. if (this.onError) {
  23882. this.onError(this, this._compilationError);
  23883. }
  23884. this.onErrorObservable.notifyObservers(this);
  23885. }
  23886. }
  23887. };
  23888. Object.defineProperty(Effect.prototype, "isSupported", {
  23889. get: function () {
  23890. return this._compilationError === "";
  23891. },
  23892. enumerable: true,
  23893. configurable: true
  23894. });
  23895. Effect.prototype._bindTexture = function (channel, texture) {
  23896. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23897. };
  23898. Effect.prototype.setTexture = function (channel, texture) {
  23899. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23900. };
  23901. Effect.prototype.setTextureArray = function (channel, textures) {
  23902. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23903. var initialPos = this._samplers.indexOf(channel);
  23904. for (var index = 1; index < textures.length; index++) {
  23905. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23906. }
  23907. }
  23908. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23909. };
  23910. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23911. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23912. };
  23913. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23914. var cache = this._valueCache[uniformName];
  23915. var flag = matrix.updateFlag;
  23916. if (cache !== undefined && cache === flag) {
  23917. return false;
  23918. }
  23919. this._valueCache[uniformName] = flag;
  23920. return true;
  23921. };
  23922. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23923. var cache = this._valueCache[uniformName];
  23924. if (!cache) {
  23925. cache = [x, y];
  23926. this._valueCache[uniformName] = cache;
  23927. return true;
  23928. }
  23929. var changed = false;
  23930. if (cache[0] !== x) {
  23931. cache[0] = x;
  23932. changed = true;
  23933. }
  23934. if (cache[1] !== y) {
  23935. cache[1] = y;
  23936. changed = true;
  23937. }
  23938. return changed;
  23939. };
  23940. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23941. var cache = this._valueCache[uniformName];
  23942. if (!cache) {
  23943. cache = [x, y, z];
  23944. this._valueCache[uniformName] = cache;
  23945. return true;
  23946. }
  23947. var changed = false;
  23948. if (cache[0] !== x) {
  23949. cache[0] = x;
  23950. changed = true;
  23951. }
  23952. if (cache[1] !== y) {
  23953. cache[1] = y;
  23954. changed = true;
  23955. }
  23956. if (cache[2] !== z) {
  23957. cache[2] = z;
  23958. changed = true;
  23959. }
  23960. return changed;
  23961. };
  23962. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23963. var cache = this._valueCache[uniformName];
  23964. if (!cache) {
  23965. cache = [x, y, z, w];
  23966. this._valueCache[uniformName] = cache;
  23967. return true;
  23968. }
  23969. var changed = false;
  23970. if (cache[0] !== x) {
  23971. cache[0] = x;
  23972. changed = true;
  23973. }
  23974. if (cache[1] !== y) {
  23975. cache[1] = y;
  23976. changed = true;
  23977. }
  23978. if (cache[2] !== z) {
  23979. cache[2] = z;
  23980. changed = true;
  23981. }
  23982. if (cache[3] !== w) {
  23983. cache[3] = w;
  23984. changed = true;
  23985. }
  23986. return changed;
  23987. };
  23988. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  23989. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  23990. return;
  23991. }
  23992. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  23993. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  23994. };
  23995. Effect.prototype.bindUniformBlock = function (blockName, index) {
  23996. this._engine.bindUniformBlock(this._program, blockName, index);
  23997. };
  23998. Effect.prototype.setIntArray = function (uniformName, array) {
  23999. this._valueCache[uniformName] = null;
  24000. this._engine.setIntArray(this.getUniform(uniformName), array);
  24001. return this;
  24002. };
  24003. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24004. this._valueCache[uniformName] = null;
  24005. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24006. return this;
  24007. };
  24008. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24009. this._valueCache[uniformName] = null;
  24010. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24011. return this;
  24012. };
  24013. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24014. this._valueCache[uniformName] = null;
  24015. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24016. return this;
  24017. };
  24018. Effect.prototype.setFloatArray = function (uniformName, array) {
  24019. this._valueCache[uniformName] = null;
  24020. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24021. return this;
  24022. };
  24023. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24024. this._valueCache[uniformName] = null;
  24025. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24026. return this;
  24027. };
  24028. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24029. this._valueCache[uniformName] = null;
  24030. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24031. return this;
  24032. };
  24033. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24034. this._valueCache[uniformName] = null;
  24035. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24036. return this;
  24037. };
  24038. Effect.prototype.setArray = function (uniformName, array) {
  24039. this._valueCache[uniformName] = null;
  24040. this._engine.setArray(this.getUniform(uniformName), array);
  24041. return this;
  24042. };
  24043. Effect.prototype.setArray2 = function (uniformName, array) {
  24044. this._valueCache[uniformName] = null;
  24045. this._engine.setArray2(this.getUniform(uniformName), array);
  24046. return this;
  24047. };
  24048. Effect.prototype.setArray3 = function (uniformName, array) {
  24049. this._valueCache[uniformName] = null;
  24050. this._engine.setArray3(this.getUniform(uniformName), array);
  24051. return this;
  24052. };
  24053. Effect.prototype.setArray4 = function (uniformName, array) {
  24054. this._valueCache[uniformName] = null;
  24055. this._engine.setArray4(this.getUniform(uniformName), array);
  24056. return this;
  24057. };
  24058. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24059. if (!matrices) {
  24060. return;
  24061. }
  24062. this._valueCache[uniformName] = null;
  24063. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24064. return this;
  24065. };
  24066. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24067. if (this._cacheMatrix(uniformName, matrix)) {
  24068. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24069. }
  24070. return this;
  24071. };
  24072. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24073. this._valueCache[uniformName] = null;
  24074. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24075. return this;
  24076. };
  24077. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24078. this._valueCache[uniformName] = null;
  24079. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24080. return this;
  24081. };
  24082. Effect.prototype.setFloat = function (uniformName, value) {
  24083. var cache = this._valueCache[uniformName];
  24084. if (cache !== undefined && cache === value)
  24085. return this;
  24086. this._valueCache[uniformName] = value;
  24087. this._engine.setFloat(this.getUniform(uniformName), value);
  24088. return this;
  24089. };
  24090. Effect.prototype.setBool = function (uniformName, bool) {
  24091. var cache = this._valueCache[uniformName];
  24092. if (cache !== undefined && cache === bool)
  24093. return this;
  24094. this._valueCache[uniformName] = bool;
  24095. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24096. return this;
  24097. };
  24098. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24099. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24100. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24101. }
  24102. return this;
  24103. };
  24104. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24105. if (this._cacheFloat2(uniformName, x, y)) {
  24106. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24107. }
  24108. return this;
  24109. };
  24110. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24111. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24112. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24113. }
  24114. return this;
  24115. };
  24116. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24117. if (this._cacheFloat3(uniformName, x, y, z)) {
  24118. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24119. }
  24120. return this;
  24121. };
  24122. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24123. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24124. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24125. }
  24126. return this;
  24127. };
  24128. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24129. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24130. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24131. }
  24132. return this;
  24133. };
  24134. Effect.prototype.setColor3 = function (uniformName, color3) {
  24135. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24136. this._engine.setColor3(this.getUniform(uniformName), color3);
  24137. }
  24138. return this;
  24139. };
  24140. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24141. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24142. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24143. }
  24144. return this;
  24145. };
  24146. Effect.prototype._recombineShader = function (node) {
  24147. if (node.define) {
  24148. if (node.condition) {
  24149. var defineIndex = this.defines.indexOf("#define " + node.define);
  24150. if (defineIndex === -1) {
  24151. return null;
  24152. }
  24153. var nextComma = this.defines.indexOf("\n", defineIndex);
  24154. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  24155. var condition = defineValue + node.condition;
  24156. if (!eval(condition)) {
  24157. return null;
  24158. }
  24159. }
  24160. else if (node.ndef) {
  24161. if (this.defines.indexOf("#define " + node.define) !== -1) {
  24162. return null;
  24163. }
  24164. }
  24165. else if (this.defines.indexOf("#define " + node.define) === -1) {
  24166. return null;
  24167. }
  24168. }
  24169. var result = "";
  24170. for (var index = 0; index < node.children.length; index++) {
  24171. var line = node.children[index];
  24172. if (line.children) {
  24173. var combined = this._recombineShader(line);
  24174. if (combined !== null) {
  24175. result += combined + "\r\n";
  24176. }
  24177. continue;
  24178. }
  24179. if (line.length > 0) {
  24180. result += line + "\r\n";
  24181. }
  24182. }
  24183. return result;
  24184. };
  24185. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  24186. var root = {
  24187. children: []
  24188. };
  24189. var currentNode = root;
  24190. var lines = shaderString.split("\n");
  24191. for (var index = 0; index < lines.length; index++) {
  24192. var line = lines[index].trim();
  24193. // #ifdef
  24194. var pos = line.indexOf("#ifdef ");
  24195. if (pos !== -1) {
  24196. var define = line.substr(pos + 7);
  24197. var newNode = {
  24198. condition: null,
  24199. ndef: false,
  24200. define: define,
  24201. children: [],
  24202. parent: currentNode
  24203. };
  24204. currentNode.children.push(newNode);
  24205. currentNode = newNode;
  24206. continue;
  24207. }
  24208. // #ifndef
  24209. var pos = line.indexOf("#ifndef ");
  24210. if (pos !== -1) {
  24211. var define = line.substr(pos + 8);
  24212. newNode = {
  24213. condition: null,
  24214. define: define,
  24215. ndef: true,
  24216. children: [],
  24217. parent: currentNode
  24218. };
  24219. currentNode.children.push(newNode);
  24220. currentNode = newNode;
  24221. continue;
  24222. }
  24223. // #if
  24224. var pos = line.indexOf("#if ");
  24225. if (pos !== -1) {
  24226. var define = line.substr(pos + 4).trim();
  24227. var conditionPos = define.indexOf(" ");
  24228. newNode = {
  24229. condition: define.substr(conditionPos + 1),
  24230. define: define.substr(0, conditionPos),
  24231. ndef: false,
  24232. children: [],
  24233. parent: currentNode
  24234. };
  24235. currentNode.children.push(newNode);
  24236. currentNode = newNode;
  24237. continue;
  24238. }
  24239. // #endif
  24240. pos = line.indexOf("#endif");
  24241. if (pos !== -1) {
  24242. currentNode = currentNode.parent;
  24243. continue;
  24244. }
  24245. currentNode.children.push(line);
  24246. }
  24247. // Recombine
  24248. return this._recombineShader(root);
  24249. };
  24250. Effect.ResetCache = function () {
  24251. Effect._baseCache = {};
  24252. };
  24253. Effect._uniqueIdSeed = 0;
  24254. Effect._baseCache = {};
  24255. // Statics
  24256. Effect.ShadersStore = {};
  24257. Effect.IncludesShadersStore = {};
  24258. return Effect;
  24259. }());
  24260. BABYLON.Effect = Effect;
  24261. })(BABYLON || (BABYLON = {}));
  24262. //# sourceMappingURL=babylon.effect.js.map
  24263. var BABYLON;
  24264. (function (BABYLON) {
  24265. var MaterialHelper = (function () {
  24266. function MaterialHelper() {
  24267. }
  24268. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24269. defines._needUVs = true;
  24270. defines[key] = true;
  24271. if (texture.getTextureMatrix().isIdentity(true)) {
  24272. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24273. if (texture.coordinatesIndex === 0) {
  24274. defines["MAINUV1"] = true;
  24275. }
  24276. else {
  24277. defines["MAINUV2"] = true;
  24278. }
  24279. }
  24280. else {
  24281. defines[key + "DIRECTUV"] = 0;
  24282. }
  24283. };
  24284. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24285. var matrix = texture.getTextureMatrix();
  24286. if (!matrix.isIdentity(true)) {
  24287. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  24288. }
  24289. };
  24290. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  24291. if (defines._areMiscDirty) {
  24292. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  24293. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  24294. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  24295. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  24296. }
  24297. };
  24298. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  24299. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  24300. var changed = false;
  24301. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  24302. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  24303. changed = true;
  24304. }
  24305. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  24306. defines["ALPHATEST"] = !defines["ALPHATEST"];
  24307. changed = true;
  24308. }
  24309. if (defines["INSTANCES"] !== useInstances) {
  24310. defines["INSTANCES"] = useInstances;
  24311. changed = true;
  24312. }
  24313. if (changed) {
  24314. defines.markAsUnprocessed();
  24315. }
  24316. };
  24317. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  24318. if (useMorphTargets === void 0) { useMorphTargets = false; }
  24319. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  24320. return false;
  24321. }
  24322. defines._normals = defines._needNormals;
  24323. defines._uvs = defines._needUVs;
  24324. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  24325. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24326. defines["TANGENT"] = true;
  24327. }
  24328. if (defines._needUVs) {
  24329. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  24330. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  24331. }
  24332. else {
  24333. defines["UV1"] = false;
  24334. defines["UV2"] = false;
  24335. }
  24336. if (useVertexColor) {
  24337. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  24338. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  24339. }
  24340. if (useBones) {
  24341. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24342. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  24343. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  24344. }
  24345. else {
  24346. defines["NUM_BONE_INFLUENCERS"] = 0;
  24347. defines["BonesPerMesh"] = 0;
  24348. }
  24349. }
  24350. if (useMorphTargets) {
  24351. if (mesh.morphTargetManager) {
  24352. var manager = mesh.morphTargetManager;
  24353. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  24354. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  24355. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  24356. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  24357. }
  24358. else {
  24359. defines["MORPHTARGETS_TANGENT"] = false;
  24360. defines["MORPHTARGETS_NORMAL"] = false;
  24361. defines["MORPHTARGETS"] = false;
  24362. defines["NUM_MORPH_INFLUENCERS"] = 0;
  24363. }
  24364. }
  24365. return true;
  24366. };
  24367. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  24368. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24369. if (disableLighting === void 0) { disableLighting = false; }
  24370. if (!defines._areLightsDirty) {
  24371. return defines._needNormals;
  24372. }
  24373. var lightIndex = 0;
  24374. var needNormals = false;
  24375. var needRebuild = false;
  24376. var lightmapMode = false;
  24377. var shadowEnabled = false;
  24378. var specularEnabled = false;
  24379. if (scene.lightsEnabled && !disableLighting) {
  24380. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24381. var light = _a[_i];
  24382. needNormals = true;
  24383. if (defines["LIGHT" + lightIndex] === undefined) {
  24384. needRebuild = true;
  24385. }
  24386. defines["LIGHT" + lightIndex] = true;
  24387. defines["SPOTLIGHT" + lightIndex] = false;
  24388. defines["HEMILIGHT" + lightIndex] = false;
  24389. defines["POINTLIGHT" + lightIndex] = false;
  24390. defines["DIRLIGHT" + lightIndex] = false;
  24391. var type;
  24392. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  24393. type = "SPOTLIGHT" + lightIndex;
  24394. }
  24395. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  24396. type = "HEMILIGHT" + lightIndex;
  24397. }
  24398. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  24399. type = "POINTLIGHT" + lightIndex;
  24400. }
  24401. else {
  24402. type = "DIRLIGHT" + lightIndex;
  24403. }
  24404. defines[type] = true;
  24405. // Specular
  24406. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  24407. specularEnabled = true;
  24408. }
  24409. // Shadows
  24410. defines["SHADOW" + lightIndex] = false;
  24411. defines["SHADOWPCF" + lightIndex] = false;
  24412. defines["SHADOWESM" + lightIndex] = false;
  24413. defines["SHADOWCUBE" + lightIndex] = false;
  24414. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  24415. var shadowGenerator = light.getShadowGenerator();
  24416. if (shadowGenerator) {
  24417. shadowEnabled = true;
  24418. shadowGenerator.prepareDefines(defines, lightIndex);
  24419. }
  24420. }
  24421. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24422. lightmapMode = true;
  24423. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24424. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  24425. }
  24426. else {
  24427. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  24428. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  24429. }
  24430. lightIndex++;
  24431. if (lightIndex === maxSimultaneousLights)
  24432. break;
  24433. }
  24434. }
  24435. defines["SPECULARTERM"] = specularEnabled;
  24436. defines["SHADOWS"] = shadowEnabled;
  24437. // Resetting all other lights if any
  24438. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  24439. if (defines["LIGHT" + index] !== undefined) {
  24440. defines["LIGHT" + index] = false;
  24441. defines["HEMILIGHT" + lightIndex] = false;
  24442. defines["POINTLIGHT" + lightIndex] = false;
  24443. defines["DIRLIGHT" + lightIndex] = false;
  24444. defines["SPOTLIGHT" + lightIndex] = false;
  24445. defines["SHADOW" + lightIndex] = false;
  24446. }
  24447. }
  24448. var caps = scene.getEngine().getCaps();
  24449. if (defines["SHADOWFLOAT"] === undefined) {
  24450. needRebuild = true;
  24451. }
  24452. defines["SHADOWFLOAT"] = shadowEnabled &&
  24453. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  24454. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  24455. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  24456. if (needRebuild) {
  24457. defines.rebuild();
  24458. }
  24459. return needNormals;
  24460. };
  24461. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  24462. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24463. var uniformsList, uniformBuffersList, samplersList, defines;
  24464. if (uniformsListOrOptions.uniformsNames) {
  24465. var options = uniformsListOrOptions;
  24466. uniformsList = options.uniformsNames;
  24467. uniformBuffersList = options.uniformBuffersNames;
  24468. samplersList = options.samplers;
  24469. defines = options.defines;
  24470. maxSimultaneousLights = options.maxSimultaneousLights;
  24471. }
  24472. else {
  24473. uniformsList = uniformsListOrOptions;
  24474. }
  24475. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24476. if (!defines["LIGHT" + lightIndex]) {
  24477. break;
  24478. }
  24479. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  24480. if (uniformBuffersList) {
  24481. uniformBuffersList.push("Light" + lightIndex);
  24482. }
  24483. samplersList.push("shadowSampler" + lightIndex);
  24484. }
  24485. if (defines["NUM_MORPH_INFLUENCERS"]) {
  24486. uniformsList.push("morphTargetInfluences");
  24487. }
  24488. };
  24489. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24490. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24491. if (!defines["SHADOWS"]) {
  24492. return;
  24493. }
  24494. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24495. if (!defines["LIGHT" + lightIndex]) {
  24496. break;
  24497. }
  24498. if (lightIndex > 0) {
  24499. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24500. }
  24501. if (defines["SHADOW" + lightIndex]) {
  24502. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24503. }
  24504. if (defines["SHADOWPCF" + lightIndex]) {
  24505. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24506. }
  24507. if (defines["SHADOWESM" + lightIndex]) {
  24508. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  24509. }
  24510. }
  24511. };
  24512. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  24513. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  24514. if (influencers > 0) {
  24515. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  24516. var manager = mesh.morphTargetManager;
  24517. var normal = manager.supportsNormals && defines["NORMAL"];
  24518. var tangent = manager.supportsTangents && defines["TANGENT"];
  24519. for (var index = 0; index < influencers; index++) {
  24520. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  24521. if (normal) {
  24522. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  24523. }
  24524. if (tangent) {
  24525. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  24526. }
  24527. if (attribs.length > maxAttributesCount) {
  24528. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  24529. }
  24530. }
  24531. }
  24532. };
  24533. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24534. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24535. fallbacks.addCPUSkinningFallback(0, mesh);
  24536. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24537. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24538. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24539. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24540. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24541. }
  24542. }
  24543. };
  24544. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24545. if (defines["INSTANCES"]) {
  24546. attribs.push("world0");
  24547. attribs.push("world1");
  24548. attribs.push("world2");
  24549. attribs.push("world3");
  24550. }
  24551. };
  24552. // Bindings
  24553. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  24554. if (light.shadowEnabled && mesh.receiveShadows) {
  24555. var shadowGenerator = light.getShadowGenerator();
  24556. if (shadowGenerator) {
  24557. shadowGenerator.bindShadowLight(lightIndex, effect);
  24558. }
  24559. }
  24560. };
  24561. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24562. light.transferToEffect(effect, lightIndex + "");
  24563. };
  24564. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  24565. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24566. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  24567. var lightIndex = 0;
  24568. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24569. var light = _a[_i];
  24570. var scaledIntensity = light.getScaledIntensity();
  24571. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  24572. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24573. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  24574. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  24575. if (defines["SPECULARTERM"]) {
  24576. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  24577. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  24578. }
  24579. // Shadows
  24580. if (scene.shadowsEnabled) {
  24581. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  24582. }
  24583. light._uniformBuffer.update();
  24584. lightIndex++;
  24585. if (lightIndex === maxSimultaneousLights)
  24586. break;
  24587. }
  24588. };
  24589. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24590. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24591. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24592. effect.setColor3("vFogColor", scene.fogColor);
  24593. }
  24594. };
  24595. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24596. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24597. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  24598. if (matrices) {
  24599. effect.setMatrices("mBones", matrices);
  24600. }
  24601. }
  24602. };
  24603. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  24604. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  24605. return;
  24606. }
  24607. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  24608. };
  24609. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24610. if (defines["LOGARITHMICDEPTH"]) {
  24611. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24612. }
  24613. };
  24614. MaterialHelper.BindClipPlane = function (effect, scene) {
  24615. if (scene.clipPlane) {
  24616. var clipPlane = scene.clipPlane;
  24617. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24618. }
  24619. };
  24620. return MaterialHelper;
  24621. }());
  24622. BABYLON.MaterialHelper = MaterialHelper;
  24623. })(BABYLON || (BABYLON = {}));
  24624. //# sourceMappingURL=babylon.materialHelper.js.map
  24625. var BABYLON;
  24626. (function (BABYLON) {
  24627. var MaterialDefines = (function () {
  24628. function MaterialDefines() {
  24629. this._isDirty = true;
  24630. this._areLightsDirty = true;
  24631. this._areAttributesDirty = true;
  24632. this._areTexturesDirty = true;
  24633. this._areFresnelDirty = true;
  24634. this._areMiscDirty = true;
  24635. this._areImageProcessingDirty = true;
  24636. this._normals = false;
  24637. this._uvs = false;
  24638. this._needNormals = false;
  24639. this._needUVs = false;
  24640. }
  24641. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  24642. get: function () {
  24643. return this._isDirty;
  24644. },
  24645. enumerable: true,
  24646. configurable: true
  24647. });
  24648. MaterialDefines.prototype.markAsProcessed = function () {
  24649. this._isDirty = false;
  24650. this._areAttributesDirty = false;
  24651. this._areTexturesDirty = false;
  24652. this._areFresnelDirty = false;
  24653. this._areLightsDirty = false;
  24654. this._areMiscDirty = false;
  24655. this._areImageProcessingDirty = false;
  24656. };
  24657. MaterialDefines.prototype.markAsUnprocessed = function () {
  24658. this._isDirty = true;
  24659. };
  24660. MaterialDefines.prototype.markAllAsDirty = function () {
  24661. this._areTexturesDirty = true;
  24662. this._areAttributesDirty = true;
  24663. this._areLightsDirty = true;
  24664. this._areFresnelDirty = true;
  24665. this._areMiscDirty = true;
  24666. this._areImageProcessingDirty = true;
  24667. this._isDirty = true;
  24668. };
  24669. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  24670. this._areImageProcessingDirty = true;
  24671. this._isDirty = true;
  24672. };
  24673. MaterialDefines.prototype.markAsLightDirty = function () {
  24674. this._areLightsDirty = true;
  24675. this._isDirty = true;
  24676. };
  24677. MaterialDefines.prototype.markAsAttributesDirty = function () {
  24678. this._areAttributesDirty = true;
  24679. this._isDirty = true;
  24680. };
  24681. MaterialDefines.prototype.markAsTexturesDirty = function () {
  24682. this._areTexturesDirty = true;
  24683. this._isDirty = true;
  24684. };
  24685. MaterialDefines.prototype.markAsFresnelDirty = function () {
  24686. this._areFresnelDirty = true;
  24687. this._isDirty = true;
  24688. };
  24689. MaterialDefines.prototype.markAsMiscDirty = function () {
  24690. this._areMiscDirty = true;
  24691. this._isDirty = true;
  24692. };
  24693. MaterialDefines.prototype.rebuild = function () {
  24694. if (this._keys) {
  24695. delete this._keys;
  24696. }
  24697. this._keys = [];
  24698. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  24699. var key = _a[_i];
  24700. if (key[0] === "_") {
  24701. continue;
  24702. }
  24703. this._keys.push(key);
  24704. }
  24705. };
  24706. MaterialDefines.prototype.isEqual = function (other) {
  24707. if (this._keys.length !== other._keys.length) {
  24708. return false;
  24709. }
  24710. for (var index = 0; index < this._keys.length; index++) {
  24711. var prop = this._keys[index];
  24712. if (this[prop] !== other[prop]) {
  24713. return false;
  24714. }
  24715. }
  24716. return true;
  24717. };
  24718. MaterialDefines.prototype.cloneTo = function (other) {
  24719. if (this._keys.length !== other._keys.length) {
  24720. other._keys = this._keys.slice(0);
  24721. }
  24722. for (var index = 0; index < this._keys.length; index++) {
  24723. var prop = this._keys[index];
  24724. other[prop] = this[prop];
  24725. }
  24726. };
  24727. MaterialDefines.prototype.reset = function () {
  24728. for (var index = 0; index < this._keys.length; index++) {
  24729. var prop = this._keys[index];
  24730. if (typeof (this[prop]) === "number") {
  24731. this[prop] = 0;
  24732. }
  24733. else {
  24734. this[prop] = false;
  24735. }
  24736. }
  24737. };
  24738. MaterialDefines.prototype.toString = function () {
  24739. var result = "";
  24740. for (var index = 0; index < this._keys.length; index++) {
  24741. var prop = this._keys[index];
  24742. var value = this[prop];
  24743. if (typeof (value) === "number") {
  24744. result += "#define " + prop + " " + this[prop] + "\n";
  24745. }
  24746. else if (value) {
  24747. result += "#define " + prop + "\n";
  24748. }
  24749. }
  24750. return result;
  24751. };
  24752. return MaterialDefines;
  24753. }());
  24754. BABYLON.MaterialDefines = MaterialDefines;
  24755. var Material = (function () {
  24756. function Material(name, scene, doNotAdd) {
  24757. this.checkReadyOnEveryCall = false;
  24758. this.checkReadyOnlyOnce = false;
  24759. this.state = "";
  24760. this.alpha = 1.0;
  24761. this._backFaceCulling = true;
  24762. this.doNotSerialize = false;
  24763. this.storeEffectOnSubMeshes = false;
  24764. /**
  24765. * An event triggered when the material is disposed.
  24766. * @type {BABYLON.Observable}
  24767. */
  24768. this.onDisposeObservable = new BABYLON.Observable();
  24769. /**
  24770. * An event triggered when the material is bound.
  24771. * @type {BABYLON.Observable}
  24772. */
  24773. this.onBindObservable = new BABYLON.Observable();
  24774. /**
  24775. * An event triggered when the material is unbound.
  24776. * @type {BABYLON.Observable}
  24777. */
  24778. this.onUnBindObservable = new BABYLON.Observable();
  24779. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  24780. this.disableDepthWrite = false;
  24781. this._fogEnabled = true;
  24782. this.pointSize = 1.0;
  24783. this.zOffset = 0;
  24784. this._wasPreviouslyReady = false;
  24785. this._fillMode = Material.TriangleFillMode;
  24786. this.name = name;
  24787. this.id = name || BABYLON.Tools.RandomId();
  24788. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24789. if (this._scene.useRightHandedSystem) {
  24790. this.sideOrientation = Material.ClockWiseSideOrientation;
  24791. }
  24792. else {
  24793. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  24794. }
  24795. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  24796. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  24797. if (!doNotAdd) {
  24798. this._scene.materials.push(this);
  24799. }
  24800. }
  24801. Object.defineProperty(Material, "TriangleFillMode", {
  24802. get: function () {
  24803. return Material._TriangleFillMode;
  24804. },
  24805. enumerable: true,
  24806. configurable: true
  24807. });
  24808. Object.defineProperty(Material, "WireFrameFillMode", {
  24809. get: function () {
  24810. return Material._WireFrameFillMode;
  24811. },
  24812. enumerable: true,
  24813. configurable: true
  24814. });
  24815. Object.defineProperty(Material, "PointFillMode", {
  24816. get: function () {
  24817. return Material._PointFillMode;
  24818. },
  24819. enumerable: true,
  24820. configurable: true
  24821. });
  24822. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  24823. get: function () {
  24824. return Material._ClockWiseSideOrientation;
  24825. },
  24826. enumerable: true,
  24827. configurable: true
  24828. });
  24829. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  24830. get: function () {
  24831. return Material._CounterClockWiseSideOrientation;
  24832. },
  24833. enumerable: true,
  24834. configurable: true
  24835. });
  24836. Object.defineProperty(Material, "TextureDirtyFlag", {
  24837. get: function () {
  24838. return Material._TextureDirtyFlag;
  24839. },
  24840. enumerable: true,
  24841. configurable: true
  24842. });
  24843. Object.defineProperty(Material, "LightDirtyFlag", {
  24844. get: function () {
  24845. return Material._LightDirtyFlag;
  24846. },
  24847. enumerable: true,
  24848. configurable: true
  24849. });
  24850. Object.defineProperty(Material, "FresnelDirtyFlag", {
  24851. get: function () {
  24852. return Material._FresnelDirtyFlag;
  24853. },
  24854. enumerable: true,
  24855. configurable: true
  24856. });
  24857. Object.defineProperty(Material, "AttributesDirtyFlag", {
  24858. get: function () {
  24859. return Material._AttributesDirtyFlag;
  24860. },
  24861. enumerable: true,
  24862. configurable: true
  24863. });
  24864. Object.defineProperty(Material, "MiscDirtyFlag", {
  24865. get: function () {
  24866. return Material._MiscDirtyFlag;
  24867. },
  24868. enumerable: true,
  24869. configurable: true
  24870. });
  24871. Object.defineProperty(Material.prototype, "backFaceCulling", {
  24872. get: function () {
  24873. return this._backFaceCulling;
  24874. },
  24875. set: function (value) {
  24876. if (this._backFaceCulling === value) {
  24877. return;
  24878. }
  24879. this._backFaceCulling = value;
  24880. this.markAsDirty(Material.TextureDirtyFlag);
  24881. },
  24882. enumerable: true,
  24883. configurable: true
  24884. });
  24885. Object.defineProperty(Material.prototype, "onDispose", {
  24886. set: function (callback) {
  24887. if (this._onDisposeObserver) {
  24888. this.onDisposeObservable.remove(this._onDisposeObserver);
  24889. }
  24890. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24891. },
  24892. enumerable: true,
  24893. configurable: true
  24894. });
  24895. Object.defineProperty(Material.prototype, "onBind", {
  24896. set: function (callback) {
  24897. if (this._onBindObserver) {
  24898. this.onBindObservable.remove(this._onBindObserver);
  24899. }
  24900. this._onBindObserver = this.onBindObservable.add(callback);
  24901. },
  24902. enumerable: true,
  24903. configurable: true
  24904. });
  24905. Object.defineProperty(Material.prototype, "fogEnabled", {
  24906. get: function () {
  24907. return this._fogEnabled;
  24908. },
  24909. set: function (value) {
  24910. if (this._fogEnabled === value) {
  24911. return;
  24912. }
  24913. this._fogEnabled = value;
  24914. this.markAsDirty(Material.MiscDirtyFlag);
  24915. },
  24916. enumerable: true,
  24917. configurable: true
  24918. });
  24919. Object.defineProperty(Material.prototype, "wireframe", {
  24920. get: function () {
  24921. return this._fillMode === Material.WireFrameFillMode;
  24922. },
  24923. set: function (value) {
  24924. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24925. },
  24926. enumerable: true,
  24927. configurable: true
  24928. });
  24929. Object.defineProperty(Material.prototype, "pointsCloud", {
  24930. get: function () {
  24931. return this._fillMode === Material.PointFillMode;
  24932. },
  24933. set: function (value) {
  24934. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24935. },
  24936. enumerable: true,
  24937. configurable: true
  24938. });
  24939. Object.defineProperty(Material.prototype, "fillMode", {
  24940. get: function () {
  24941. return this._fillMode;
  24942. },
  24943. set: function (value) {
  24944. if (this._fillMode === value) {
  24945. return;
  24946. }
  24947. this._fillMode = value;
  24948. this.markAsDirty(Material.MiscDirtyFlag);
  24949. },
  24950. enumerable: true,
  24951. configurable: true
  24952. });
  24953. /**
  24954. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24955. * subclasses should override adding information pertainent to themselves
  24956. */
  24957. Material.prototype.toString = function (fullDetails) {
  24958. var ret = "Name: " + this.name;
  24959. if (fullDetails) {
  24960. }
  24961. return ret;
  24962. };
  24963. /**
  24964. * Child classes can use it to update shaders
  24965. */
  24966. Material.prototype.getClassName = function () {
  24967. return "Material";
  24968. };
  24969. Object.defineProperty(Material.prototype, "isFrozen", {
  24970. get: function () {
  24971. return this.checkReadyOnlyOnce;
  24972. },
  24973. enumerable: true,
  24974. configurable: true
  24975. });
  24976. Material.prototype.freeze = function () {
  24977. this.checkReadyOnlyOnce = true;
  24978. };
  24979. Material.prototype.unfreeze = function () {
  24980. this.checkReadyOnlyOnce = false;
  24981. };
  24982. Material.prototype.isReady = function (mesh, useInstances) {
  24983. return true;
  24984. };
  24985. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  24986. return false;
  24987. };
  24988. Material.prototype.getEffect = function () {
  24989. return this._effect;
  24990. };
  24991. Material.prototype.getScene = function () {
  24992. return this._scene;
  24993. };
  24994. Material.prototype.needAlphaBlending = function () {
  24995. return (this.alpha < 1.0);
  24996. };
  24997. Material.prototype.needAlphaTesting = function () {
  24998. return false;
  24999. };
  25000. Material.prototype.getAlphaTestTexture = function () {
  25001. return null;
  25002. };
  25003. Material.prototype.markDirty = function () {
  25004. this._wasPreviouslyReady = false;
  25005. };
  25006. Material.prototype._preBind = function (effect) {
  25007. var engine = this._scene.getEngine();
  25008. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25009. engine.enableEffect(effect ? effect : this._effect);
  25010. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25011. };
  25012. Material.prototype.bind = function (world, mesh) {
  25013. };
  25014. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25015. };
  25016. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25017. };
  25018. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25019. sceneUbo.bindToEffect(effect, "Scene");
  25020. };
  25021. Material.prototype.bindView = function (effect) {
  25022. if (!this._useUBO) {
  25023. effect.setMatrix("view", this.getScene().getViewMatrix());
  25024. }
  25025. else {
  25026. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25027. }
  25028. };
  25029. Material.prototype.bindViewProjection = function (effect) {
  25030. if (!this._useUBO) {
  25031. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25032. }
  25033. else {
  25034. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25035. }
  25036. };
  25037. Material.prototype._afterBind = function (mesh) {
  25038. this._scene._cachedMaterial = this;
  25039. if (mesh) {
  25040. this._scene._cachedVisibility = mesh.visibility;
  25041. }
  25042. else {
  25043. this._scene._cachedVisibility = 1;
  25044. }
  25045. this.onBindObservable.notifyObservers(mesh);
  25046. if (this.disableDepthWrite) {
  25047. var engine = this._scene.getEngine();
  25048. this._cachedDepthWriteState = engine.getDepthWrite();
  25049. engine.setDepthWrite(false);
  25050. }
  25051. };
  25052. Material.prototype.unbind = function () {
  25053. this.onUnBindObservable.notifyObservers(this);
  25054. if (this.disableDepthWrite) {
  25055. var engine = this._scene.getEngine();
  25056. engine.setDepthWrite(this._cachedDepthWriteState);
  25057. }
  25058. };
  25059. Material.prototype.getActiveTextures = function () {
  25060. return [];
  25061. };
  25062. Material.prototype.hasTexture = function (texture) {
  25063. return false;
  25064. };
  25065. Material.prototype.clone = function (name) {
  25066. return null;
  25067. };
  25068. Material.prototype.getBindedMeshes = function () {
  25069. var result = new Array();
  25070. for (var index = 0; index < this._scene.meshes.length; index++) {
  25071. var mesh = this._scene.meshes[index];
  25072. if (mesh.material === this) {
  25073. result.push(mesh);
  25074. }
  25075. }
  25076. return result;
  25077. };
  25078. /**
  25079. * Force shader compilation including textures ready check
  25080. */
  25081. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25082. var _this = this;
  25083. var subMesh = new BABYLON.BaseSubMesh();
  25084. var scene = this.getScene();
  25085. var engine = scene.getEngine();
  25086. var checkReady = function () {
  25087. if (!_this._scene || !_this._scene.getEngine()) {
  25088. return;
  25089. }
  25090. if (subMesh._materialDefines) {
  25091. subMesh._materialDefines._renderId = -1;
  25092. }
  25093. var alphaTestState = engine.getAlphaTesting();
  25094. var clipPlaneState = scene.clipPlane;
  25095. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25096. if (options && options.clipPlane) {
  25097. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25098. }
  25099. if (_this.storeEffectOnSubMeshes) {
  25100. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25101. if (onCompiled) {
  25102. onCompiled(_this);
  25103. }
  25104. }
  25105. else {
  25106. setTimeout(checkReady, 16);
  25107. }
  25108. }
  25109. else {
  25110. if (_this.isReady(mesh)) {
  25111. if (onCompiled) {
  25112. onCompiled(_this);
  25113. }
  25114. }
  25115. else {
  25116. setTimeout(checkReady, 16);
  25117. }
  25118. }
  25119. engine.setAlphaTesting(alphaTestState);
  25120. if (options && options.clipPlane) {
  25121. scene.clipPlane = clipPlaneState;
  25122. }
  25123. };
  25124. checkReady();
  25125. };
  25126. Material.prototype.markAsDirty = function (flag) {
  25127. if (flag & Material.TextureDirtyFlag) {
  25128. this._markAllSubMeshesAsTexturesDirty();
  25129. }
  25130. if (flag & Material.LightDirtyFlag) {
  25131. this._markAllSubMeshesAsLightsDirty();
  25132. }
  25133. if (flag & Material.FresnelDirtyFlag) {
  25134. this._markAllSubMeshesAsFresnelDirty();
  25135. }
  25136. if (flag & Material.AttributesDirtyFlag) {
  25137. this._markAllSubMeshesAsAttributesDirty();
  25138. }
  25139. if (flag & Material.MiscDirtyFlag) {
  25140. this._markAllSubMeshesAsMiscDirty();
  25141. }
  25142. this.getScene().resetCachedMaterial();
  25143. };
  25144. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25145. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25146. var mesh = _a[_i];
  25147. if (!mesh.subMeshes) {
  25148. continue;
  25149. }
  25150. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25151. var subMesh = _c[_b];
  25152. if (subMesh.getMaterial() !== this) {
  25153. continue;
  25154. }
  25155. if (!subMesh._materialDefines) {
  25156. continue;
  25157. }
  25158. func(subMesh._materialDefines);
  25159. }
  25160. }
  25161. };
  25162. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25163. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25164. };
  25165. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25166. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25167. };
  25168. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25169. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25170. };
  25171. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25172. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25173. };
  25174. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25175. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25176. };
  25177. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  25178. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  25179. };
  25180. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25181. // Animations
  25182. this.getScene().stopAnimation(this);
  25183. // Remove from scene
  25184. var index = this._scene.materials.indexOf(this);
  25185. if (index >= 0) {
  25186. this._scene.materials.splice(index, 1);
  25187. }
  25188. // Remove from meshes
  25189. for (index = 0; index < this._scene.meshes.length; index++) {
  25190. var mesh = this._scene.meshes[index];
  25191. if (mesh.material === this) {
  25192. mesh.material = null;
  25193. if (mesh.geometry) {
  25194. var geometry = mesh.geometry;
  25195. if (this.storeEffectOnSubMeshes) {
  25196. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  25197. var subMesh = _a[_i];
  25198. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  25199. }
  25200. }
  25201. else {
  25202. geometry._releaseVertexArrayObject(this._effect);
  25203. }
  25204. }
  25205. }
  25206. }
  25207. this._uniformBuffer.dispose();
  25208. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25209. if (forceDisposeEffect && this._effect) {
  25210. if (this.storeEffectOnSubMeshes) {
  25211. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25212. var subMesh = _c[_b];
  25213. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  25214. }
  25215. }
  25216. else {
  25217. this._scene.getEngine()._releaseEffect(this._effect);
  25218. }
  25219. this._effect = null;
  25220. }
  25221. // Callback
  25222. this.onDisposeObservable.notifyObservers(this);
  25223. this.onDisposeObservable.clear();
  25224. this.onBindObservable.clear();
  25225. this.onUnBindObservable.clear();
  25226. };
  25227. Material.prototype.serialize = function () {
  25228. return BABYLON.SerializationHelper.Serialize(this);
  25229. };
  25230. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25231. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25232. multiMaterial.id = parsedMultiMaterial.id;
  25233. if (BABYLON.Tags) {
  25234. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25235. }
  25236. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25237. var subMatId = parsedMultiMaterial.materials[matIndex];
  25238. if (subMatId) {
  25239. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25240. }
  25241. else {
  25242. multiMaterial.subMaterials.push(null);
  25243. }
  25244. }
  25245. return multiMaterial;
  25246. };
  25247. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25248. if (!parsedMaterial.customType) {
  25249. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25250. }
  25251. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  25252. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  25253. if (!BABYLON.LegacyPBRMaterial) {
  25254. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25255. return;
  25256. }
  25257. }
  25258. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25259. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25260. ;
  25261. };
  25262. Material._TriangleFillMode = 0;
  25263. Material._WireFrameFillMode = 1;
  25264. Material._PointFillMode = 2;
  25265. Material._ClockWiseSideOrientation = 0;
  25266. Material._CounterClockWiseSideOrientation = 1;
  25267. Material._TextureDirtyFlag = 1;
  25268. Material._LightDirtyFlag = 2;
  25269. Material._FresnelDirtyFlag = 4;
  25270. Material._AttributesDirtyFlag = 8;
  25271. Material._MiscDirtyFlag = 16;
  25272. __decorate([
  25273. BABYLON.serialize()
  25274. ], Material.prototype, "id", void 0);
  25275. __decorate([
  25276. BABYLON.serialize()
  25277. ], Material.prototype, "name", void 0);
  25278. __decorate([
  25279. BABYLON.serialize()
  25280. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25281. __decorate([
  25282. BABYLON.serialize()
  25283. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25284. __decorate([
  25285. BABYLON.serialize()
  25286. ], Material.prototype, "state", void 0);
  25287. __decorate([
  25288. BABYLON.serialize()
  25289. ], Material.prototype, "alpha", void 0);
  25290. __decorate([
  25291. BABYLON.serialize("backFaceCulling")
  25292. ], Material.prototype, "_backFaceCulling", void 0);
  25293. __decorate([
  25294. BABYLON.serialize()
  25295. ], Material.prototype, "sideOrientation", void 0);
  25296. __decorate([
  25297. BABYLON.serialize()
  25298. ], Material.prototype, "alphaMode", void 0);
  25299. __decorate([
  25300. BABYLON.serialize()
  25301. ], Material.prototype, "disableDepthWrite", void 0);
  25302. __decorate([
  25303. BABYLON.serialize("fogEnabled")
  25304. ], Material.prototype, "_fogEnabled", void 0);
  25305. __decorate([
  25306. BABYLON.serialize()
  25307. ], Material.prototype, "pointSize", void 0);
  25308. __decorate([
  25309. BABYLON.serialize()
  25310. ], Material.prototype, "zOffset", void 0);
  25311. __decorate([
  25312. BABYLON.serialize()
  25313. ], Material.prototype, "wireframe", null);
  25314. __decorate([
  25315. BABYLON.serialize()
  25316. ], Material.prototype, "pointsCloud", null);
  25317. __decorate([
  25318. BABYLON.serialize()
  25319. ], Material.prototype, "fillMode", null);
  25320. return Material;
  25321. }());
  25322. BABYLON.Material = Material;
  25323. })(BABYLON || (BABYLON = {}));
  25324. //# sourceMappingURL=babylon.material.js.map
  25325. var BABYLON;
  25326. (function (BABYLON) {
  25327. var UniformBuffer = (function () {
  25328. /**
  25329. * Uniform buffer objects.
  25330. *
  25331. * Handles blocks of uniform on the GPU.
  25332. *
  25333. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  25334. *
  25335. * For more information, please refer to :
  25336. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  25337. */
  25338. function UniformBuffer(engine, data, dynamic) {
  25339. this._engine = engine;
  25340. this._noUBO = engine.webGLVersion === 1;
  25341. this._dynamic = dynamic;
  25342. this._data = data || [];
  25343. this._uniformLocations = {};
  25344. this._uniformSizes = {};
  25345. this._uniformLocationPointer = 0;
  25346. this._needSync = false;
  25347. if (this._noUBO) {
  25348. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  25349. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  25350. this.updateFloat = this._updateFloatForEffect;
  25351. this.updateFloat2 = this._updateFloat2ForEffect;
  25352. this.updateFloat3 = this._updateFloat3ForEffect;
  25353. this.updateFloat4 = this._updateFloat4ForEffect;
  25354. this.updateMatrix = this._updateMatrixForEffect;
  25355. this.updateVector3 = this._updateVector3ForEffect;
  25356. this.updateVector4 = this._updateVector4ForEffect;
  25357. this.updateColor3 = this._updateColor3ForEffect;
  25358. this.updateColor4 = this._updateColor4ForEffect;
  25359. }
  25360. else {
  25361. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  25362. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  25363. this.updateFloat = this._updateFloatForUniform;
  25364. this.updateFloat2 = this._updateFloat2ForUniform;
  25365. this.updateFloat3 = this._updateFloat3ForUniform;
  25366. this.updateFloat4 = this._updateFloat4ForUniform;
  25367. this.updateMatrix = this._updateMatrixForUniform;
  25368. this.updateVector3 = this._updateVector3ForUniform;
  25369. this.updateVector4 = this._updateVector4ForUniform;
  25370. this.updateColor3 = this._updateColor3ForUniform;
  25371. this.updateColor4 = this._updateColor4ForUniform;
  25372. }
  25373. }
  25374. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  25375. // Properties
  25376. /**
  25377. * Indicates if the buffer is using the WebGL2 UBO implementation,
  25378. * or just falling back on setUniformXXX calls.
  25379. */
  25380. get: function () {
  25381. return !this._noUBO;
  25382. },
  25383. enumerable: true,
  25384. configurable: true
  25385. });
  25386. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  25387. /**
  25388. * Indicates if the WebGL underlying uniform buffer is in sync
  25389. * with the javascript cache data.
  25390. */
  25391. get: function () {
  25392. return !this._needSync;
  25393. },
  25394. enumerable: true,
  25395. configurable: true
  25396. });
  25397. /**
  25398. * Indicates if the WebGL underlying uniform buffer is dynamic.
  25399. * Also, a dynamic UniformBuffer will disable cache verification and always
  25400. * update the underlying WebGL uniform buffer to the GPU.
  25401. */
  25402. UniformBuffer.prototype.isDynamic = function () {
  25403. return this._dynamic;
  25404. };
  25405. /**
  25406. * The data cache on JS side.
  25407. */
  25408. UniformBuffer.prototype.getData = function () {
  25409. return this._bufferData;
  25410. };
  25411. /**
  25412. * The underlying WebGL Uniform buffer.
  25413. */
  25414. UniformBuffer.prototype.getBuffer = function () {
  25415. return this._buffer;
  25416. };
  25417. /**
  25418. * std140 layout specifies how to align data within an UBO structure.
  25419. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  25420. * for specs.
  25421. */
  25422. UniformBuffer.prototype._fillAlignment = function (size) {
  25423. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  25424. // and 4x4 matrices
  25425. // TODO : change if other types are used
  25426. var alignment;
  25427. if (size <= 2) {
  25428. alignment = size;
  25429. }
  25430. else {
  25431. alignment = 4;
  25432. }
  25433. if ((this._uniformLocationPointer % alignment) !== 0) {
  25434. var oldPointer = this._uniformLocationPointer;
  25435. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  25436. var diff = this._uniformLocationPointer - oldPointer;
  25437. for (var i = 0; i < diff; i++) {
  25438. this._data.push(0);
  25439. }
  25440. }
  25441. };
  25442. /**
  25443. * Adds an uniform in the buffer.
  25444. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  25445. * for the layout to be correct !
  25446. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25447. * @param {number|number[]} size Data size, or data directly.
  25448. */
  25449. UniformBuffer.prototype.addUniform = function (name, size) {
  25450. if (this._noUBO) {
  25451. return;
  25452. }
  25453. if (this._uniformLocations[name] !== undefined) {
  25454. // Already existing uniform
  25455. return;
  25456. }
  25457. // This function must be called in the order of the shader layout !
  25458. // size can be the size of the uniform, or data directly
  25459. var data;
  25460. if (size instanceof Array) {
  25461. data = size;
  25462. size = data.length;
  25463. }
  25464. else {
  25465. size = size;
  25466. data = [];
  25467. // Fill with zeros
  25468. for (var i = 0; i < size; i++) {
  25469. data.push(0);
  25470. }
  25471. }
  25472. this._fillAlignment(size);
  25473. this._uniformSizes[name] = size;
  25474. this._uniformLocations[name] = this._uniformLocationPointer;
  25475. this._uniformLocationPointer += size;
  25476. for (var i = 0; i < size; i++) {
  25477. this._data.push(data[i]);
  25478. }
  25479. this._needSync = true;
  25480. };
  25481. /**
  25482. * Wrapper for addUniform.
  25483. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25484. * @param {Matrix} mat A 4x4 matrix.
  25485. */
  25486. UniformBuffer.prototype.addMatrix = function (name, mat) {
  25487. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  25488. };
  25489. /**
  25490. * Wrapper for addUniform.
  25491. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25492. * @param {number} x
  25493. * @param {number} y
  25494. */
  25495. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  25496. var temp = [x, y];
  25497. this.addUniform(name, temp);
  25498. };
  25499. /**
  25500. * Wrapper for addUniform.
  25501. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25502. * @param {number} x
  25503. * @param {number} y
  25504. * @param {number} z
  25505. */
  25506. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  25507. var temp = [x, y, z];
  25508. this.addUniform(name, temp);
  25509. };
  25510. /**
  25511. * Wrapper for addUniform.
  25512. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25513. * @param {Color3} color
  25514. */
  25515. UniformBuffer.prototype.addColor3 = function (name, color) {
  25516. var temp = [];
  25517. color.toArray(temp);
  25518. this.addUniform(name, temp);
  25519. };
  25520. /**
  25521. * Wrapper for addUniform.
  25522. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25523. * @param {Color3} color
  25524. * @param {number} alpha
  25525. */
  25526. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  25527. var temp = [];
  25528. color.toArray(temp);
  25529. temp.push(alpha);
  25530. this.addUniform(name, temp);
  25531. };
  25532. /**
  25533. * Wrapper for addUniform.
  25534. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25535. * @param {Vector3} vector
  25536. */
  25537. UniformBuffer.prototype.addVector3 = function (name, vector) {
  25538. var temp = [];
  25539. vector.toArray(temp);
  25540. this.addUniform(name, temp);
  25541. };
  25542. /**
  25543. * Wrapper for addUniform.
  25544. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25545. */
  25546. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  25547. this.addUniform(name, 12);
  25548. };
  25549. /**
  25550. * Wrapper for addUniform.
  25551. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25552. */
  25553. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  25554. this.addUniform(name, 8);
  25555. };
  25556. /**
  25557. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  25558. */
  25559. UniformBuffer.prototype.create = function () {
  25560. if (this._noUBO) {
  25561. return;
  25562. }
  25563. if (this._buffer) {
  25564. return; // nothing to do
  25565. }
  25566. // See spec, alignment must be filled as a vec4
  25567. this._fillAlignment(4);
  25568. this._bufferData = new Float32Array(this._data);
  25569. if (this._dynamic) {
  25570. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  25571. }
  25572. else {
  25573. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  25574. }
  25575. this._needSync = true;
  25576. };
  25577. /**
  25578. * Updates the WebGL Uniform Buffer on the GPU.
  25579. * If the `dynamic` flag is set to true, no cache comparison is done.
  25580. * Otherwise, the buffer will be updated only if the cache differs.
  25581. */
  25582. UniformBuffer.prototype.update = function () {
  25583. if (!this._buffer) {
  25584. this.create();
  25585. return;
  25586. }
  25587. if (!this._dynamic && !this._needSync) {
  25588. return;
  25589. }
  25590. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  25591. this._needSync = false;
  25592. };
  25593. /**
  25594. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  25595. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  25596. * @param {number[]|Float32Array} data Flattened data
  25597. * @param {number} size Size of the data.
  25598. */
  25599. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  25600. var location = this._uniformLocations[uniformName];
  25601. if (location === undefined) {
  25602. if (this._buffer) {
  25603. // Cannot add an uniform if the buffer is already created
  25604. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  25605. return;
  25606. }
  25607. this.addUniform(uniformName, size);
  25608. location = this._uniformLocations[uniformName];
  25609. }
  25610. if (!this._buffer) {
  25611. this.create();
  25612. }
  25613. if (!this._dynamic) {
  25614. // Cache for static uniform buffers
  25615. var changed = false;
  25616. for (var i = 0; i < size; i++) {
  25617. if (this._bufferData[location + i] !== data[i]) {
  25618. changed = true;
  25619. this._bufferData[location + i] = data[i];
  25620. }
  25621. }
  25622. this._needSync = this._needSync || changed;
  25623. }
  25624. else {
  25625. // No cache for dynamic
  25626. for (var i = 0; i < size; i++) {
  25627. this._bufferData[location + i] = data[i];
  25628. }
  25629. }
  25630. };
  25631. // Update methods
  25632. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  25633. // To match std140, matrix must be realigned
  25634. for (var i = 0; i < 3; i++) {
  25635. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  25636. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  25637. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  25638. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  25639. }
  25640. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  25641. };
  25642. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  25643. this._currentEffect.setMatrix3x3(name, matrix);
  25644. };
  25645. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  25646. this._currentEffect.setMatrix2x2(name, matrix);
  25647. };
  25648. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  25649. // To match std140, matrix must be realigned
  25650. for (var i = 0; i < 2; i++) {
  25651. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  25652. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  25653. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  25654. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  25655. }
  25656. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  25657. };
  25658. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  25659. this._currentEffect.setFloat(name, x);
  25660. };
  25661. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  25662. UniformBuffer._tempBuffer[0] = x;
  25663. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  25664. };
  25665. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  25666. if (suffix === void 0) { suffix = ""; }
  25667. this._currentEffect.setFloat2(name + suffix, x, y);
  25668. };
  25669. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  25670. if (suffix === void 0) { suffix = ""; }
  25671. UniformBuffer._tempBuffer[0] = x;
  25672. UniformBuffer._tempBuffer[1] = y;
  25673. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  25674. };
  25675. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  25676. if (suffix === void 0) { suffix = ""; }
  25677. this._currentEffect.setFloat3(name + suffix, x, y, z);
  25678. };
  25679. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  25680. if (suffix === void 0) { suffix = ""; }
  25681. UniformBuffer._tempBuffer[0] = x;
  25682. UniformBuffer._tempBuffer[1] = y;
  25683. UniformBuffer._tempBuffer[2] = z;
  25684. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25685. };
  25686. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  25687. if (suffix === void 0) { suffix = ""; }
  25688. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  25689. };
  25690. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  25691. if (suffix === void 0) { suffix = ""; }
  25692. UniformBuffer._tempBuffer[0] = x;
  25693. UniformBuffer._tempBuffer[1] = y;
  25694. UniformBuffer._tempBuffer[2] = z;
  25695. UniformBuffer._tempBuffer[3] = w;
  25696. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25697. };
  25698. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  25699. this._currentEffect.setMatrix(name, mat);
  25700. };
  25701. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  25702. this.updateUniform(name, mat.toArray(), 16);
  25703. };
  25704. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  25705. this._currentEffect.setVector3(name, vector);
  25706. };
  25707. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  25708. vector.toArray(UniformBuffer._tempBuffer);
  25709. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25710. };
  25711. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  25712. this._currentEffect.setVector4(name, vector);
  25713. };
  25714. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  25715. vector.toArray(UniformBuffer._tempBuffer);
  25716. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25717. };
  25718. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  25719. if (suffix === void 0) { suffix = ""; }
  25720. this._currentEffect.setColor3(name + suffix, color);
  25721. };
  25722. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  25723. if (suffix === void 0) { suffix = ""; }
  25724. color.toArray(UniformBuffer._tempBuffer);
  25725. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25726. };
  25727. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  25728. if (suffix === void 0) { suffix = ""; }
  25729. this._currentEffect.setColor4(name + suffix, color, alpha);
  25730. };
  25731. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  25732. if (suffix === void 0) { suffix = ""; }
  25733. color.toArray(UniformBuffer._tempBuffer);
  25734. UniformBuffer._tempBuffer[3] = alpha;
  25735. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25736. };
  25737. /**
  25738. * Sets a sampler uniform on the effect.
  25739. * @param {string} name Name of the sampler.
  25740. * @param {Texture} texture
  25741. */
  25742. UniformBuffer.prototype.setTexture = function (name, texture) {
  25743. this._currentEffect.setTexture(name, texture);
  25744. };
  25745. /**
  25746. * Directly updates the value of the uniform in the cache AND on the GPU.
  25747. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  25748. * @param {number[]|Float32Array} data Flattened data
  25749. */
  25750. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  25751. this.updateUniform(uniformName, data, data.length);
  25752. this.update();
  25753. };
  25754. /**
  25755. * Binds this uniform buffer to an effect.
  25756. * @param {Effect} effect
  25757. * @param {string} name Name of the uniform block in the shader.
  25758. */
  25759. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  25760. this._currentEffect = effect;
  25761. if (this._noUBO) {
  25762. return;
  25763. }
  25764. effect.bindUniformBuffer(this._buffer, name);
  25765. };
  25766. /**
  25767. * Disposes the uniform buffer.
  25768. */
  25769. UniformBuffer.prototype.dispose = function () {
  25770. if (!this._buffer) {
  25771. return;
  25772. }
  25773. if (this._engine._releaseBuffer(this._buffer)) {
  25774. this._buffer = null;
  25775. }
  25776. };
  25777. // Pool for avoiding memory leaks
  25778. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  25779. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  25780. return UniformBuffer;
  25781. }());
  25782. BABYLON.UniformBuffer = UniformBuffer;
  25783. })(BABYLON || (BABYLON = {}));
  25784. //# sourceMappingURL=babylon.uniformBuffer.js.map
  25785. var BABYLON;
  25786. (function (BABYLON) {
  25787. var PushMaterial = (function (_super) {
  25788. __extends(PushMaterial, _super);
  25789. function PushMaterial(name, scene) {
  25790. var _this = _super.call(this, name, scene) || this;
  25791. _this.storeEffectOnSubMeshes = true;
  25792. return _this;
  25793. }
  25794. PushMaterial.prototype.getEffect = function () {
  25795. return this._activeEffect;
  25796. };
  25797. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  25798. if (!mesh) {
  25799. return false;
  25800. }
  25801. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25802. return true;
  25803. }
  25804. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  25805. };
  25806. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25807. this._activeEffect.setMatrix("world", world);
  25808. };
  25809. PushMaterial.prototype.bind = function (world, mesh) {
  25810. if (!mesh) {
  25811. return;
  25812. }
  25813. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  25814. };
  25815. PushMaterial.prototype._afterBind = function (mesh, effect) {
  25816. _super.prototype._afterBind.call(this, mesh);
  25817. this.getScene()._cachedEffect = effect;
  25818. };
  25819. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  25820. if (visibility === void 0) { visibility = 0; }
  25821. return scene.isCachedMaterialInvalid(this, effect, visibility);
  25822. };
  25823. return PushMaterial;
  25824. }(BABYLON.Material));
  25825. BABYLON.PushMaterial = PushMaterial;
  25826. })(BABYLON || (BABYLON = {}));
  25827. //# sourceMappingURL=babylon.pushMaterial.js.map
  25828. var BABYLON;
  25829. (function (BABYLON) {
  25830. var VertexData = (function () {
  25831. function VertexData() {
  25832. }
  25833. VertexData.prototype.set = function (data, kind) {
  25834. switch (kind) {
  25835. case BABYLON.VertexBuffer.PositionKind:
  25836. this.positions = data;
  25837. break;
  25838. case BABYLON.VertexBuffer.NormalKind:
  25839. this.normals = data;
  25840. break;
  25841. case BABYLON.VertexBuffer.TangentKind:
  25842. this.tangents = data;
  25843. break;
  25844. case BABYLON.VertexBuffer.UVKind:
  25845. this.uvs = data;
  25846. break;
  25847. case BABYLON.VertexBuffer.UV2Kind:
  25848. this.uvs2 = data;
  25849. break;
  25850. case BABYLON.VertexBuffer.UV3Kind:
  25851. this.uvs3 = data;
  25852. break;
  25853. case BABYLON.VertexBuffer.UV4Kind:
  25854. this.uvs4 = data;
  25855. break;
  25856. case BABYLON.VertexBuffer.UV5Kind:
  25857. this.uvs5 = data;
  25858. break;
  25859. case BABYLON.VertexBuffer.UV6Kind:
  25860. this.uvs6 = data;
  25861. break;
  25862. case BABYLON.VertexBuffer.ColorKind:
  25863. this.colors = data;
  25864. break;
  25865. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25866. this.matricesIndices = data;
  25867. break;
  25868. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25869. this.matricesWeights = data;
  25870. break;
  25871. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  25872. this.matricesIndicesExtra = data;
  25873. break;
  25874. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  25875. this.matricesWeightsExtra = data;
  25876. break;
  25877. }
  25878. };
  25879. /**
  25880. * Associates the vertexData to the passed Mesh.
  25881. * Sets it as updatable or not (default `false`).
  25882. * Returns the VertexData.
  25883. */
  25884. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25885. this._applyTo(mesh, updatable);
  25886. return this;
  25887. };
  25888. /**
  25889. * Associates the vertexData to the passed Geometry.
  25890. * Sets it as updatable or not (default `false`).
  25891. * Returns the VertexData.
  25892. */
  25893. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25894. this._applyTo(geometry, updatable);
  25895. return this;
  25896. };
  25897. /**
  25898. * Updates the associated mesh.
  25899. * Returns the VertexData.
  25900. */
  25901. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25902. this._update(mesh);
  25903. return this;
  25904. };
  25905. /**
  25906. * Updates the associated geometry.
  25907. * Returns the VertexData.
  25908. */
  25909. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25910. this._update(geometry);
  25911. return this;
  25912. };
  25913. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25914. if (this.positions) {
  25915. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25916. }
  25917. if (this.normals) {
  25918. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25919. }
  25920. if (this.tangents) {
  25921. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  25922. }
  25923. if (this.uvs) {
  25924. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25925. }
  25926. if (this.uvs2) {
  25927. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25928. }
  25929. if (this.uvs3) {
  25930. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25931. }
  25932. if (this.uvs4) {
  25933. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25934. }
  25935. if (this.uvs5) {
  25936. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25937. }
  25938. if (this.uvs6) {
  25939. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25940. }
  25941. if (this.colors) {
  25942. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25943. }
  25944. if (this.matricesIndices) {
  25945. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25946. }
  25947. if (this.matricesWeights) {
  25948. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25949. }
  25950. if (this.matricesIndicesExtra) {
  25951. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  25952. }
  25953. if (this.matricesWeightsExtra) {
  25954. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  25955. }
  25956. if (this.indices) {
  25957. meshOrGeometry.setIndices(this.indices);
  25958. }
  25959. return this;
  25960. };
  25961. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25962. if (this.positions) {
  25963. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25964. }
  25965. if (this.normals) {
  25966. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25967. }
  25968. if (this.tangents) {
  25969. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  25970. }
  25971. if (this.uvs) {
  25972. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25973. }
  25974. if (this.uvs2) {
  25975. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25976. }
  25977. if (this.uvs3) {
  25978. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25979. }
  25980. if (this.uvs4) {
  25981. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25982. }
  25983. if (this.uvs5) {
  25984. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25985. }
  25986. if (this.uvs6) {
  25987. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25988. }
  25989. if (this.colors) {
  25990. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25991. }
  25992. if (this.matricesIndices) {
  25993. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25994. }
  25995. if (this.matricesWeights) {
  25996. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25997. }
  25998. if (this.matricesIndicesExtra) {
  25999. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26000. }
  26001. if (this.matricesWeightsExtra) {
  26002. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26003. }
  26004. if (this.indices) {
  26005. meshOrGeometry.setIndices(this.indices);
  26006. }
  26007. return this;
  26008. };
  26009. /**
  26010. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26011. * Returns the VertexData.
  26012. */
  26013. VertexData.prototype.transform = function (matrix) {
  26014. var transformed = BABYLON.Vector3.Zero();
  26015. var index;
  26016. if (this.positions) {
  26017. var position = BABYLON.Vector3.Zero();
  26018. for (index = 0; index < this.positions.length; index += 3) {
  26019. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26020. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26021. this.positions[index] = transformed.x;
  26022. this.positions[index + 1] = transformed.y;
  26023. this.positions[index + 2] = transformed.z;
  26024. }
  26025. }
  26026. if (this.normals) {
  26027. var normal = BABYLON.Vector3.Zero();
  26028. for (index = 0; index < this.normals.length; index += 3) {
  26029. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26030. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26031. this.normals[index] = transformed.x;
  26032. this.normals[index + 1] = transformed.y;
  26033. this.normals[index + 2] = transformed.z;
  26034. }
  26035. }
  26036. if (this.tangents) {
  26037. var tangent = BABYLON.Vector4.Zero();
  26038. var tangentTransformed = BABYLON.Vector4.Zero();
  26039. for (index = 0; index < this.tangents.length; index += 4) {
  26040. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26041. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26042. this.tangents[index] = tangentTransformed.x;
  26043. this.tangents[index + 1] = tangentTransformed.y;
  26044. this.tangents[index + 2] = tangentTransformed.z;
  26045. this.tangents[index + 3] = tangentTransformed.w;
  26046. }
  26047. }
  26048. return this;
  26049. };
  26050. /**
  26051. * Merges the passed VertexData into the current one.
  26052. * Returns the modified VertexData.
  26053. */
  26054. VertexData.prototype.merge = function (other) {
  26055. if (other.indices) {
  26056. if (!this.indices) {
  26057. this.indices = [];
  26058. }
  26059. var offset = this.positions ? this.positions.length / 3 : 0;
  26060. for (var index = 0; index < other.indices.length; index++) {
  26061. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26062. this.indices.push(other.indices[index] + offset);
  26063. }
  26064. }
  26065. this.positions = this._mergeElement(this.positions, other.positions);
  26066. this.normals = this._mergeElement(this.normals, other.normals);
  26067. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26068. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26069. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26070. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26071. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26072. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26073. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26074. this.colors = this._mergeElement(this.colors, other.colors);
  26075. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26076. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26077. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26078. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26079. return this;
  26080. };
  26081. VertexData.prototype._mergeElement = function (source, other) {
  26082. if (!other)
  26083. return source;
  26084. if (!source)
  26085. return other;
  26086. var len = other.length + source.length;
  26087. var isSrcTypedArray = source instanceof Float32Array;
  26088. var isOthTypedArray = other instanceof Float32Array;
  26089. // use non-loop method when the source is Float32Array
  26090. if (isSrcTypedArray) {
  26091. var ret32 = new Float32Array(len);
  26092. ret32.set(source);
  26093. ret32.set(other, source.length);
  26094. return ret32;
  26095. // source is number[], when other is also use concat
  26096. }
  26097. else if (!isOthTypedArray) {
  26098. return source.concat(other);
  26099. // source is a number[], but other is a Float32Array, loop required
  26100. }
  26101. else {
  26102. var ret = source.slice(0); // copy source to a separate array
  26103. for (var i = 0, len = other.length; i < len; i++) {
  26104. ret.push(other[i]);
  26105. }
  26106. return ret;
  26107. }
  26108. };
  26109. /**
  26110. * Serializes the VertexData.
  26111. * Returns a serialized object.
  26112. */
  26113. VertexData.prototype.serialize = function () {
  26114. var serializationObject = this.serialize();
  26115. if (this.positions) {
  26116. serializationObject.positions = this.positions;
  26117. }
  26118. if (this.normals) {
  26119. serializationObject.normals = this.normals;
  26120. }
  26121. if (this.tangents) {
  26122. serializationObject.tangents = this.tangents;
  26123. }
  26124. if (this.uvs) {
  26125. serializationObject.uvs = this.uvs;
  26126. }
  26127. if (this.uvs2) {
  26128. serializationObject.uvs2 = this.uvs2;
  26129. }
  26130. if (this.uvs3) {
  26131. serializationObject.uvs3 = this.uvs3;
  26132. }
  26133. if (this.uvs4) {
  26134. serializationObject.uvs4 = this.uvs4;
  26135. }
  26136. if (this.uvs5) {
  26137. serializationObject.uvs5 = this.uvs5;
  26138. }
  26139. if (this.uvs6) {
  26140. serializationObject.uvs6 = this.uvs6;
  26141. }
  26142. if (this.colors) {
  26143. serializationObject.colors = this.colors;
  26144. }
  26145. if (this.matricesIndices) {
  26146. serializationObject.matricesIndices = this.matricesIndices;
  26147. serializationObject.matricesIndices._isExpanded = true;
  26148. }
  26149. if (this.matricesWeights) {
  26150. serializationObject.matricesWeights = this.matricesWeights;
  26151. }
  26152. if (this.matricesIndicesExtra) {
  26153. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26154. serializationObject.matricesIndicesExtra._isExpanded = true;
  26155. }
  26156. if (this.matricesWeightsExtra) {
  26157. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26158. }
  26159. serializationObject.indices = this.indices;
  26160. return serializationObject;
  26161. };
  26162. // Statics
  26163. /**
  26164. * Returns the object VertexData associated to the passed mesh.
  26165. */
  26166. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  26167. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  26168. };
  26169. /**
  26170. * Returns the object VertexData associated to the passed geometry.
  26171. */
  26172. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  26173. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  26174. };
  26175. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  26176. var result = new VertexData();
  26177. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26178. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  26179. }
  26180. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26181. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  26182. }
  26183. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26184. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  26185. }
  26186. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26187. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  26188. }
  26189. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26190. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  26191. }
  26192. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26193. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  26194. }
  26195. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26196. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  26197. }
  26198. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26199. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  26200. }
  26201. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26202. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  26203. }
  26204. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26205. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  26206. }
  26207. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26208. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  26209. }
  26210. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26211. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  26212. }
  26213. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26214. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  26215. }
  26216. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26217. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  26218. }
  26219. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26220. return result;
  26221. };
  26222. /**
  26223. * Creates the vertexData of the Ribbon.
  26224. */
  26225. VertexData.CreateRibbon = function (options) {
  26226. var pathArray = options.pathArray;
  26227. var closeArray = options.closeArray || false;
  26228. var closePath = options.closePath || false;
  26229. var invertUV = options.invertUV || false;
  26230. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26231. var offset = options.offset || defaultOffset;
  26232. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26233. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26234. var customUV = options.uvs;
  26235. var customColors = options.colors;
  26236. var positions = [];
  26237. var indices = [];
  26238. var normals = [];
  26239. var uvs = [];
  26240. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26241. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26242. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26243. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26244. var minlg; // minimal length among all paths from pathArray
  26245. var lg = []; // array of path lengths : nb of vertex per path
  26246. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26247. var p; // path iterator
  26248. var i; // point iterator
  26249. var j; // point iterator
  26250. // if single path in pathArray
  26251. if (pathArray.length < 2) {
  26252. var ar1 = [];
  26253. var ar2 = [];
  26254. for (i = 0; i < pathArray[0].length - offset; i++) {
  26255. ar1.push(pathArray[0][i]);
  26256. ar2.push(pathArray[0][i + offset]);
  26257. }
  26258. pathArray = [ar1, ar2];
  26259. }
  26260. // positions and horizontal distances (u)
  26261. var idc = 0;
  26262. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26263. var path;
  26264. var l;
  26265. minlg = pathArray[0].length;
  26266. var vectlg;
  26267. var dist;
  26268. for (p = 0; p < pathArray.length; p++) {
  26269. uTotalDistance[p] = 0;
  26270. us[p] = [0];
  26271. path = pathArray[p];
  26272. l = path.length;
  26273. minlg = (minlg < l) ? minlg : l;
  26274. j = 0;
  26275. while (j < l) {
  26276. positions.push(path[j].x, path[j].y, path[j].z);
  26277. if (j > 0) {
  26278. vectlg = path[j].subtract(path[j - 1]).length();
  26279. dist = vectlg + uTotalDistance[p];
  26280. us[p].push(dist);
  26281. uTotalDistance[p] = dist;
  26282. }
  26283. j++;
  26284. }
  26285. if (closePath) {
  26286. j--;
  26287. positions.push(path[0].x, path[0].y, path[0].z);
  26288. vectlg = path[j].subtract(path[0]).length();
  26289. dist = vectlg + uTotalDistance[p];
  26290. us[p].push(dist);
  26291. uTotalDistance[p] = dist;
  26292. }
  26293. lg[p] = l + closePathCorr;
  26294. idx[p] = idc;
  26295. idc += (l + closePathCorr);
  26296. }
  26297. // vertical distances (v)
  26298. var path1;
  26299. var path2;
  26300. var vertex1;
  26301. var vertex2;
  26302. for (i = 0; i < minlg + closePathCorr; i++) {
  26303. vTotalDistance[i] = 0;
  26304. vs[i] = [0];
  26305. for (p = 0; p < pathArray.length - 1; p++) {
  26306. path1 = pathArray[p];
  26307. path2 = pathArray[p + 1];
  26308. if (i === minlg) {
  26309. vertex1 = path1[0];
  26310. vertex2 = path2[0];
  26311. }
  26312. else {
  26313. vertex1 = path1[i];
  26314. vertex2 = path2[i];
  26315. }
  26316. vectlg = vertex2.subtract(vertex1).length();
  26317. dist = vectlg + vTotalDistance[i];
  26318. vs[i].push(dist);
  26319. vTotalDistance[i] = dist;
  26320. }
  26321. if (closeArray) {
  26322. path1 = pathArray[p];
  26323. path2 = pathArray[0];
  26324. if (i === minlg) {
  26325. vertex2 = path2[0];
  26326. }
  26327. vectlg = vertex2.subtract(vertex1).length();
  26328. dist = vectlg + vTotalDistance[i];
  26329. vTotalDistance[i] = dist;
  26330. }
  26331. }
  26332. // uvs
  26333. var u;
  26334. var v;
  26335. if (customUV) {
  26336. for (p = 0; p < customUV.length; p++) {
  26337. uvs.push(customUV[p].x, customUV[p].y);
  26338. }
  26339. }
  26340. else {
  26341. for (p = 0; p < pathArray.length; p++) {
  26342. for (i = 0; i < minlg + closePathCorr; i++) {
  26343. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  26344. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  26345. if (invertUV) {
  26346. uvs.push(v, u);
  26347. }
  26348. else {
  26349. uvs.push(u, v);
  26350. }
  26351. }
  26352. }
  26353. }
  26354. // indices
  26355. p = 0; // path index
  26356. var pi = 0; // positions array index
  26357. var l1 = lg[p] - 1; // path1 length
  26358. var l2 = lg[p + 1] - 1; // path2 length
  26359. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26360. var shft = idx[1] - idx[0]; // shift
  26361. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26362. while (pi <= min && p < path1nb) {
  26363. // 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
  26364. indices.push(pi, pi + shft, pi + 1);
  26365. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26366. pi += 1;
  26367. if (pi === min) {
  26368. p++;
  26369. if (p === lg.length - 1) {
  26370. shft = idx[0] - idx[p];
  26371. l1 = lg[p] - 1;
  26372. l2 = lg[0] - 1;
  26373. }
  26374. else {
  26375. shft = idx[p + 1] - idx[p];
  26376. l1 = lg[p] - 1;
  26377. l2 = lg[p + 1] - 1;
  26378. }
  26379. pi = idx[p];
  26380. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26381. }
  26382. }
  26383. // normals
  26384. VertexData.ComputeNormals(positions, indices, normals);
  26385. if (closePath) {
  26386. var indexFirst = 0;
  26387. var indexLast = 0;
  26388. for (p = 0; p < pathArray.length; p++) {
  26389. indexFirst = idx[p] * 3;
  26390. if (p + 1 < pathArray.length) {
  26391. indexLast = (idx[p + 1] - 1) * 3;
  26392. }
  26393. else {
  26394. indexLast = normals.length - 3;
  26395. }
  26396. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26397. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26398. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26399. normals[indexLast] = normals[indexFirst];
  26400. normals[indexLast + 1] = normals[indexFirst + 1];
  26401. normals[indexLast + 2] = normals[indexFirst + 2];
  26402. }
  26403. }
  26404. // sides
  26405. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26406. // Colors
  26407. if (customColors) {
  26408. var colors = new Float32Array(customColors.length * 4);
  26409. for (var c = 0; c < customColors.length; c++) {
  26410. colors[c * 4] = customColors[c].r;
  26411. colors[c * 4 + 1] = customColors[c].g;
  26412. colors[c * 4 + 2] = customColors[c].b;
  26413. colors[c * 4 + 3] = customColors[c].a;
  26414. }
  26415. }
  26416. // Result
  26417. var vertexData = new VertexData();
  26418. var positions32 = new Float32Array(positions);
  26419. var normals32 = new Float32Array(normals);
  26420. var uvs32 = new Float32Array(uvs);
  26421. vertexData.indices = indices;
  26422. vertexData.positions = positions32;
  26423. vertexData.normals = normals32;
  26424. vertexData.uvs = uvs32;
  26425. if (customColors) {
  26426. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  26427. }
  26428. if (closePath) {
  26429. vertexData._idx = idx;
  26430. }
  26431. return vertexData;
  26432. };
  26433. /**
  26434. * Creates the VertexData of the Box.
  26435. */
  26436. VertexData.CreateBox = function (options) {
  26437. var normalsSource = [
  26438. new BABYLON.Vector3(0, 0, 1),
  26439. new BABYLON.Vector3(0, 0, -1),
  26440. new BABYLON.Vector3(1, 0, 0),
  26441. new BABYLON.Vector3(-1, 0, 0),
  26442. new BABYLON.Vector3(0, 1, 0),
  26443. new BABYLON.Vector3(0, -1, 0)
  26444. ];
  26445. var indices = [];
  26446. var positions = [];
  26447. var normals = [];
  26448. var uvs = [];
  26449. var width = options.width || options.size || 1;
  26450. var height = options.height || options.size || 1;
  26451. var depth = options.depth || options.size || 1;
  26452. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26453. var faceUV = options.faceUV || new Array(6);
  26454. var faceColors = options.faceColors;
  26455. var colors = [];
  26456. // default face colors and UV if undefined
  26457. for (var f = 0; f < 6; f++) {
  26458. if (faceUV[f] === undefined) {
  26459. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26460. }
  26461. if (faceColors && faceColors[f] === undefined) {
  26462. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26463. }
  26464. }
  26465. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26466. // Create each face in turn.
  26467. for (var index = 0; index < normalsSource.length; index++) {
  26468. var normal = normalsSource[index];
  26469. // Get two vectors perpendicular to the face normal and to each other.
  26470. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26471. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26472. // Six indices (two triangles) per face.
  26473. var verticesLength = positions.length / 3;
  26474. indices.push(verticesLength);
  26475. indices.push(verticesLength + 1);
  26476. indices.push(verticesLength + 2);
  26477. indices.push(verticesLength);
  26478. indices.push(verticesLength + 2);
  26479. indices.push(verticesLength + 3);
  26480. // Four vertices per face.
  26481. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26482. positions.push(vertex.x, vertex.y, vertex.z);
  26483. normals.push(normal.x, normal.y, normal.z);
  26484. uvs.push(faceUV[index].z, faceUV[index].w);
  26485. if (faceColors) {
  26486. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26487. }
  26488. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26489. positions.push(vertex.x, vertex.y, vertex.z);
  26490. normals.push(normal.x, normal.y, normal.z);
  26491. uvs.push(faceUV[index].x, faceUV[index].w);
  26492. if (faceColors) {
  26493. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26494. }
  26495. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26496. positions.push(vertex.x, vertex.y, vertex.z);
  26497. normals.push(normal.x, normal.y, normal.z);
  26498. uvs.push(faceUV[index].x, faceUV[index].y);
  26499. if (faceColors) {
  26500. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26501. }
  26502. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26503. positions.push(vertex.x, vertex.y, vertex.z);
  26504. normals.push(normal.x, normal.y, normal.z);
  26505. uvs.push(faceUV[index].z, faceUV[index].y);
  26506. if (faceColors) {
  26507. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26508. }
  26509. }
  26510. // sides
  26511. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26512. // Result
  26513. var vertexData = new VertexData();
  26514. vertexData.indices = indices;
  26515. vertexData.positions = positions;
  26516. vertexData.normals = normals;
  26517. vertexData.uvs = uvs;
  26518. if (faceColors) {
  26519. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26520. vertexData.colors = totalColors;
  26521. }
  26522. return vertexData;
  26523. };
  26524. /**
  26525. * Creates the VertexData of the Sphere.
  26526. */
  26527. VertexData.CreateSphere = function (options) {
  26528. var segments = options.segments || 32;
  26529. var diameterX = options.diameterX || options.diameter || 1;
  26530. var diameterY = options.diameterY || options.diameter || 1;
  26531. var diameterZ = options.diameterZ || options.diameter || 1;
  26532. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26533. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26534. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26535. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26536. var totalZRotationSteps = 2 + segments;
  26537. var totalYRotationSteps = 2 * totalZRotationSteps;
  26538. var indices = [];
  26539. var positions = [];
  26540. var normals = [];
  26541. var uvs = [];
  26542. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26543. var normalizedZ = zRotationStep / totalZRotationSteps;
  26544. var angleZ = normalizedZ * Math.PI * slice;
  26545. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26546. var normalizedY = yRotationStep / totalYRotationSteps;
  26547. var angleY = normalizedY * Math.PI * 2 * arc;
  26548. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26549. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26550. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26551. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26552. var vertex = complete.multiply(radius);
  26553. var normal = complete.divide(radius).normalize();
  26554. positions.push(vertex.x, vertex.y, vertex.z);
  26555. normals.push(normal.x, normal.y, normal.z);
  26556. uvs.push(normalizedY, normalizedZ);
  26557. }
  26558. if (zRotationStep > 0) {
  26559. var verticesCount = positions.length / 3;
  26560. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26561. indices.push((firstIndex));
  26562. indices.push((firstIndex + 1));
  26563. indices.push(firstIndex + totalYRotationSteps + 1);
  26564. indices.push((firstIndex + totalYRotationSteps + 1));
  26565. indices.push((firstIndex + 1));
  26566. indices.push((firstIndex + totalYRotationSteps + 2));
  26567. }
  26568. }
  26569. }
  26570. // Sides
  26571. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26572. // Result
  26573. var vertexData = new VertexData();
  26574. vertexData.indices = indices;
  26575. vertexData.positions = positions;
  26576. vertexData.normals = normals;
  26577. vertexData.uvs = uvs;
  26578. return vertexData;
  26579. };
  26580. /**
  26581. * Creates the VertexData of the Cylinder or Cone.
  26582. */
  26583. VertexData.CreateCylinder = function (options) {
  26584. var height = options.height || 2;
  26585. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  26586. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  26587. var tessellation = options.tessellation || 24;
  26588. var subdivisions = options.subdivisions || 1;
  26589. var hasRings = options.hasRings;
  26590. var enclose = options.enclose;
  26591. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26592. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26593. var faceUV = options.faceUV || new Array(3);
  26594. var faceColors = options.faceColors;
  26595. // default face colors and UV if undefined
  26596. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  26597. var ringNb = (hasRings) ? subdivisions : 1;
  26598. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  26599. var f;
  26600. for (f = 0; f < surfaceNb; f++) {
  26601. if (faceColors && faceColors[f] === undefined) {
  26602. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26603. }
  26604. }
  26605. for (f = 0; f < surfaceNb; f++) {
  26606. if (faceUV && faceUV[f] === undefined) {
  26607. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26608. }
  26609. }
  26610. var indices = [];
  26611. var positions = [];
  26612. var normals = [];
  26613. var uvs = [];
  26614. var colors = [];
  26615. var angle_step = Math.PI * 2 * arc / tessellation;
  26616. var angle;
  26617. var h;
  26618. var radius;
  26619. var tan = (diameterBottom - diameterTop) / 2 / height;
  26620. var ringVertex = BABYLON.Vector3.Zero();
  26621. var ringNormal = BABYLON.Vector3.Zero();
  26622. var ringFirstVertex = BABYLON.Vector3.Zero();
  26623. var ringFirstNormal = BABYLON.Vector3.Zero();
  26624. var quadNormal = BABYLON.Vector3.Zero();
  26625. var Y = BABYLON.Axis.Y;
  26626. // positions, normals, uvs
  26627. var i;
  26628. var j;
  26629. var r;
  26630. var ringIdx = 1;
  26631. var s = 1; // surface index
  26632. var cs = 0;
  26633. var v = 0;
  26634. for (i = 0; i <= subdivisions; i++) {
  26635. h = i / subdivisions;
  26636. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26637. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  26638. for (r = 0; r < ringIdx; r++) {
  26639. if (hasRings) {
  26640. s += r;
  26641. }
  26642. if (enclose) {
  26643. s += 2 * r;
  26644. }
  26645. for (j = 0; j <= tessellation; j++) {
  26646. angle = j * angle_step;
  26647. // position
  26648. ringVertex.x = Math.cos(-angle) * radius;
  26649. ringVertex.y = -height / 2 + h * height;
  26650. ringVertex.z = Math.sin(-angle) * radius;
  26651. // normal
  26652. if (diameterTop === 0 && i === subdivisions) {
  26653. // if no top cap, reuse former normals
  26654. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26655. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26656. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26657. }
  26658. else {
  26659. ringNormal.x = ringVertex.x;
  26660. ringNormal.z = ringVertex.z;
  26661. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26662. ringNormal.normalize();
  26663. }
  26664. // keep first ring vertex values for enclose
  26665. if (j === 0) {
  26666. ringFirstVertex.copyFrom(ringVertex);
  26667. ringFirstNormal.copyFrom(ringNormal);
  26668. }
  26669. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26670. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26671. if (hasRings) {
  26672. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  26673. }
  26674. else {
  26675. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  26676. }
  26677. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  26678. if (faceColors) {
  26679. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  26680. }
  26681. }
  26682. // if enclose, add four vertices and their dedicated normals
  26683. if (arc !== 1 && enclose) {
  26684. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26685. positions.push(0, ringVertex.y, 0);
  26686. positions.push(0, ringVertex.y, 0);
  26687. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  26688. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  26689. quadNormal.normalize();
  26690. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26691. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  26692. quadNormal.normalize();
  26693. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26694. if (hasRings) {
  26695. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  26696. }
  26697. else {
  26698. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  26699. }
  26700. uvs.push(faceUV[s + 1].x, v);
  26701. uvs.push(faceUV[s + 1].z, v);
  26702. if (hasRings) {
  26703. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  26704. }
  26705. else {
  26706. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  26707. }
  26708. uvs.push(faceUV[s + 2].x, v);
  26709. uvs.push(faceUV[s + 2].z, v);
  26710. if (faceColors) {
  26711. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26712. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26713. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26714. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26715. }
  26716. }
  26717. if (cs !== s) {
  26718. cs = s;
  26719. }
  26720. }
  26721. }
  26722. // indices
  26723. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  26724. var s;
  26725. i = 0;
  26726. for (s = 0; s < subdivisions; s++) {
  26727. for (j = 0; j < tessellation; j++) {
  26728. var i0 = i * (e + 1) + j;
  26729. var i1 = (i + 1) * (e + 1) + j;
  26730. var i2 = i * (e + 1) + (j + 1);
  26731. var i3 = (i + 1) * (e + 1) + (j + 1);
  26732. indices.push(i0, i1, i2);
  26733. indices.push(i3, i2, i1);
  26734. }
  26735. if (arc !== 1 && enclose) {
  26736. indices.push(i0 + 2, i1 + 2, i2 + 2);
  26737. indices.push(i3 + 2, i2 + 2, i1 + 2);
  26738. indices.push(i0 + 4, i1 + 4, i2 + 4);
  26739. indices.push(i3 + 4, i2 + 4, i1 + 4);
  26740. }
  26741. i = (hasRings) ? (i + 2) : (i + 1);
  26742. }
  26743. // Caps
  26744. var createCylinderCap = function (isTop) {
  26745. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26746. if (radius === 0) {
  26747. return;
  26748. }
  26749. // Cap positions, normals & uvs
  26750. var angle;
  26751. var circleVector;
  26752. var i;
  26753. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  26754. var c;
  26755. if (faceColors) {
  26756. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  26757. }
  26758. // cap center
  26759. var vbase = positions.length / 3;
  26760. var offset = isTop ? height / 2 : -height / 2;
  26761. var center = new BABYLON.Vector3(0, offset, 0);
  26762. positions.push(center.x, center.y, center.z);
  26763. normals.push(0, isTop ? 1 : -1, 0);
  26764. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  26765. if (faceColors) {
  26766. colors.push(c.r, c.g, c.b, c.a);
  26767. }
  26768. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26769. for (i = 0; i <= tessellation; i++) {
  26770. angle = Math.PI * 2 * i * arc / tessellation;
  26771. var cos = Math.cos(-angle);
  26772. var sin = Math.sin(-angle);
  26773. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  26774. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  26775. positions.push(circleVector.x, circleVector.y, circleVector.z);
  26776. normals.push(0, isTop ? 1 : -1, 0);
  26777. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  26778. if (faceColors) {
  26779. colors.push(c.r, c.g, c.b, c.a);
  26780. }
  26781. }
  26782. // Cap indices
  26783. for (i = 0; i < tessellation; i++) {
  26784. if (!isTop) {
  26785. indices.push(vbase);
  26786. indices.push(vbase + (i + 1));
  26787. indices.push(vbase + (i + 2));
  26788. }
  26789. else {
  26790. indices.push(vbase);
  26791. indices.push(vbase + (i + 2));
  26792. indices.push(vbase + (i + 1));
  26793. }
  26794. }
  26795. };
  26796. // add caps to geometry
  26797. createCylinderCap(false);
  26798. createCylinderCap(true);
  26799. // Sides
  26800. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26801. var vertexData = new VertexData();
  26802. vertexData.indices = indices;
  26803. vertexData.positions = positions;
  26804. vertexData.normals = normals;
  26805. vertexData.uvs = uvs;
  26806. if (faceColors) {
  26807. vertexData.colors = colors;
  26808. }
  26809. return vertexData;
  26810. };
  26811. /**
  26812. * Creates the VertexData of the Torus.
  26813. */
  26814. VertexData.CreateTorus = function (options) {
  26815. var indices = [];
  26816. var positions = [];
  26817. var normals = [];
  26818. var uvs = [];
  26819. var diameter = options.diameter || 1;
  26820. var thickness = options.thickness || 0.5;
  26821. var tessellation = options.tessellation || 16;
  26822. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26823. var stride = tessellation + 1;
  26824. for (var i = 0; i <= tessellation; i++) {
  26825. var u = i / tessellation;
  26826. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26827. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26828. for (var j = 0; j <= tessellation; j++) {
  26829. var v = 1 - j / tessellation;
  26830. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26831. var dx = Math.cos(innerAngle);
  26832. var dy = Math.sin(innerAngle);
  26833. // Create a vertex.
  26834. var normal = new BABYLON.Vector3(dx, dy, 0);
  26835. var position = normal.scale(thickness / 2);
  26836. var textureCoordinate = new BABYLON.Vector2(u, v);
  26837. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26838. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26839. positions.push(position.x, position.y, position.z);
  26840. normals.push(normal.x, normal.y, normal.z);
  26841. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26842. // And create indices for two triangles.
  26843. var nextI = (i + 1) % stride;
  26844. var nextJ = (j + 1) % stride;
  26845. indices.push(i * stride + j);
  26846. indices.push(i * stride + nextJ);
  26847. indices.push(nextI * stride + j);
  26848. indices.push(i * stride + nextJ);
  26849. indices.push(nextI * stride + nextJ);
  26850. indices.push(nextI * stride + j);
  26851. }
  26852. }
  26853. // Sides
  26854. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26855. // Result
  26856. var vertexData = new VertexData();
  26857. vertexData.indices = indices;
  26858. vertexData.positions = positions;
  26859. vertexData.normals = normals;
  26860. vertexData.uvs = uvs;
  26861. return vertexData;
  26862. };
  26863. /**
  26864. * Creates the VertexData of the LineSystem.
  26865. */
  26866. VertexData.CreateLineSystem = function (options) {
  26867. var indices = [];
  26868. var positions = [];
  26869. var lines = options.lines;
  26870. var idx = 0;
  26871. for (var l = 0; l < lines.length; l++) {
  26872. var points = lines[l];
  26873. for (var index = 0; index < points.length; index++) {
  26874. positions.push(points[index].x, points[index].y, points[index].z);
  26875. if (index > 0) {
  26876. indices.push(idx - 1);
  26877. indices.push(idx);
  26878. }
  26879. idx++;
  26880. }
  26881. }
  26882. var vertexData = new VertexData();
  26883. vertexData.indices = indices;
  26884. vertexData.positions = positions;
  26885. return vertexData;
  26886. };
  26887. /**
  26888. * Create the VertexData of the DashedLines.
  26889. */
  26890. VertexData.CreateDashedLines = function (options) {
  26891. var dashSize = options.dashSize || 3;
  26892. var gapSize = options.gapSize || 1;
  26893. var dashNb = options.dashNb || 200;
  26894. var points = options.points;
  26895. var positions = new Array();
  26896. var indices = new Array();
  26897. var curvect = BABYLON.Vector3.Zero();
  26898. var lg = 0;
  26899. var nb = 0;
  26900. var shft = 0;
  26901. var dashshft = 0;
  26902. var curshft = 0;
  26903. var idx = 0;
  26904. var i = 0;
  26905. for (i = 0; i < points.length - 1; i++) {
  26906. points[i + 1].subtractToRef(points[i], curvect);
  26907. lg += curvect.length();
  26908. }
  26909. shft = lg / dashNb;
  26910. dashshft = dashSize * shft / (dashSize + gapSize);
  26911. for (i = 0; i < points.length - 1; i++) {
  26912. points[i + 1].subtractToRef(points[i], curvect);
  26913. nb = Math.floor(curvect.length() / shft);
  26914. curvect.normalize();
  26915. for (var j = 0; j < nb; j++) {
  26916. curshft = shft * j;
  26917. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26918. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26919. indices.push(idx, idx + 1);
  26920. idx += 2;
  26921. }
  26922. }
  26923. // Result
  26924. var vertexData = new VertexData();
  26925. vertexData.positions = positions;
  26926. vertexData.indices = indices;
  26927. return vertexData;
  26928. };
  26929. /**
  26930. * Creates the VertexData of the Ground.
  26931. */
  26932. VertexData.CreateGround = function (options) {
  26933. var indices = [];
  26934. var positions = [];
  26935. var normals = [];
  26936. var uvs = [];
  26937. var row, col;
  26938. var width = options.width || 1;
  26939. var height = options.height || 1;
  26940. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26941. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26942. for (row = 0; row <= subdivisionsY; row++) {
  26943. for (col = 0; col <= subdivisionsX; col++) {
  26944. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  26945. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26946. positions.push(position.x, position.y, position.z);
  26947. normals.push(normal.x, normal.y, normal.z);
  26948. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  26949. }
  26950. }
  26951. for (row = 0; row < subdivisionsY; row++) {
  26952. for (col = 0; col < subdivisionsX; col++) {
  26953. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26954. indices.push(col + 1 + row * (subdivisionsX + 1));
  26955. indices.push(col + row * (subdivisionsX + 1));
  26956. indices.push(col + (row + 1) * (subdivisionsX + 1));
  26957. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26958. indices.push(col + row * (subdivisionsX + 1));
  26959. }
  26960. }
  26961. // Result
  26962. var vertexData = new VertexData();
  26963. vertexData.indices = indices;
  26964. vertexData.positions = positions;
  26965. vertexData.normals = normals;
  26966. vertexData.uvs = uvs;
  26967. return vertexData;
  26968. };
  26969. /**
  26970. * Creates the VertexData of the TiledGround.
  26971. */
  26972. VertexData.CreateTiledGround = function (options) {
  26973. var xmin = options.xmin || -1.0;
  26974. var zmin = options.zmin || -1.0;
  26975. var xmax = options.xmax || 1.0;
  26976. var zmax = options.zmax || 1.0;
  26977. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  26978. var precision = options.precision || { w: 1, h: 1 };
  26979. var indices = [];
  26980. var positions = [];
  26981. var normals = [];
  26982. var uvs = [];
  26983. var row, col, tileRow, tileCol;
  26984. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  26985. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26986. precision.w = (precision.w < 1) ? 1 : precision.w;
  26987. precision.h = (precision.h < 1) ? 1 : precision.h;
  26988. var tileSize = {
  26989. 'w': (xmax - xmin) / subdivisions.w,
  26990. 'h': (zmax - zmin) / subdivisions.h
  26991. };
  26992. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26993. // Indices
  26994. var base = positions.length / 3;
  26995. var rowLength = precision.w + 1;
  26996. for (row = 0; row < precision.h; row++) {
  26997. for (col = 0; col < precision.w; col++) {
  26998. var square = [
  26999. base + col + row * rowLength,
  27000. base + (col + 1) + row * rowLength,
  27001. base + (col + 1) + (row + 1) * rowLength,
  27002. base + col + (row + 1) * rowLength
  27003. ];
  27004. indices.push(square[1]);
  27005. indices.push(square[2]);
  27006. indices.push(square[3]);
  27007. indices.push(square[0]);
  27008. indices.push(square[1]);
  27009. indices.push(square[3]);
  27010. }
  27011. }
  27012. // Position, normals and uvs
  27013. var position = BABYLON.Vector3.Zero();
  27014. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27015. for (row = 0; row <= precision.h; row++) {
  27016. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27017. for (col = 0; col <= precision.w; col++) {
  27018. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27019. position.y = 0;
  27020. positions.push(position.x, position.y, position.z);
  27021. normals.push(normal.x, normal.y, normal.z);
  27022. uvs.push(col / precision.w, row / precision.h);
  27023. }
  27024. }
  27025. }
  27026. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27027. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27028. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27029. }
  27030. }
  27031. // Result
  27032. var vertexData = new VertexData();
  27033. vertexData.indices = indices;
  27034. vertexData.positions = positions;
  27035. vertexData.normals = normals;
  27036. vertexData.uvs = uvs;
  27037. return vertexData;
  27038. };
  27039. /**
  27040. * Creates the VertexData of the Ground designed from a heightmap.
  27041. */
  27042. VertexData.CreateGroundFromHeightMap = function (options) {
  27043. var indices = [];
  27044. var positions = [];
  27045. var normals = [];
  27046. var uvs = [];
  27047. var row, col;
  27048. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27049. // Vertices
  27050. for (row = 0; row <= options.subdivisions; row++) {
  27051. for (col = 0; col <= options.subdivisions; col++) {
  27052. 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));
  27053. // Compute height
  27054. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27055. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27056. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27057. var r = options.buffer[pos] / 255.0;
  27058. var g = options.buffer[pos + 1] / 255.0;
  27059. var b = options.buffer[pos + 2] / 255.0;
  27060. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27061. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27062. // Add vertex
  27063. positions.push(position.x, position.y, position.z);
  27064. normals.push(0, 0, 0);
  27065. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27066. }
  27067. }
  27068. // Indices
  27069. for (row = 0; row < options.subdivisions; row++) {
  27070. for (col = 0; col < options.subdivisions; col++) {
  27071. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27072. indices.push(col + 1 + row * (options.subdivisions + 1));
  27073. indices.push(col + row * (options.subdivisions + 1));
  27074. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27075. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27076. indices.push(col + row * (options.subdivisions + 1));
  27077. }
  27078. }
  27079. // Normals
  27080. VertexData.ComputeNormals(positions, indices, normals);
  27081. // Result
  27082. var vertexData = new VertexData();
  27083. vertexData.indices = indices;
  27084. vertexData.positions = positions;
  27085. vertexData.normals = normals;
  27086. vertexData.uvs = uvs;
  27087. return vertexData;
  27088. };
  27089. /**
  27090. * Creates the VertexData of the Plane.
  27091. */
  27092. VertexData.CreatePlane = function (options) {
  27093. var indices = [];
  27094. var positions = [];
  27095. var normals = [];
  27096. var uvs = [];
  27097. var width = options.width || options.size || 1;
  27098. var height = options.height || options.size || 1;
  27099. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27100. // Vertices
  27101. var halfWidth = width / 2.0;
  27102. var halfHeight = height / 2.0;
  27103. positions.push(-halfWidth, -halfHeight, 0);
  27104. normals.push(0, 0, -1.0);
  27105. uvs.push(0.0, 0.0);
  27106. positions.push(halfWidth, -halfHeight, 0);
  27107. normals.push(0, 0, -1.0);
  27108. uvs.push(1.0, 0.0);
  27109. positions.push(halfWidth, halfHeight, 0);
  27110. normals.push(0, 0, -1.0);
  27111. uvs.push(1.0, 1.0);
  27112. positions.push(-halfWidth, halfHeight, 0);
  27113. normals.push(0, 0, -1.0);
  27114. uvs.push(0.0, 1.0);
  27115. // Indices
  27116. indices.push(0);
  27117. indices.push(1);
  27118. indices.push(2);
  27119. indices.push(0);
  27120. indices.push(2);
  27121. indices.push(3);
  27122. // Sides
  27123. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27124. // Result
  27125. var vertexData = new VertexData();
  27126. vertexData.indices = indices;
  27127. vertexData.positions = positions;
  27128. vertexData.normals = normals;
  27129. vertexData.uvs = uvs;
  27130. return vertexData;
  27131. };
  27132. /**
  27133. * Creates the VertexData of the Disc or regular Polygon.
  27134. */
  27135. VertexData.CreateDisc = function (options) {
  27136. var positions = [];
  27137. var indices = [];
  27138. var normals = [];
  27139. var uvs = [];
  27140. var radius = options.radius || 0.5;
  27141. var tessellation = options.tessellation || 64;
  27142. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27143. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27144. // positions and uvs
  27145. positions.push(0, 0, 0); // disc center first
  27146. uvs.push(0.5, 0.5);
  27147. var theta = Math.PI * 2 * arc;
  27148. var step = theta / tessellation;
  27149. for (var a = 0; a < theta; a += step) {
  27150. var x = Math.cos(a);
  27151. var y = Math.sin(a);
  27152. var u = (x + 1) / 2;
  27153. var v = (1 - y) / 2;
  27154. positions.push(radius * x, radius * y, 0);
  27155. uvs.push(u, v);
  27156. }
  27157. if (arc === 1) {
  27158. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27159. uvs.push(uvs[2], uvs[3]);
  27160. }
  27161. //indices
  27162. var vertexNb = positions.length / 3;
  27163. for (var i = 1; i < vertexNb - 1; i++) {
  27164. indices.push(i + 1, 0, i);
  27165. }
  27166. // result
  27167. VertexData.ComputeNormals(positions, indices, normals);
  27168. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27169. var vertexData = new VertexData();
  27170. vertexData.indices = indices;
  27171. vertexData.positions = positions;
  27172. vertexData.normals = normals;
  27173. vertexData.uvs = uvs;
  27174. return vertexData;
  27175. };
  27176. /**
  27177. * Re-creates the VertexData of the Polygon for sideOrientation.
  27178. */
  27179. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  27180. var faceUV = fUV || new Array(3);
  27181. var faceColors = fColors;
  27182. var colors = [];
  27183. // default face colors and UV if undefined
  27184. for (var f = 0; f < 3; f++) {
  27185. if (faceUV[f] === undefined) {
  27186. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27187. }
  27188. if (faceColors && faceColors[f] === undefined) {
  27189. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27190. }
  27191. }
  27192. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27193. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27194. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27195. var indices = polygon.getIndices();
  27196. // set face colours and textures
  27197. var idx = 0;
  27198. var face = 0;
  27199. for (var index = 0; index < normals.length; index += 3) {
  27200. //Edge Face no. 1
  27201. if (Math.abs(normals[index + 1]) < 0.001) {
  27202. face = 1;
  27203. }
  27204. //Top Face no. 0
  27205. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  27206. face = 0;
  27207. }
  27208. //Bottom Face no. 2
  27209. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  27210. face = 2;
  27211. }
  27212. idx = index / 3;
  27213. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  27214. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  27215. if (faceColors) {
  27216. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  27217. }
  27218. }
  27219. // sides
  27220. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  27221. // Result
  27222. var vertexData = new VertexData();
  27223. vertexData.indices = indices;
  27224. vertexData.positions = positions;
  27225. vertexData.normals = normals;
  27226. vertexData.uvs = uvs;
  27227. if (faceColors) {
  27228. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27229. vertexData.colors = totalColors;
  27230. }
  27231. return vertexData;
  27232. };
  27233. /**
  27234. * Creates the VertexData of the IcoSphere.
  27235. */
  27236. VertexData.CreateIcoSphere = function (options) {
  27237. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27238. var radius = options.radius || 1;
  27239. var flat = (options.flat === undefined) ? true : options.flat;
  27240. var subdivisions = options.subdivisions || 4;
  27241. var radiusX = options.radiusX || radius;
  27242. var radiusY = options.radiusY || radius;
  27243. var radiusZ = options.radiusZ || radius;
  27244. var t = (1 + Math.sqrt(5)) / 2;
  27245. // 12 vertex x,y,z
  27246. var ico_vertices = [
  27247. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27248. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27249. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27250. ];
  27251. // index of 3 vertex makes a face of icopshere
  27252. var ico_indices = [
  27253. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27254. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27255. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27256. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27257. ];
  27258. // vertex for uv have aliased position, not for UV
  27259. var vertices_unalias_id = [
  27260. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27261. // vertex alias
  27262. 0,
  27263. 2,
  27264. 3,
  27265. 3,
  27266. 3,
  27267. 4,
  27268. 7,
  27269. 8,
  27270. 9,
  27271. 9,
  27272. 10,
  27273. 11 // 23: B + 12
  27274. ];
  27275. // uv as integer step (not pixels !)
  27276. var ico_vertexuv = [
  27277. 5, 1, 3, 1, 6, 4, 0, 0,
  27278. 5, 3, 4, 2, 2, 2, 4, 0,
  27279. 2, 0, 1, 1, 6, 0, 6, 2,
  27280. // vertex alias (for same vertex on different faces)
  27281. 0, 4,
  27282. 3, 3,
  27283. 4, 4,
  27284. 3, 1,
  27285. 4, 2,
  27286. 4, 4,
  27287. 0, 2,
  27288. 1, 1,
  27289. 2, 2,
  27290. 3, 3,
  27291. 1, 3,
  27292. 2, 4 // 23: B + 12
  27293. ];
  27294. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27295. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27296. // First island of uv mapping
  27297. // v = 4h 3+ 2
  27298. // v = 3h 9+ 4
  27299. // v = 2h 9+ 5 B
  27300. // v = 1h 9 1 0
  27301. // v = 0h 3 8 7 A
  27302. // u = 0 1 2 3 4 5 6 *a
  27303. // Second island of uv mapping
  27304. // v = 4h 0+ B+ 4+
  27305. // v = 3h A+ 2+
  27306. // v = 2h 7+ 6 3+
  27307. // v = 1h 8+ 3+
  27308. // v = 0h
  27309. // u = 0 1 2 3 4 5 6 *a
  27310. // Face layout on texture UV mapping
  27311. // ============
  27312. // \ 4 /\ 16 / ======
  27313. // \ / \ / /\ 11 /
  27314. // \/ 7 \/ / \ /
  27315. // ======= / 10 \/
  27316. // /\ 17 /\ =======
  27317. // / \ / \ \ 15 /\
  27318. // / 8 \/ 12 \ \ / \
  27319. // ============ \/ 6 \
  27320. // \ 18 /\ ============
  27321. // \ / \ \ 5 /\ 0 /
  27322. // \/ 13 \ \ / \ /
  27323. // ======= \/ 1 \/
  27324. // =============
  27325. // /\ 19 /\ 2 /\
  27326. // / \ / \ / \
  27327. // / 14 \/ 9 \/ 3 \
  27328. // ===================
  27329. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27330. var ustep = 138 / 1024;
  27331. var vstep = 239 / 1024;
  27332. var uoffset = 60 / 1024;
  27333. var voffset = 26 / 1024;
  27334. // Second island should have margin, not to touch the first island
  27335. // avoid any borderline artefact in pixel rounding
  27336. var island_u_offset = -40 / 1024;
  27337. var island_v_offset = +20 / 1024;
  27338. // face is either island 0 or 1 :
  27339. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27340. var island = [
  27341. 0, 0, 0, 0, 1,
  27342. 0, 0, 1, 1, 0,
  27343. 0, 0, 1, 1, 0,
  27344. 0, 1, 1, 1, 0 // 15 - 19
  27345. ];
  27346. var indices = [];
  27347. var positions = [];
  27348. var normals = [];
  27349. var uvs = [];
  27350. var current_indice = 0;
  27351. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27352. var face_vertex_pos = new Array(3);
  27353. var face_vertex_uv = new Array(3);
  27354. var v012;
  27355. for (v012 = 0; v012 < 3; v012++) {
  27356. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27357. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27358. }
  27359. // create all with normals
  27360. for (var face = 0; face < 20; face++) {
  27361. // 3 vertex per face
  27362. for (v012 = 0; v012 < 3; v012++) {
  27363. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27364. var v_id = ico_indices[3 * face + v012];
  27365. // vertex have 3D position (x,y,z)
  27366. 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]);
  27367. // Normalize to get normal, then scale to radius
  27368. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27369. // uv Coordinates from vertex ID
  27370. 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);
  27371. }
  27372. // Subdivide the face (interpolate pos, norm, uv)
  27373. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27374. // - norm is linear interpolation of vertex corner normal
  27375. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27376. // - uv is linear interpolation
  27377. //
  27378. // Topology is as below for sub-divide by 2
  27379. // vertex shown as v0,v1,v2
  27380. // interp index is i1 to progress in range [v0,v1[
  27381. // interp index is i2 to progress in range [v0,v2[
  27382. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27383. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27384. //
  27385. //
  27386. // i2 v2
  27387. // ^ ^
  27388. // / / \
  27389. // / / \
  27390. // / / \
  27391. // / / (0,1) \
  27392. // / #---------\
  27393. // / / \ (0,0)'/ \
  27394. // / / \ / \
  27395. // / / \ / \
  27396. // / / (0,0) \ / (1,0) \
  27397. // / #---------#---------\
  27398. // v0 v1
  27399. //
  27400. // --------------------> i1
  27401. //
  27402. // interp of (i1,i2):
  27403. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27404. // along i1 : lerp(x0,x1, i1/(S-i2))
  27405. //
  27406. // centroid of triangle is needed to get help normal computation
  27407. // (c1,c2) are used for centroid location
  27408. var interp_vertex = function (i1, i2, c1, c2) {
  27409. // vertex is interpolated from
  27410. // - face_vertex_pos[0..2]
  27411. // - face_vertex_uv[0..2]
  27412. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  27413. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  27414. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  27415. pos_interp.normalize();
  27416. var vertex_normal;
  27417. if (flat) {
  27418. // in flat mode, recalculate normal as face centroid normal
  27419. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  27420. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  27421. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  27422. }
  27423. else {
  27424. // in smooth mode, recalculate normal from each single vertex position
  27425. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  27426. }
  27427. // Vertex normal need correction due to X,Y,Z radius scaling
  27428. vertex_normal.x /= radiusX;
  27429. vertex_normal.y /= radiusY;
  27430. vertex_normal.z /= radiusZ;
  27431. vertex_normal.normalize();
  27432. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  27433. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  27434. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  27435. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  27436. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  27437. uvs.push(uv_interp.x, uv_interp.y);
  27438. // push each vertex has member of a face
  27439. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  27440. indices.push(current_indice);
  27441. current_indice++;
  27442. };
  27443. for (var i2 = 0; i2 < subdivisions; i2++) {
  27444. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  27445. // face : (i1,i2) for /\ :
  27446. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  27447. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27448. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27449. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27450. if (i1 + i2 + 1 < subdivisions) {
  27451. // face : (i1,i2)' for \/ :
  27452. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27453. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27454. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27455. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27456. }
  27457. }
  27458. }
  27459. }
  27460. // Sides
  27461. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27462. // Result
  27463. var vertexData = new VertexData();
  27464. vertexData.indices = indices;
  27465. vertexData.positions = positions;
  27466. vertexData.normals = normals;
  27467. vertexData.uvs = uvs;
  27468. return vertexData;
  27469. };
  27470. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  27471. /**
  27472. * Creates the VertexData of the Polyhedron.
  27473. */
  27474. VertexData.CreatePolyhedron = function (options) {
  27475. // provided polyhedron types :
  27476. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  27477. // 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)
  27478. var polyhedra = [];
  27479. 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]] };
  27480. 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]] };
  27481. polyhedra[2] = {
  27482. 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]],
  27483. 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]]
  27484. };
  27485. polyhedra[3] = {
  27486. 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]],
  27487. 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]]
  27488. };
  27489. polyhedra[4] = {
  27490. 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]],
  27491. 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]]
  27492. };
  27493. 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]] };
  27494. 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]] };
  27495. 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]] };
  27496. 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]] };
  27497. 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]] };
  27498. 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]] };
  27499. 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]] };
  27500. 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]] };
  27501. 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]] };
  27502. polyhedra[14] = {
  27503. 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]],
  27504. 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]]
  27505. };
  27506. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  27507. var size = options.size;
  27508. var sizeX = options.sizeX || size || 1;
  27509. var sizeY = options.sizeY || size || 1;
  27510. var sizeZ = options.sizeZ || size || 1;
  27511. var data = options.custom || polyhedra[type];
  27512. var nbfaces = data.face.length;
  27513. var faceUV = options.faceUV || new Array(nbfaces);
  27514. var faceColors = options.faceColors;
  27515. var flat = (options.flat === undefined) ? true : options.flat;
  27516. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27517. var positions = [];
  27518. var indices = [];
  27519. var normals = [];
  27520. var uvs = [];
  27521. var colors = [];
  27522. var index = 0;
  27523. var faceIdx = 0; // face cursor in the array "indexes"
  27524. var indexes = [];
  27525. var i = 0;
  27526. var f = 0;
  27527. var u, v, ang, x, y, tmp;
  27528. // default face colors and UV if undefined
  27529. if (flat) {
  27530. for (f = 0; f < nbfaces; f++) {
  27531. if (faceColors && faceColors[f] === undefined) {
  27532. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27533. }
  27534. if (faceUV && faceUV[f] === undefined) {
  27535. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27536. }
  27537. }
  27538. }
  27539. if (!flat) {
  27540. for (i = 0; i < data.vertex.length; i++) {
  27541. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  27542. uvs.push(0, 0);
  27543. }
  27544. for (f = 0; f < nbfaces; f++) {
  27545. for (i = 0; i < data.face[f].length - 2; i++) {
  27546. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  27547. }
  27548. }
  27549. }
  27550. else {
  27551. for (f = 0; f < nbfaces; f++) {
  27552. var fl = data.face[f].length; // number of vertices of the current face
  27553. ang = 2 * Math.PI / fl;
  27554. x = 0.5 * Math.tan(ang / 2);
  27555. y = 0.5;
  27556. // positions, uvs, colors
  27557. for (i = 0; i < fl; i++) {
  27558. // positions
  27559. 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);
  27560. indexes.push(index);
  27561. index++;
  27562. // uvs
  27563. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  27564. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  27565. uvs.push(u, v);
  27566. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  27567. y = x * Math.sin(ang) + y * Math.cos(ang);
  27568. x = tmp;
  27569. // colors
  27570. if (faceColors) {
  27571. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  27572. }
  27573. }
  27574. // indices from indexes
  27575. for (i = 0; i < fl - 2; i++) {
  27576. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  27577. }
  27578. faceIdx += fl;
  27579. }
  27580. }
  27581. VertexData.ComputeNormals(positions, indices, normals);
  27582. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27583. var vertexData = new VertexData();
  27584. vertexData.positions = positions;
  27585. vertexData.indices = indices;
  27586. vertexData.normals = normals;
  27587. vertexData.uvs = uvs;
  27588. if (faceColors && flat) {
  27589. vertexData.colors = colors;
  27590. }
  27591. return vertexData;
  27592. };
  27593. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27594. /**
  27595. * Creates the VertexData of the Torus Knot.
  27596. */
  27597. VertexData.CreateTorusKnot = function (options) {
  27598. var indices = [];
  27599. var positions = [];
  27600. var normals = [];
  27601. var uvs = [];
  27602. var radius = options.radius || 2;
  27603. var tube = options.tube || 0.5;
  27604. var radialSegments = options.radialSegments || 32;
  27605. var tubularSegments = options.tubularSegments || 32;
  27606. var p = options.p || 2;
  27607. var q = options.q || 3;
  27608. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27609. // Helper
  27610. var getPos = function (angle) {
  27611. var cu = Math.cos(angle);
  27612. var su = Math.sin(angle);
  27613. var quOverP = q / p * angle;
  27614. var cs = Math.cos(quOverP);
  27615. var tx = radius * (2 + cs) * 0.5 * cu;
  27616. var ty = radius * (2 + cs) * su * 0.5;
  27617. var tz = radius * Math.sin(quOverP) * 0.5;
  27618. return new BABYLON.Vector3(tx, ty, tz);
  27619. };
  27620. // Vertices
  27621. var i;
  27622. var j;
  27623. for (i = 0; i <= radialSegments; i++) {
  27624. var modI = i % radialSegments;
  27625. var u = modI / radialSegments * 2 * p * Math.PI;
  27626. var p1 = getPos(u);
  27627. var p2 = getPos(u + 0.01);
  27628. var tang = p2.subtract(p1);
  27629. var n = p2.add(p1);
  27630. var bitan = BABYLON.Vector3.Cross(tang, n);
  27631. n = BABYLON.Vector3.Cross(bitan, tang);
  27632. bitan.normalize();
  27633. n.normalize();
  27634. for (j = 0; j < tubularSegments; j++) {
  27635. var modJ = j % tubularSegments;
  27636. var v = modJ / tubularSegments * 2 * Math.PI;
  27637. var cx = -tube * Math.cos(v);
  27638. var cy = tube * Math.sin(v);
  27639. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27640. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27641. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27642. uvs.push(i / radialSegments);
  27643. uvs.push(j / tubularSegments);
  27644. }
  27645. }
  27646. for (i = 0; i < radialSegments; i++) {
  27647. for (j = 0; j < tubularSegments; j++) {
  27648. var jNext = (j + 1) % tubularSegments;
  27649. var a = i * tubularSegments + j;
  27650. var b = (i + 1) * tubularSegments + j;
  27651. var c = (i + 1) * tubularSegments + jNext;
  27652. var d = i * tubularSegments + jNext;
  27653. indices.push(d);
  27654. indices.push(b);
  27655. indices.push(a);
  27656. indices.push(d);
  27657. indices.push(c);
  27658. indices.push(b);
  27659. }
  27660. }
  27661. // Normals
  27662. VertexData.ComputeNormals(positions, indices, normals);
  27663. // Sides
  27664. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27665. // Result
  27666. var vertexData = new VertexData();
  27667. vertexData.indices = indices;
  27668. vertexData.positions = positions;
  27669. vertexData.normals = normals;
  27670. vertexData.uvs = uvs;
  27671. return vertexData;
  27672. };
  27673. // Tools
  27674. /**
  27675. * @param {any} - positions (number[] or Float32Array)
  27676. * @param {any} - indices (number[] or Uint16Array)
  27677. * @param {any} - normals (number[] or Float32Array)
  27678. * options (optional) :
  27679. * facetPositions : optional array of facet positions (vector3)
  27680. * facetNormals : optional array of facet normals (vector3)
  27681. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  27682. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  27683. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  27684. * bbSize : optional bounding box size data, required for facetPartitioning computation
  27685. * bInfo : optional bounding info, required for facetPartitioning computation
  27686. */
  27687. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  27688. // temporary scalar variables
  27689. var index = 0; // facet index
  27690. var p1p2x = 0.0; // p1p2 vector x coordinate
  27691. var p1p2y = 0.0; // p1p2 vector y coordinate
  27692. var p1p2z = 0.0; // p1p2 vector z coordinate
  27693. var p3p2x = 0.0; // p3p2 vector x coordinate
  27694. var p3p2y = 0.0; // p3p2 vector y coordinate
  27695. var p3p2z = 0.0; // p3p2 vector z coordinate
  27696. var faceNormalx = 0.0; // facet normal x coordinate
  27697. var faceNormaly = 0.0; // facet normal y coordinate
  27698. var faceNormalz = 0.0; // facet normal z coordinate
  27699. var length = 0.0; // facet normal length before normalization
  27700. var v1x = 0; // vector1 x index in the positions array
  27701. var v1y = 0; // vector1 y index in the positions array
  27702. var v1z = 0; // vector1 z index in the positions array
  27703. var v2x = 0; // vector2 x index in the positions array
  27704. var v2y = 0; // vector2 y index in the positions array
  27705. var v2z = 0; // vector2 z index in the positions array
  27706. var v3x = 0; // vector3 x index in the positions array
  27707. var v3y = 0; // vector3 y index in the positions array
  27708. var v3z = 0; // vector3 z index in the positions array
  27709. var computeFacetNormals = false;
  27710. var computeFacetPositions = false;
  27711. var computeFacetPartitioning = false;
  27712. var faceNormalSign = 1;
  27713. if (options) {
  27714. computeFacetNormals = (options.facetNormals) ? true : false;
  27715. computeFacetPositions = (options.facetPositions) ? true : false;
  27716. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  27717. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  27718. }
  27719. // facetPartitioning reinit if needed
  27720. if (computeFacetPartitioning) {
  27721. var ox = 0; // X partitioning index for facet position
  27722. var oy = 0; // Y partinioning index for facet position
  27723. var oz = 0; // Z partinioning index for facet position
  27724. var b1x = 0; // X partitioning index for facet v1 vertex
  27725. var b1y = 0; // Y partitioning index for facet v1 vertex
  27726. var b1z = 0; // z partitioning index for facet v1 vertex
  27727. var b2x = 0; // X partitioning index for facet v2 vertex
  27728. var b2y = 0; // Y partitioning index for facet v2 vertex
  27729. var b2z = 0; // Z partitioning index for facet v2 vertex
  27730. var b3x = 0; // X partitioning index for facet v3 vertex
  27731. var b3y = 0; // Y partitioning index for facet v3 vertex
  27732. var b3z = 0; // Z partitioning index for facet v3 vertex
  27733. var block_idx_o = 0; // facet barycenter block index
  27734. var block_idx_v1 = 0; // v1 vertex block index
  27735. var block_idx_v2 = 0; // v2 vertex block index
  27736. var block_idx_v3 = 0; // v3 vertex block index
  27737. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  27738. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  27739. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  27740. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  27741. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  27742. var subSq = options.subDiv.max * options.subDiv.max;
  27743. options.facetPartitioning.length = 0;
  27744. }
  27745. // reset the normals
  27746. for (index = 0; index < positions.length; index++) {
  27747. normals[index] = 0.0;
  27748. }
  27749. // Loop : 1 indice triplet = 1 facet
  27750. var nbFaces = indices.length / 3;
  27751. for (index = 0; index < nbFaces; index++) {
  27752. // get the indexes of the coordinates of each vertex of the facet
  27753. v1x = indices[index * 3] * 3;
  27754. v1y = v1x + 1;
  27755. v1z = v1x + 2;
  27756. v2x = indices[index * 3 + 1] * 3;
  27757. v2y = v2x + 1;
  27758. v2z = v2x + 2;
  27759. v3x = indices[index * 3 + 2] * 3;
  27760. v3y = v3x + 1;
  27761. v3z = v3x + 2;
  27762. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  27763. p1p2y = positions[v1y] - positions[v2y];
  27764. p1p2z = positions[v1z] - positions[v2z];
  27765. p3p2x = positions[v3x] - positions[v2x];
  27766. p3p2y = positions[v3y] - positions[v2y];
  27767. p3p2z = positions[v3z] - positions[v2z];
  27768. // compute the face normal with the cross product
  27769. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  27770. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  27771. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  27772. // normalize this normal and store it in the array facetData
  27773. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27774. length = (length === 0) ? 1.0 : length;
  27775. faceNormalx /= length;
  27776. faceNormaly /= length;
  27777. faceNormalz /= length;
  27778. if (computeFacetNormals) {
  27779. options.facetNormals[index].x = faceNormalx;
  27780. options.facetNormals[index].y = faceNormaly;
  27781. options.facetNormals[index].z = faceNormalz;
  27782. }
  27783. if (computeFacetPositions) {
  27784. // compute and the facet barycenter coordinates in the array facetPositions
  27785. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  27786. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  27787. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  27788. }
  27789. if (computeFacetPartitioning) {
  27790. // store the facet indexes in arrays in the main facetPartitioning array :
  27791. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  27792. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27793. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27794. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27795. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27796. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27797. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27798. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27799. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27800. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27801. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27802. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27803. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27804. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  27805. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  27806. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  27807. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  27808. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  27809. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  27810. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  27811. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  27812. // push each facet index in each block containing the vertex
  27813. options.facetPartitioning[block_idx_v1].push(index);
  27814. if (block_idx_v2 != block_idx_v1) {
  27815. options.facetPartitioning[block_idx_v2].push(index);
  27816. }
  27817. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  27818. options.facetPartitioning[block_idx_v3].push(index);
  27819. }
  27820. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  27821. options.facetPartitioning[block_idx_o].push(index);
  27822. }
  27823. }
  27824. // compute the normals anyway
  27825. normals[v1x] += faceNormalx; // accumulate all the normals per face
  27826. normals[v1y] += faceNormaly;
  27827. normals[v1z] += faceNormalz;
  27828. normals[v2x] += faceNormalx;
  27829. normals[v2y] += faceNormaly;
  27830. normals[v2z] += faceNormalz;
  27831. normals[v3x] += faceNormalx;
  27832. normals[v3y] += faceNormaly;
  27833. normals[v3z] += faceNormalz;
  27834. }
  27835. // last normalization of each normal
  27836. for (index = 0; index < normals.length / 3; index++) {
  27837. faceNormalx = normals[index * 3];
  27838. faceNormaly = normals[index * 3 + 1];
  27839. faceNormalz = normals[index * 3 + 2];
  27840. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27841. length = (length === 0) ? 1.0 : length;
  27842. faceNormalx /= length;
  27843. faceNormaly /= length;
  27844. faceNormalz /= length;
  27845. normals[index * 3] = faceNormalx;
  27846. normals[index * 3 + 1] = faceNormaly;
  27847. normals[index * 3 + 2] = faceNormalz;
  27848. }
  27849. };
  27850. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  27851. var li = indices.length;
  27852. var ln = normals.length;
  27853. var i;
  27854. var n;
  27855. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27856. switch (sideOrientation) {
  27857. case BABYLON.Mesh.FRONTSIDE:
  27858. // nothing changed
  27859. break;
  27860. case BABYLON.Mesh.BACKSIDE:
  27861. var tmp;
  27862. // indices
  27863. for (i = 0; i < li; i += 3) {
  27864. tmp = indices[i];
  27865. indices[i] = indices[i + 2];
  27866. indices[i + 2] = tmp;
  27867. }
  27868. // normals
  27869. for (n = 0; n < ln; n++) {
  27870. normals[n] = -normals[n];
  27871. }
  27872. break;
  27873. case BABYLON.Mesh.DOUBLESIDE:
  27874. // positions
  27875. var lp = positions.length;
  27876. var l = lp / 3;
  27877. for (var p = 0; p < lp; p++) {
  27878. positions[lp + p] = positions[p];
  27879. }
  27880. // indices
  27881. for (i = 0; i < li; i += 3) {
  27882. indices[i + li] = indices[i + 2] + l;
  27883. indices[i + 1 + li] = indices[i + 1] + l;
  27884. indices[i + 2 + li] = indices[i] + l;
  27885. }
  27886. // normals
  27887. for (n = 0; n < ln; n++) {
  27888. normals[ln + n] = -normals[n];
  27889. }
  27890. // uvs
  27891. var lu = uvs.length;
  27892. var u = 0;
  27893. for (u = 0; u < lu; u++) {
  27894. uvs[u + lu] = uvs[u];
  27895. }
  27896. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27897. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27898. u = 0;
  27899. for (i = 0; i < lu / 2; i++) {
  27900. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  27901. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  27902. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  27903. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  27904. u += 2;
  27905. }
  27906. break;
  27907. }
  27908. };
  27909. /**
  27910. * Creates a new VertexData from the imported parameters.
  27911. */
  27912. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  27913. var vertexData = new VertexData();
  27914. // positions
  27915. var positions = parsedVertexData.positions;
  27916. if (positions) {
  27917. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27918. }
  27919. // normals
  27920. var normals = parsedVertexData.normals;
  27921. if (normals) {
  27922. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27923. }
  27924. // tangents
  27925. var tangents = parsedVertexData.tangents;
  27926. if (tangents) {
  27927. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  27928. }
  27929. // uvs
  27930. var uvs = parsedVertexData.uvs;
  27931. if (uvs) {
  27932. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27933. }
  27934. // uv2s
  27935. var uv2s = parsedVertexData.uv2s;
  27936. if (uv2s) {
  27937. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27938. }
  27939. // uv3s
  27940. var uv3s = parsedVertexData.uv3s;
  27941. if (uv3s) {
  27942. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27943. }
  27944. // uv4s
  27945. var uv4s = parsedVertexData.uv4s;
  27946. if (uv4s) {
  27947. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27948. }
  27949. // uv5s
  27950. var uv5s = parsedVertexData.uv5s;
  27951. if (uv5s) {
  27952. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27953. }
  27954. // uv6s
  27955. var uv6s = parsedVertexData.uv6s;
  27956. if (uv6s) {
  27957. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27958. }
  27959. // colors
  27960. var colors = parsedVertexData.colors;
  27961. if (colors) {
  27962. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27963. }
  27964. // matricesIndices
  27965. var matricesIndices = parsedVertexData.matricesIndices;
  27966. if (matricesIndices) {
  27967. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27968. }
  27969. // matricesWeights
  27970. var matricesWeights = parsedVertexData.matricesWeights;
  27971. if (matricesWeights) {
  27972. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27973. }
  27974. // indices
  27975. var indices = parsedVertexData.indices;
  27976. if (indices) {
  27977. vertexData.indices = indices;
  27978. }
  27979. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  27980. };
  27981. return VertexData;
  27982. }());
  27983. BABYLON.VertexData = VertexData;
  27984. })(BABYLON || (BABYLON = {}));
  27985. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  27986. var BABYLON;
  27987. (function (BABYLON) {
  27988. var Geometry = (function () {
  27989. function Geometry(id, scene, vertexData, updatable, mesh) {
  27990. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27991. this._totalVertices = 0;
  27992. this._isDisposed = false;
  27993. this.id = id;
  27994. this._engine = scene.getEngine();
  27995. this._meshes = [];
  27996. this._scene = scene;
  27997. //Init vertex buffer cache
  27998. this._vertexBuffers = {};
  27999. this._indices = [];
  28000. this._updatable = updatable;
  28001. // vertexData
  28002. if (vertexData) {
  28003. this.setAllVerticesData(vertexData, updatable);
  28004. }
  28005. else {
  28006. this._totalVertices = 0;
  28007. this._indices = [];
  28008. }
  28009. if (this._engine.getCaps().vertexArrayObject) {
  28010. this._vertexArrayObjects = {};
  28011. }
  28012. // applyToMesh
  28013. if (mesh) {
  28014. if (mesh.getClassName() === "LinesMesh") {
  28015. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28016. this.updateExtend();
  28017. }
  28018. this.applyToMesh(mesh);
  28019. mesh.computeWorldMatrix(true);
  28020. }
  28021. }
  28022. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28023. /**
  28024. * 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
  28025. * @returns The Bias Vector
  28026. */
  28027. get: function () {
  28028. return this._boundingBias;
  28029. },
  28030. set: function (value) {
  28031. if (this._boundingBias && this._boundingBias.equals(value)) {
  28032. return;
  28033. }
  28034. this._boundingBias = value.clone();
  28035. this.updateBoundingInfo(true, null);
  28036. },
  28037. enumerable: true,
  28038. configurable: true
  28039. });
  28040. Object.defineProperty(Geometry.prototype, "extend", {
  28041. get: function () {
  28042. return this._extend;
  28043. },
  28044. enumerable: true,
  28045. configurable: true
  28046. });
  28047. Geometry.prototype.getScene = function () {
  28048. return this._scene;
  28049. };
  28050. Geometry.prototype.getEngine = function () {
  28051. return this._engine;
  28052. };
  28053. Geometry.prototype.isReady = function () {
  28054. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28055. };
  28056. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28057. get: function () {
  28058. for (var index = 0; index < this._meshes.length; index++) {
  28059. if (!this._meshes[index].doNotSerialize) {
  28060. return false;
  28061. }
  28062. }
  28063. return true;
  28064. },
  28065. enumerable: true,
  28066. configurable: true
  28067. });
  28068. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28069. vertexData.applyToGeometry(this, updatable);
  28070. this.notifyUpdate();
  28071. };
  28072. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28073. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28074. this.setVerticesBuffer(buffer);
  28075. };
  28076. Geometry.prototype.removeVerticesData = function (kind) {
  28077. if (this._vertexBuffers[kind]) {
  28078. this._vertexBuffers[kind].dispose();
  28079. delete this._vertexBuffers[kind];
  28080. }
  28081. };
  28082. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28083. var kind = buffer.getKind();
  28084. if (this._vertexBuffers[kind]) {
  28085. this._vertexBuffers[kind].dispose();
  28086. }
  28087. this._vertexBuffers[kind] = buffer;
  28088. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28089. var data = buffer.getData();
  28090. var stride = buffer.getStrideSize();
  28091. this._totalVertices = data.length / stride;
  28092. this.updateExtend(data, stride);
  28093. this._resetPointsArrayCache();
  28094. var meshes = this._meshes;
  28095. var numOfMeshes = meshes.length;
  28096. for (var index = 0; index < numOfMeshes; index++) {
  28097. var mesh = meshes[index];
  28098. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28099. mesh._createGlobalSubMesh(false);
  28100. mesh.computeWorldMatrix(true);
  28101. }
  28102. }
  28103. this.notifyUpdate(kind);
  28104. if (this._vertexArrayObjects) {
  28105. this._disposeVertexArrayObjects();
  28106. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28107. }
  28108. };
  28109. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28110. var vertexBuffer = this.getVertexBuffer(kind);
  28111. if (!vertexBuffer) {
  28112. return;
  28113. }
  28114. vertexBuffer.updateDirectly(data, offset);
  28115. this.notifyUpdate(kind);
  28116. };
  28117. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28118. var vertexBuffer = this.getVertexBuffer(kind);
  28119. if (!vertexBuffer) {
  28120. return;
  28121. }
  28122. vertexBuffer.update(data);
  28123. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28124. var stride = vertexBuffer.getStrideSize();
  28125. this._totalVertices = data.length / stride;
  28126. this.updateBoundingInfo(updateExtends, data);
  28127. }
  28128. this.notifyUpdate(kind);
  28129. };
  28130. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28131. if (updateExtends) {
  28132. this.updateExtend(data);
  28133. }
  28134. var meshes = this._meshes;
  28135. var numOfMeshes = meshes.length;
  28136. this._resetPointsArrayCache();
  28137. for (var index = 0; index < numOfMeshes; index++) {
  28138. var mesh = meshes[index];
  28139. if (updateExtends) {
  28140. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28141. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28142. var subMesh = mesh.subMeshes[subIndex];
  28143. subMesh.refreshBoundingInfo();
  28144. }
  28145. }
  28146. }
  28147. };
  28148. Geometry.prototype._bind = function (effect, indexToBind) {
  28149. if (indexToBind === void 0) { indexToBind = undefined; }
  28150. if (indexToBind === undefined) {
  28151. indexToBind = this._indexBuffer;
  28152. }
  28153. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  28154. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  28155. return;
  28156. }
  28157. // Using VAO
  28158. if (!this._vertexArrayObjects[effect.key]) {
  28159. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  28160. }
  28161. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  28162. };
  28163. Geometry.prototype.getTotalVertices = function () {
  28164. if (!this.isReady()) {
  28165. return 0;
  28166. }
  28167. return this._totalVertices;
  28168. };
  28169. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28170. var vertexBuffer = this.getVertexBuffer(kind);
  28171. if (!vertexBuffer) {
  28172. return null;
  28173. }
  28174. var orig = vertexBuffer.getData();
  28175. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  28176. return orig;
  28177. }
  28178. else {
  28179. var len = orig.length;
  28180. var copy = [];
  28181. for (var i = 0; i < len; i++) {
  28182. copy.push(orig[i]);
  28183. }
  28184. return copy;
  28185. }
  28186. };
  28187. Geometry.prototype.getVertexBuffer = function (kind) {
  28188. if (!this.isReady()) {
  28189. return null;
  28190. }
  28191. return this._vertexBuffers[kind];
  28192. };
  28193. Geometry.prototype.getVertexBuffers = function () {
  28194. if (!this.isReady()) {
  28195. return null;
  28196. }
  28197. return this._vertexBuffers;
  28198. };
  28199. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28200. if (!this._vertexBuffers) {
  28201. if (this._delayInfo) {
  28202. return this._delayInfo.indexOf(kind) !== -1;
  28203. }
  28204. return false;
  28205. }
  28206. return this._vertexBuffers[kind] !== undefined;
  28207. };
  28208. Geometry.prototype.getVerticesDataKinds = function () {
  28209. var result = [];
  28210. var kind;
  28211. if (!this._vertexBuffers && this._delayInfo) {
  28212. for (kind in this._delayInfo) {
  28213. result.push(kind);
  28214. }
  28215. }
  28216. else {
  28217. for (kind in this._vertexBuffers) {
  28218. result.push(kind);
  28219. }
  28220. }
  28221. return result;
  28222. };
  28223. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28224. if (this._indexBuffer) {
  28225. this._engine._releaseBuffer(this._indexBuffer);
  28226. }
  28227. this._disposeVertexArrayObjects();
  28228. this._indices = indices;
  28229. if (this._meshes.length !== 0 && this._indices) {
  28230. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28231. }
  28232. if (totalVertices !== undefined) {
  28233. this._totalVertices = totalVertices;
  28234. }
  28235. var meshes = this._meshes;
  28236. var numOfMeshes = meshes.length;
  28237. for (var index = 0; index < numOfMeshes; index++) {
  28238. meshes[index]._createGlobalSubMesh(true);
  28239. }
  28240. this.notifyUpdate();
  28241. };
  28242. Geometry.prototype.getTotalIndices = function () {
  28243. if (!this.isReady()) {
  28244. return 0;
  28245. }
  28246. return this._indices.length;
  28247. };
  28248. Geometry.prototype.getIndices = function (copyWhenShared) {
  28249. if (!this.isReady()) {
  28250. return null;
  28251. }
  28252. var orig = this._indices;
  28253. if (!copyWhenShared || this._meshes.length === 1) {
  28254. return orig;
  28255. }
  28256. else {
  28257. var len = orig.length;
  28258. var copy = [];
  28259. for (var i = 0; i < len; i++) {
  28260. copy.push(orig[i]);
  28261. }
  28262. return copy;
  28263. }
  28264. };
  28265. Geometry.prototype.getIndexBuffer = function () {
  28266. if (!this.isReady()) {
  28267. return null;
  28268. }
  28269. return this._indexBuffer;
  28270. };
  28271. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  28272. if (!effect || !this._vertexArrayObjects) {
  28273. return;
  28274. }
  28275. if (this._vertexArrayObjects[effect.key]) {
  28276. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  28277. delete this._vertexArrayObjects[effect.key];
  28278. }
  28279. };
  28280. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28281. var meshes = this._meshes;
  28282. var index = meshes.indexOf(mesh);
  28283. if (index === -1) {
  28284. return;
  28285. }
  28286. meshes.splice(index, 1);
  28287. mesh._geometry = null;
  28288. if (meshes.length === 0 && shouldDispose) {
  28289. this.dispose();
  28290. }
  28291. };
  28292. Geometry.prototype.applyToMesh = function (mesh) {
  28293. if (mesh._geometry === this) {
  28294. return;
  28295. }
  28296. var previousGeometry = mesh._geometry;
  28297. if (previousGeometry) {
  28298. previousGeometry.releaseForMesh(mesh);
  28299. }
  28300. var meshes = this._meshes;
  28301. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28302. mesh._geometry = this;
  28303. this._scene.pushGeometry(this);
  28304. meshes.push(mesh);
  28305. if (this.isReady()) {
  28306. this._applyToMesh(mesh);
  28307. }
  28308. else {
  28309. mesh._boundingInfo = this._boundingInfo;
  28310. }
  28311. };
  28312. Geometry.prototype.updateExtend = function (data, stride) {
  28313. if (data === void 0) { data = null; }
  28314. if (!data) {
  28315. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  28316. }
  28317. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  28318. };
  28319. Geometry.prototype._applyToMesh = function (mesh) {
  28320. var numOfMeshes = this._meshes.length;
  28321. // vertexBuffers
  28322. for (var kind in this._vertexBuffers) {
  28323. if (numOfMeshes === 1) {
  28324. this._vertexBuffers[kind].create();
  28325. }
  28326. var buffer = this._vertexBuffers[kind].getBuffer();
  28327. if (buffer)
  28328. buffer.references = numOfMeshes;
  28329. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28330. if (!this._extend) {
  28331. this.updateExtend(this._vertexBuffers[kind].getData());
  28332. }
  28333. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28334. mesh._createGlobalSubMesh(false);
  28335. //bounding info was just created again, world matrix should be applied again.
  28336. mesh._updateBoundingInfo();
  28337. }
  28338. }
  28339. // indexBuffer
  28340. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  28341. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28342. }
  28343. if (this._indexBuffer) {
  28344. this._indexBuffer.references = numOfMeshes;
  28345. }
  28346. };
  28347. Geometry.prototype.notifyUpdate = function (kind) {
  28348. if (this.onGeometryUpdated) {
  28349. this.onGeometryUpdated(this, kind);
  28350. }
  28351. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  28352. var mesh = _a[_i];
  28353. mesh._markSubMeshesAsAttributesDirty();
  28354. }
  28355. };
  28356. Geometry.prototype.load = function (scene, onLoaded) {
  28357. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28358. return;
  28359. }
  28360. if (this.isReady()) {
  28361. if (onLoaded) {
  28362. onLoaded();
  28363. }
  28364. return;
  28365. }
  28366. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28367. this._queueLoad(scene, onLoaded);
  28368. };
  28369. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  28370. var _this = this;
  28371. scene._addPendingData(this);
  28372. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28373. _this._delayLoadingFunction(JSON.parse(data), _this);
  28374. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28375. _this._delayInfo = [];
  28376. scene._removePendingData(_this);
  28377. var meshes = _this._meshes;
  28378. var numOfMeshes = meshes.length;
  28379. for (var index = 0; index < numOfMeshes; index++) {
  28380. _this._applyToMesh(meshes[index]);
  28381. }
  28382. if (onLoaded) {
  28383. onLoaded();
  28384. }
  28385. }, function () { }, scene.database);
  28386. };
  28387. /**
  28388. * Invert the geometry to move from a right handed system to a left handed one.
  28389. */
  28390. Geometry.prototype.toLeftHanded = function () {
  28391. // Flip faces
  28392. var tIndices = this.getIndices(false);
  28393. if (tIndices != null && tIndices.length > 0) {
  28394. for (var i = 0; i < tIndices.length; i += 3) {
  28395. var tTemp = tIndices[i + 0];
  28396. tIndices[i + 0] = tIndices[i + 2];
  28397. tIndices[i + 2] = tTemp;
  28398. }
  28399. this.setIndices(tIndices);
  28400. }
  28401. // Negate position.z
  28402. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  28403. if (tPositions != null && tPositions.length > 0) {
  28404. for (var i = 0; i < tPositions.length; i += 3) {
  28405. tPositions[i + 2] = -tPositions[i + 2];
  28406. }
  28407. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  28408. }
  28409. // Negate normal.z
  28410. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  28411. if (tNormals != null && tNormals.length > 0) {
  28412. for (var i = 0; i < tNormals.length; i += 3) {
  28413. tNormals[i + 2] = -tNormals[i + 2];
  28414. }
  28415. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  28416. }
  28417. };
  28418. // Cache
  28419. Geometry.prototype._resetPointsArrayCache = function () {
  28420. this._positions = null;
  28421. };
  28422. Geometry.prototype._generatePointsArray = function () {
  28423. if (this._positions)
  28424. return true;
  28425. this._positions = [];
  28426. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28427. if (!data) {
  28428. return false;
  28429. }
  28430. for (var index = 0; index < data.length; index += 3) {
  28431. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  28432. }
  28433. return true;
  28434. };
  28435. Geometry.prototype.isDisposed = function () {
  28436. return this._isDisposed;
  28437. };
  28438. Geometry.prototype._disposeVertexArrayObjects = function () {
  28439. if (this._vertexArrayObjects) {
  28440. for (var kind in this._vertexArrayObjects) {
  28441. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  28442. }
  28443. this._vertexArrayObjects = {};
  28444. }
  28445. };
  28446. Geometry.prototype.dispose = function () {
  28447. var meshes = this._meshes;
  28448. var numOfMeshes = meshes.length;
  28449. var index;
  28450. for (index = 0; index < numOfMeshes; index++) {
  28451. this.releaseForMesh(meshes[index]);
  28452. }
  28453. this._meshes = [];
  28454. this._disposeVertexArrayObjects();
  28455. for (var kind in this._vertexBuffers) {
  28456. this._vertexBuffers[kind].dispose();
  28457. }
  28458. this._vertexBuffers = {};
  28459. this._totalVertices = 0;
  28460. if (this._indexBuffer) {
  28461. this._engine._releaseBuffer(this._indexBuffer);
  28462. }
  28463. this._indexBuffer = null;
  28464. this._indices = [];
  28465. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28466. this.delayLoadingFile = null;
  28467. this._delayLoadingFunction = null;
  28468. this._delayInfo = [];
  28469. this._boundingInfo = null;
  28470. this._scene.removeGeometry(this);
  28471. this._isDisposed = true;
  28472. };
  28473. Geometry.prototype.copy = function (id) {
  28474. var vertexData = new BABYLON.VertexData();
  28475. vertexData.indices = [];
  28476. var indices = this.getIndices();
  28477. for (var index = 0; index < indices.length; index++) {
  28478. vertexData.indices.push(indices[index]);
  28479. }
  28480. var updatable = false;
  28481. var stopChecking = false;
  28482. var kind;
  28483. for (kind in this._vertexBuffers) {
  28484. // using slice() to make a copy of the array and not just reference it
  28485. var data = this.getVerticesData(kind);
  28486. if (data instanceof Float32Array) {
  28487. vertexData.set(new Float32Array(data), kind);
  28488. }
  28489. else {
  28490. vertexData.set(data.slice(0), kind);
  28491. }
  28492. if (!stopChecking) {
  28493. updatable = this.getVertexBuffer(kind).isUpdatable();
  28494. stopChecking = !updatable;
  28495. }
  28496. }
  28497. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28498. geometry.delayLoadState = this.delayLoadState;
  28499. geometry.delayLoadingFile = this.delayLoadingFile;
  28500. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28501. for (kind in this._delayInfo) {
  28502. geometry._delayInfo = geometry._delayInfo || [];
  28503. geometry._delayInfo.push(kind);
  28504. }
  28505. // Bounding info
  28506. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28507. return geometry;
  28508. };
  28509. Geometry.prototype.serialize = function () {
  28510. var serializationObject = {};
  28511. serializationObject.id = this.id;
  28512. serializationObject.updatable = this._updatable;
  28513. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28514. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28515. }
  28516. return serializationObject;
  28517. };
  28518. Geometry.prototype.toNumberArray = function (origin) {
  28519. if (Array.isArray(origin)) {
  28520. return origin;
  28521. }
  28522. else {
  28523. return Array.prototype.slice.call(origin);
  28524. }
  28525. };
  28526. Geometry.prototype.serializeVerticeData = function () {
  28527. var serializationObject = this.serialize();
  28528. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28529. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  28530. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  28531. serializationObject.positions._updatable = true;
  28532. }
  28533. }
  28534. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28535. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  28536. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  28537. serializationObject.normals._updatable = true;
  28538. }
  28539. }
  28540. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28541. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  28542. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  28543. serializationObject.uvs._updatable = true;
  28544. }
  28545. }
  28546. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28547. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  28548. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  28549. serializationObject.uv2s._updatable = true;
  28550. }
  28551. }
  28552. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28553. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  28554. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  28555. serializationObject.uv3s._updatable = true;
  28556. }
  28557. }
  28558. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28559. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  28560. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  28561. serializationObject.uv4s._updatable = true;
  28562. }
  28563. }
  28564. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28565. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  28566. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  28567. serializationObject.uv5s._updatable = true;
  28568. }
  28569. }
  28570. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28571. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  28572. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  28573. serializationObject.uv6s._updatable = true;
  28574. }
  28575. }
  28576. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28577. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  28578. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  28579. serializationObject.colors._updatable = true;
  28580. }
  28581. }
  28582. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28583. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  28584. serializationObject.matricesIndices._isExpanded = true;
  28585. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  28586. serializationObject.matricesIndices._updatable = true;
  28587. }
  28588. }
  28589. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28590. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  28591. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  28592. serializationObject.matricesWeights._updatable = true;
  28593. }
  28594. }
  28595. serializationObject.indices = this.toNumberArray(this.getIndices());
  28596. return serializationObject;
  28597. };
  28598. // Statics
  28599. Geometry.ExtractFromMesh = function (mesh, id) {
  28600. var geometry = mesh._geometry;
  28601. if (!geometry) {
  28602. return null;
  28603. }
  28604. return geometry.copy(id);
  28605. };
  28606. /**
  28607. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  28608. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28609. * Be aware Math.random() could cause collisions, but:
  28610. * "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"
  28611. */
  28612. Geometry.RandomId = function () {
  28613. return BABYLON.Tools.RandomId();
  28614. };
  28615. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  28616. var scene = mesh.getScene();
  28617. // Geometry
  28618. var geometryId = parsedGeometry.geometryId;
  28619. if (geometryId) {
  28620. var geometry = scene.getGeometryByID(geometryId);
  28621. if (geometry) {
  28622. geometry.applyToMesh(mesh);
  28623. }
  28624. }
  28625. else if (parsedGeometry instanceof ArrayBuffer) {
  28626. var binaryInfo = mesh._binaryInfo;
  28627. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  28628. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  28629. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  28630. }
  28631. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  28632. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  28633. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  28634. }
  28635. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  28636. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  28637. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  28638. }
  28639. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  28640. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  28641. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  28642. }
  28643. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  28644. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  28645. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  28646. }
  28647. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  28648. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  28649. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  28650. }
  28651. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  28652. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  28653. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  28654. }
  28655. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  28656. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  28657. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  28658. }
  28659. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  28660. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  28661. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  28662. }
  28663. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  28664. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  28665. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  28666. }
  28667. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  28668. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  28669. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  28670. }
  28671. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  28672. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  28673. mesh.setIndices(indicesData);
  28674. }
  28675. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  28676. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  28677. mesh.subMeshes = [];
  28678. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  28679. var materialIndex = subMeshesData[(i * 5) + 0];
  28680. var verticesStart = subMeshesData[(i * 5) + 1];
  28681. var verticesCount = subMeshesData[(i * 5) + 2];
  28682. var indexStart = subMeshesData[(i * 5) + 3];
  28683. var indexCount = subMeshesData[(i * 5) + 4];
  28684. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  28685. }
  28686. }
  28687. }
  28688. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  28689. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  28690. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  28691. if (parsedGeometry.uvs) {
  28692. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  28693. }
  28694. if (parsedGeometry.uvs2) {
  28695. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  28696. }
  28697. if (parsedGeometry.uvs3) {
  28698. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  28699. }
  28700. if (parsedGeometry.uvs4) {
  28701. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  28702. }
  28703. if (parsedGeometry.uvs5) {
  28704. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  28705. }
  28706. if (parsedGeometry.uvs6) {
  28707. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  28708. }
  28709. if (parsedGeometry.colors) {
  28710. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  28711. }
  28712. if (parsedGeometry.matricesIndices) {
  28713. if (!parsedGeometry.matricesIndices._isExpanded) {
  28714. var floatIndices = [];
  28715. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  28716. var matricesIndex = parsedGeometry.matricesIndices[i];
  28717. floatIndices.push(matricesIndex & 0x000000FF);
  28718. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28719. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28720. floatIndices.push(matricesIndex >> 24);
  28721. }
  28722. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  28723. }
  28724. else {
  28725. delete parsedGeometry.matricesIndices._isExpanded;
  28726. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  28727. }
  28728. }
  28729. if (parsedGeometry.matricesIndicesExtra) {
  28730. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  28731. var floatIndices = [];
  28732. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  28733. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  28734. floatIndices.push(matricesIndex & 0x000000FF);
  28735. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28736. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28737. floatIndices.push(matricesIndex >> 24);
  28738. }
  28739. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  28740. }
  28741. else {
  28742. delete parsedGeometry.matricesIndices._isExpanded;
  28743. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  28744. }
  28745. }
  28746. if (parsedGeometry.matricesWeights) {
  28747. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  28748. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  28749. }
  28750. if (parsedGeometry.matricesWeightsExtra) {
  28751. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  28752. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  28753. }
  28754. mesh.setIndices(parsedGeometry.indices);
  28755. }
  28756. // SubMeshes
  28757. if (parsedGeometry.subMeshes) {
  28758. mesh.subMeshes = [];
  28759. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  28760. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  28761. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  28762. }
  28763. }
  28764. // Flat shading
  28765. if (mesh._shouldGenerateFlatShading) {
  28766. mesh.convertToFlatShadedMesh();
  28767. delete mesh._shouldGenerateFlatShading;
  28768. }
  28769. // Update
  28770. mesh.computeWorldMatrix(true);
  28771. // Octree
  28772. if (scene['_selectionOctree']) {
  28773. scene['_selectionOctree'].addMesh(mesh);
  28774. }
  28775. };
  28776. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  28777. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  28778. return;
  28779. }
  28780. var size = matricesWeights.length;
  28781. for (var i = 0; i < size; i += influencers) {
  28782. var weight = 0;
  28783. var biggerIndex = i;
  28784. var biggerWeight = 0;
  28785. for (var j = 0; j < influencers - 1; j++) {
  28786. weight += matricesWeights[i + j];
  28787. if (matricesWeights[i + j] > biggerWeight) {
  28788. biggerWeight = matricesWeights[i + j];
  28789. biggerIndex = i + j;
  28790. }
  28791. }
  28792. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  28793. }
  28794. };
  28795. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  28796. if (scene.getGeometryByID(parsedVertexData.id)) {
  28797. return null; // null since geometry could be something else than a box...
  28798. }
  28799. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  28800. if (BABYLON.Tags) {
  28801. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  28802. }
  28803. if (parsedVertexData.delayLoadingFile) {
  28804. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28805. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  28806. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  28807. geometry._delayInfo = [];
  28808. if (parsedVertexData.hasUVs) {
  28809. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28810. }
  28811. if (parsedVertexData.hasUVs2) {
  28812. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28813. }
  28814. if (parsedVertexData.hasUVs3) {
  28815. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28816. }
  28817. if (parsedVertexData.hasUVs4) {
  28818. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28819. }
  28820. if (parsedVertexData.hasUVs5) {
  28821. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28822. }
  28823. if (parsedVertexData.hasUVs6) {
  28824. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28825. }
  28826. if (parsedVertexData.hasColors) {
  28827. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28828. }
  28829. if (parsedVertexData.hasMatricesIndices) {
  28830. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28831. }
  28832. if (parsedVertexData.hasMatricesWeights) {
  28833. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28834. }
  28835. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  28836. }
  28837. else {
  28838. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  28839. }
  28840. scene.pushGeometry(geometry, true);
  28841. return geometry;
  28842. };
  28843. return Geometry;
  28844. }());
  28845. BABYLON.Geometry = Geometry;
  28846. /////// Primitives //////////////////////////////////////////////
  28847. (function (Geometry) {
  28848. var Primitives;
  28849. (function (Primitives) {
  28850. /// Abstract class
  28851. var _Primitive = (function (_super) {
  28852. __extends(_Primitive, _super);
  28853. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  28854. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  28855. _this._canBeRegenerated = _canBeRegenerated;
  28856. _this._beingRegenerated = true;
  28857. _this.regenerate();
  28858. _this._beingRegenerated = false;
  28859. return _this;
  28860. }
  28861. _Primitive.prototype.canBeRegenerated = function () {
  28862. return this._canBeRegenerated;
  28863. };
  28864. _Primitive.prototype.regenerate = function () {
  28865. if (!this._canBeRegenerated) {
  28866. return;
  28867. }
  28868. this._beingRegenerated = true;
  28869. this.setAllVerticesData(this._regenerateVertexData(), false);
  28870. this._beingRegenerated = false;
  28871. };
  28872. _Primitive.prototype.asNewGeometry = function (id) {
  28873. return _super.prototype.copy.call(this, id);
  28874. };
  28875. // overrides
  28876. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28877. if (!this._beingRegenerated) {
  28878. return;
  28879. }
  28880. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28881. };
  28882. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28883. if (!this._beingRegenerated) {
  28884. return;
  28885. }
  28886. _super.prototype.setVerticesData.call(this, kind, data, false);
  28887. };
  28888. // to override
  28889. // protected
  28890. _Primitive.prototype._regenerateVertexData = function () {
  28891. throw new Error("Abstract method");
  28892. };
  28893. _Primitive.prototype.copy = function (id) {
  28894. throw new Error("Must be overriden in sub-classes.");
  28895. };
  28896. _Primitive.prototype.serialize = function () {
  28897. var serializationObject = _super.prototype.serialize.call(this);
  28898. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28899. return serializationObject;
  28900. };
  28901. return _Primitive;
  28902. }(Geometry));
  28903. Primitives._Primitive = _Primitive;
  28904. var Ribbon = (function (_super) {
  28905. __extends(Ribbon, _super);
  28906. // Members
  28907. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28908. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28909. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28910. _this.pathArray = pathArray;
  28911. _this.closeArray = closeArray;
  28912. _this.closePath = closePath;
  28913. _this.offset = offset;
  28914. _this.side = side;
  28915. return _this;
  28916. }
  28917. Ribbon.prototype._regenerateVertexData = function () {
  28918. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28919. };
  28920. Ribbon.prototype.copy = function (id) {
  28921. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28922. };
  28923. return Ribbon;
  28924. }(_Primitive));
  28925. Primitives.Ribbon = Ribbon;
  28926. var Box = (function (_super) {
  28927. __extends(Box, _super);
  28928. // Members
  28929. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28930. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28931. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28932. _this.size = size;
  28933. _this.side = side;
  28934. return _this;
  28935. }
  28936. Box.prototype._regenerateVertexData = function () {
  28937. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28938. };
  28939. Box.prototype.copy = function (id) {
  28940. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28941. };
  28942. Box.prototype.serialize = function () {
  28943. var serializationObject = _super.prototype.serialize.call(this);
  28944. serializationObject.size = this.size;
  28945. return serializationObject;
  28946. };
  28947. Box.Parse = function (parsedBox, scene) {
  28948. if (scene.getGeometryByID(parsedBox.id)) {
  28949. return null; // null since geometry could be something else than a box...
  28950. }
  28951. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28952. if (BABYLON.Tags) {
  28953. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28954. }
  28955. scene.pushGeometry(box, true);
  28956. return box;
  28957. };
  28958. return Box;
  28959. }(_Primitive));
  28960. Primitives.Box = Box;
  28961. var Sphere = (function (_super) {
  28962. __extends(Sphere, _super);
  28963. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28964. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28965. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28966. _this.segments = segments;
  28967. _this.diameter = diameter;
  28968. _this.side = side;
  28969. return _this;
  28970. }
  28971. Sphere.prototype._regenerateVertexData = function () {
  28972. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28973. };
  28974. Sphere.prototype.copy = function (id) {
  28975. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28976. };
  28977. Sphere.prototype.serialize = function () {
  28978. var serializationObject = _super.prototype.serialize.call(this);
  28979. serializationObject.segments = this.segments;
  28980. serializationObject.diameter = this.diameter;
  28981. return serializationObject;
  28982. };
  28983. Sphere.Parse = function (parsedSphere, scene) {
  28984. if (scene.getGeometryByID(parsedSphere.id)) {
  28985. return null; // null since geometry could be something else than a sphere...
  28986. }
  28987. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28988. if (BABYLON.Tags) {
  28989. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28990. }
  28991. scene.pushGeometry(sphere, true);
  28992. return sphere;
  28993. };
  28994. return Sphere;
  28995. }(_Primitive));
  28996. Primitives.Sphere = Sphere;
  28997. var Disc = (function (_super) {
  28998. __extends(Disc, _super);
  28999. // Members
  29000. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29001. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29002. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29003. _this.radius = radius;
  29004. _this.tessellation = tessellation;
  29005. _this.side = side;
  29006. return _this;
  29007. }
  29008. Disc.prototype._regenerateVertexData = function () {
  29009. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29010. };
  29011. Disc.prototype.copy = function (id) {
  29012. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29013. };
  29014. return Disc;
  29015. }(_Primitive));
  29016. Primitives.Disc = Disc;
  29017. var Cylinder = (function (_super) {
  29018. __extends(Cylinder, _super);
  29019. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29020. if (subdivisions === void 0) { subdivisions = 1; }
  29021. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29022. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29023. _this.height = height;
  29024. _this.diameterTop = diameterTop;
  29025. _this.diameterBottom = diameterBottom;
  29026. _this.tessellation = tessellation;
  29027. _this.subdivisions = subdivisions;
  29028. _this.side = side;
  29029. return _this;
  29030. }
  29031. Cylinder.prototype._regenerateVertexData = function () {
  29032. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29033. };
  29034. Cylinder.prototype.copy = function (id) {
  29035. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29036. };
  29037. Cylinder.prototype.serialize = function () {
  29038. var serializationObject = _super.prototype.serialize.call(this);
  29039. serializationObject.height = this.height;
  29040. serializationObject.diameterTop = this.diameterTop;
  29041. serializationObject.diameterBottom = this.diameterBottom;
  29042. serializationObject.tessellation = this.tessellation;
  29043. return serializationObject;
  29044. };
  29045. Cylinder.Parse = function (parsedCylinder, scene) {
  29046. if (scene.getGeometryByID(parsedCylinder.id)) {
  29047. return null; // null since geometry could be something else than a cylinder...
  29048. }
  29049. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29050. if (BABYLON.Tags) {
  29051. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29052. }
  29053. scene.pushGeometry(cylinder, true);
  29054. return cylinder;
  29055. };
  29056. return Cylinder;
  29057. }(_Primitive));
  29058. Primitives.Cylinder = Cylinder;
  29059. var Torus = (function (_super) {
  29060. __extends(Torus, _super);
  29061. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29062. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29063. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29064. _this.diameter = diameter;
  29065. _this.thickness = thickness;
  29066. _this.tessellation = tessellation;
  29067. _this.side = side;
  29068. return _this;
  29069. }
  29070. Torus.prototype._regenerateVertexData = function () {
  29071. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29072. };
  29073. Torus.prototype.copy = function (id) {
  29074. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29075. };
  29076. Torus.prototype.serialize = function () {
  29077. var serializationObject = _super.prototype.serialize.call(this);
  29078. serializationObject.diameter = this.diameter;
  29079. serializationObject.thickness = this.thickness;
  29080. serializationObject.tessellation = this.tessellation;
  29081. return serializationObject;
  29082. };
  29083. Torus.Parse = function (parsedTorus, scene) {
  29084. if (scene.getGeometryByID(parsedTorus.id)) {
  29085. return null; // null since geometry could be something else than a torus...
  29086. }
  29087. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29088. if (BABYLON.Tags) {
  29089. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29090. }
  29091. scene.pushGeometry(torus, true);
  29092. return torus;
  29093. };
  29094. return Torus;
  29095. }(_Primitive));
  29096. Primitives.Torus = Torus;
  29097. var Ground = (function (_super) {
  29098. __extends(Ground, _super);
  29099. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29100. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29101. _this.width = width;
  29102. _this.height = height;
  29103. _this.subdivisions = subdivisions;
  29104. return _this;
  29105. }
  29106. Ground.prototype._regenerateVertexData = function () {
  29107. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29108. };
  29109. Ground.prototype.copy = function (id) {
  29110. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29111. };
  29112. Ground.prototype.serialize = function () {
  29113. var serializationObject = _super.prototype.serialize.call(this);
  29114. serializationObject.width = this.width;
  29115. serializationObject.height = this.height;
  29116. serializationObject.subdivisions = this.subdivisions;
  29117. return serializationObject;
  29118. };
  29119. Ground.Parse = function (parsedGround, scene) {
  29120. if (scene.getGeometryByID(parsedGround.id)) {
  29121. return null; // null since geometry could be something else than a ground...
  29122. }
  29123. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29124. if (BABYLON.Tags) {
  29125. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29126. }
  29127. scene.pushGeometry(ground, true);
  29128. return ground;
  29129. };
  29130. return Ground;
  29131. }(_Primitive));
  29132. Primitives.Ground = Ground;
  29133. var TiledGround = (function (_super) {
  29134. __extends(TiledGround, _super);
  29135. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29136. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29137. _this.xmin = xmin;
  29138. _this.zmin = zmin;
  29139. _this.xmax = xmax;
  29140. _this.zmax = zmax;
  29141. _this.subdivisions = subdivisions;
  29142. _this.precision = precision;
  29143. return _this;
  29144. }
  29145. TiledGround.prototype._regenerateVertexData = function () {
  29146. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29147. };
  29148. TiledGround.prototype.copy = function (id) {
  29149. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29150. };
  29151. return TiledGround;
  29152. }(_Primitive));
  29153. Primitives.TiledGround = TiledGround;
  29154. var Plane = (function (_super) {
  29155. __extends(Plane, _super);
  29156. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29157. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29158. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29159. _this.size = size;
  29160. _this.side = side;
  29161. return _this;
  29162. }
  29163. Plane.prototype._regenerateVertexData = function () {
  29164. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29165. };
  29166. Plane.prototype.copy = function (id) {
  29167. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29168. };
  29169. Plane.prototype.serialize = function () {
  29170. var serializationObject = _super.prototype.serialize.call(this);
  29171. serializationObject.size = this.size;
  29172. return serializationObject;
  29173. };
  29174. Plane.Parse = function (parsedPlane, scene) {
  29175. if (scene.getGeometryByID(parsedPlane.id)) {
  29176. return null; // null since geometry could be something else than a ground...
  29177. }
  29178. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  29179. if (BABYLON.Tags) {
  29180. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  29181. }
  29182. scene.pushGeometry(plane, true);
  29183. return plane;
  29184. };
  29185. return Plane;
  29186. }(_Primitive));
  29187. Primitives.Plane = Plane;
  29188. var TorusKnot = (function (_super) {
  29189. __extends(TorusKnot, _super);
  29190. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29191. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29192. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29193. _this.radius = radius;
  29194. _this.tube = tube;
  29195. _this.radialSegments = radialSegments;
  29196. _this.tubularSegments = tubularSegments;
  29197. _this.p = p;
  29198. _this.q = q;
  29199. _this.side = side;
  29200. return _this;
  29201. }
  29202. TorusKnot.prototype._regenerateVertexData = function () {
  29203. 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 });
  29204. };
  29205. TorusKnot.prototype.copy = function (id) {
  29206. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29207. };
  29208. TorusKnot.prototype.serialize = function () {
  29209. var serializationObject = _super.prototype.serialize.call(this);
  29210. serializationObject.radius = this.radius;
  29211. serializationObject.tube = this.tube;
  29212. serializationObject.radialSegments = this.radialSegments;
  29213. serializationObject.tubularSegments = this.tubularSegments;
  29214. serializationObject.p = this.p;
  29215. serializationObject.q = this.q;
  29216. return serializationObject;
  29217. };
  29218. ;
  29219. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  29220. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  29221. return null; // null since geometry could be something else than a ground...
  29222. }
  29223. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  29224. if (BABYLON.Tags) {
  29225. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  29226. }
  29227. scene.pushGeometry(torusKnot, true);
  29228. return torusKnot;
  29229. };
  29230. return TorusKnot;
  29231. }(_Primitive));
  29232. Primitives.TorusKnot = TorusKnot;
  29233. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29234. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29235. })(BABYLON || (BABYLON = {}));
  29236. //# sourceMappingURL=babylon.geometry.js.map
  29237. var BABYLON;
  29238. (function (BABYLON) {
  29239. var PostProcessManager = (function () {
  29240. function PostProcessManager(scene) {
  29241. this._vertexBuffers = {};
  29242. this._scene = scene;
  29243. }
  29244. PostProcessManager.prototype._prepareBuffers = function () {
  29245. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29246. return;
  29247. }
  29248. // VBO
  29249. var vertices = [];
  29250. vertices.push(1, 1);
  29251. vertices.push(-1, 1);
  29252. vertices.push(-1, -1);
  29253. vertices.push(1, -1);
  29254. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29255. // Indices
  29256. var indices = [];
  29257. indices.push(0);
  29258. indices.push(1);
  29259. indices.push(2);
  29260. indices.push(0);
  29261. indices.push(2);
  29262. indices.push(3);
  29263. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29264. };
  29265. // Methods
  29266. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  29267. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29268. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29269. return false;
  29270. }
  29271. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  29272. return true;
  29273. };
  29274. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  29275. var engine = this._scene.getEngine();
  29276. for (var index = 0; index < postProcesses.length; index++) {
  29277. if (index < postProcesses.length - 1) {
  29278. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29279. }
  29280. else {
  29281. if (targetTexture) {
  29282. engine.bindFramebuffer(targetTexture);
  29283. }
  29284. else {
  29285. engine.restoreDefaultFramebuffer();
  29286. }
  29287. }
  29288. var pp = postProcesses[index];
  29289. var effect = pp.apply();
  29290. if (effect) {
  29291. pp.onBeforeRenderObservable.notifyObservers(effect);
  29292. // VBOs
  29293. this._prepareBuffers();
  29294. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29295. // Draw order
  29296. engine.draw(true, 0, 6);
  29297. pp.onAfterRenderObservable.notifyObservers(effect);
  29298. }
  29299. }
  29300. // Restore depth buffer
  29301. engine.setDepthBuffer(true);
  29302. engine.setDepthWrite(true);
  29303. };
  29304. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29305. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29306. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29307. return;
  29308. }
  29309. var engine = this._scene.getEngine();
  29310. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29311. if (index < len - 1) {
  29312. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29313. }
  29314. else {
  29315. if (targetTexture) {
  29316. engine.bindFramebuffer(targetTexture, faceIndex);
  29317. }
  29318. else {
  29319. engine.restoreDefaultFramebuffer();
  29320. }
  29321. }
  29322. if (doNotPresent) {
  29323. break;
  29324. }
  29325. var pp = postProcesses[index];
  29326. var effect = pp.apply();
  29327. if (effect) {
  29328. pp.onBeforeRenderObservable.notifyObservers(effect);
  29329. // VBOs
  29330. this._prepareBuffers();
  29331. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29332. // Draw order
  29333. engine.draw(true, 0, 6);
  29334. pp.onAfterRenderObservable.notifyObservers(effect);
  29335. }
  29336. }
  29337. // Restore states
  29338. engine.setDepthBuffer(true);
  29339. engine.setDepthWrite(true);
  29340. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29341. };
  29342. PostProcessManager.prototype.dispose = function () {
  29343. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29344. if (buffer) {
  29345. buffer.dispose();
  29346. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29347. }
  29348. if (this._indexBuffer) {
  29349. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29350. this._indexBuffer = null;
  29351. }
  29352. };
  29353. return PostProcessManager;
  29354. }());
  29355. BABYLON.PostProcessManager = PostProcessManager;
  29356. })(BABYLON || (BABYLON = {}));
  29357. //# sourceMappingURL=babylon.postProcessManager.js.map
  29358. var BABYLON;
  29359. (function (BABYLON) {
  29360. /**
  29361. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  29362. */
  29363. var PerformanceMonitor = (function () {
  29364. /**
  29365. * constructor
  29366. * @param frameSampleSize The number of samples required to saturate the sliding window
  29367. */
  29368. function PerformanceMonitor(frameSampleSize) {
  29369. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  29370. this._enabled = true;
  29371. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  29372. }
  29373. /**
  29374. * Samples current frame
  29375. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  29376. */
  29377. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  29378. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  29379. if (!this._enabled)
  29380. return;
  29381. if (this._lastFrameTimeMs != null) {
  29382. var dt = timeMs - this._lastFrameTimeMs;
  29383. this._rollingFrameTime.add(dt);
  29384. }
  29385. this._lastFrameTimeMs = timeMs;
  29386. };
  29387. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  29388. /**
  29389. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29390. * @return Average frame time in milliseconds
  29391. */
  29392. get: function () {
  29393. return this._rollingFrameTime.average;
  29394. },
  29395. enumerable: true,
  29396. configurable: true
  29397. });
  29398. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  29399. /**
  29400. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29401. * @return Frame time variance in milliseconds squared
  29402. */
  29403. get: function () {
  29404. return this._rollingFrameTime.variance;
  29405. },
  29406. enumerable: true,
  29407. configurable: true
  29408. });
  29409. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  29410. /**
  29411. * Returns the frame time of the most recent frame
  29412. * @return Frame time in milliseconds
  29413. */
  29414. get: function () {
  29415. return this._rollingFrameTime.history(0);
  29416. },
  29417. enumerable: true,
  29418. configurable: true
  29419. });
  29420. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  29421. /**
  29422. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  29423. * @return Framerate in frames per second
  29424. */
  29425. get: function () {
  29426. return 1000.0 / this._rollingFrameTime.average;
  29427. },
  29428. enumerable: true,
  29429. configurable: true
  29430. });
  29431. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  29432. /**
  29433. * Returns the average framerate in frames per second using the most recent frame time
  29434. * @return Framerate in frames per second
  29435. */
  29436. get: function () {
  29437. return 1000.0 / this._rollingFrameTime.history(0);
  29438. },
  29439. enumerable: true,
  29440. configurable: true
  29441. });
  29442. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  29443. /**
  29444. * Returns true if enough samples have been taken to completely fill the sliding window
  29445. * @return true if saturated
  29446. */
  29447. get: function () {
  29448. return this._rollingFrameTime.isSaturated();
  29449. },
  29450. enumerable: true,
  29451. configurable: true
  29452. });
  29453. /**
  29454. * Enables contributions to the sliding window sample set
  29455. */
  29456. PerformanceMonitor.prototype.enable = function () {
  29457. this._enabled = true;
  29458. };
  29459. /**
  29460. * Disables contributions to the sliding window sample set
  29461. * Samples will not be interpolated over the disabled period
  29462. */
  29463. PerformanceMonitor.prototype.disable = function () {
  29464. this._enabled = false;
  29465. //clear last sample to avoid interpolating over the disabled period when next enabled
  29466. this._lastFrameTimeMs = null;
  29467. this._lastChangeTimeMs = null;
  29468. };
  29469. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  29470. /**
  29471. * Returns true if sampling is enabled
  29472. * @return true if enabled
  29473. */
  29474. get: function () {
  29475. return this._enabled;
  29476. },
  29477. enumerable: true,
  29478. configurable: true
  29479. });
  29480. /**
  29481. * Resets performance monitor
  29482. */
  29483. PerformanceMonitor.prototype.reset = function () {
  29484. //clear last sample to avoid interpolating over the disabled period when next enabled
  29485. this._lastFrameTimeMs = null;
  29486. this._lastChangeTimeMs = null;
  29487. //wipe record
  29488. this._rollingFrameTime.reset();
  29489. };
  29490. return PerformanceMonitor;
  29491. }());
  29492. BABYLON.PerformanceMonitor = PerformanceMonitor;
  29493. /**
  29494. * RollingAverage
  29495. *
  29496. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  29497. */
  29498. var RollingAverage = (function () {
  29499. /**
  29500. * constructor
  29501. * @param length The number of samples required to saturate the sliding window
  29502. */
  29503. function RollingAverage(length) {
  29504. this._samples = new Array(length);
  29505. this.reset();
  29506. }
  29507. /**
  29508. * Adds a sample to the sample set
  29509. * @param v The sample value
  29510. */
  29511. RollingAverage.prototype.add = function (v) {
  29512. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  29513. var delta;
  29514. //we need to check if we've already wrapped round
  29515. if (this.isSaturated()) {
  29516. //remove bottom of stack from mean
  29517. var bottomValue = this._samples[this._pos];
  29518. delta = bottomValue - this.average;
  29519. this.average -= delta / (this._sampleCount - 1);
  29520. this._m2 -= delta * (bottomValue - this.average);
  29521. }
  29522. else {
  29523. this._sampleCount++;
  29524. }
  29525. //add new value to mean
  29526. delta = v - this.average;
  29527. this.average += delta / (this._sampleCount);
  29528. this._m2 += delta * (v - this.average);
  29529. //set the new variance
  29530. this.variance = this._m2 / (this._sampleCount - 1);
  29531. this._samples[this._pos] = v;
  29532. this._pos++;
  29533. this._pos %= this._samples.length; //positive wrap around
  29534. };
  29535. /**
  29536. * Returns previously added values or null if outside of history or outside the sliding window domain
  29537. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  29538. * @return Value previously recorded with add() or null if outside of range
  29539. */
  29540. RollingAverage.prototype.history = function (i) {
  29541. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  29542. return null;
  29543. }
  29544. var i0 = this._wrapPosition(this._pos - 1.0);
  29545. return this._samples[this._wrapPosition(i0 - i)];
  29546. };
  29547. /**
  29548. * Returns true if enough samples have been taken to completely fill the sliding window
  29549. * @return true if sample-set saturated
  29550. */
  29551. RollingAverage.prototype.isSaturated = function () {
  29552. return this._sampleCount >= this._samples.length;
  29553. };
  29554. /**
  29555. * Resets the rolling average (equivalent to 0 samples taken so far)
  29556. */
  29557. RollingAverage.prototype.reset = function () {
  29558. this.average = 0;
  29559. this.variance = 0;
  29560. this._sampleCount = 0;
  29561. this._pos = 0;
  29562. this._m2 = 0;
  29563. };
  29564. /**
  29565. * Wraps a value around the sample range boundaries
  29566. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  29567. * @return Wrapped position in sample range
  29568. */
  29569. RollingAverage.prototype._wrapPosition = function (i) {
  29570. var max = this._samples.length;
  29571. return ((i % max) + max) % max;
  29572. };
  29573. return RollingAverage;
  29574. }());
  29575. BABYLON.RollingAverage = RollingAverage;
  29576. })(BABYLON || (BABYLON = {}));
  29577. //# sourceMappingURL=babylon.performanceMonitor.js.map
  29578. var BABYLON;
  29579. (function (BABYLON) {
  29580. var AnimationRange = (function () {
  29581. function AnimationRange(name, from, to) {
  29582. this.name = name;
  29583. this.from = from;
  29584. this.to = to;
  29585. }
  29586. AnimationRange.prototype.clone = function () {
  29587. return new AnimationRange(this.name, this.from, this.to);
  29588. };
  29589. return AnimationRange;
  29590. }());
  29591. BABYLON.AnimationRange = AnimationRange;
  29592. /**
  29593. * Composed of a frame, and an action function
  29594. */
  29595. var AnimationEvent = (function () {
  29596. function AnimationEvent(frame, action, onlyOnce) {
  29597. this.frame = frame;
  29598. this.action = action;
  29599. this.onlyOnce = onlyOnce;
  29600. this.isDone = false;
  29601. }
  29602. return AnimationEvent;
  29603. }());
  29604. BABYLON.AnimationEvent = AnimationEvent;
  29605. var PathCursor = (function () {
  29606. function PathCursor(path) {
  29607. this.path = path;
  29608. this._onchange = new Array();
  29609. this.value = 0;
  29610. this.animations = new Array();
  29611. }
  29612. PathCursor.prototype.getPoint = function () {
  29613. var point = this.path.getPointAtLengthPosition(this.value);
  29614. return new BABYLON.Vector3(point.x, 0, point.y);
  29615. };
  29616. PathCursor.prototype.moveAhead = function (step) {
  29617. if (step === void 0) { step = 0.002; }
  29618. this.move(step);
  29619. return this;
  29620. };
  29621. PathCursor.prototype.moveBack = function (step) {
  29622. if (step === void 0) { step = 0.002; }
  29623. this.move(-step);
  29624. return this;
  29625. };
  29626. PathCursor.prototype.move = function (step) {
  29627. if (Math.abs(step) > 1) {
  29628. throw "step size should be less than 1.";
  29629. }
  29630. this.value += step;
  29631. this.ensureLimits();
  29632. this.raiseOnChange();
  29633. return this;
  29634. };
  29635. PathCursor.prototype.ensureLimits = function () {
  29636. while (this.value > 1) {
  29637. this.value -= 1;
  29638. }
  29639. while (this.value < 0) {
  29640. this.value += 1;
  29641. }
  29642. return this;
  29643. };
  29644. // used by animation engine
  29645. PathCursor.prototype.markAsDirty = function (propertyName) {
  29646. this.ensureLimits();
  29647. this.raiseOnChange();
  29648. return this;
  29649. };
  29650. PathCursor.prototype.raiseOnChange = function () {
  29651. var _this = this;
  29652. this._onchange.forEach(function (f) { return f(_this); });
  29653. return this;
  29654. };
  29655. PathCursor.prototype.onchange = function (f) {
  29656. this._onchange.push(f);
  29657. return this;
  29658. };
  29659. return PathCursor;
  29660. }());
  29661. BABYLON.PathCursor = PathCursor;
  29662. var Animation = (function () {
  29663. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29664. this.name = name;
  29665. this.targetProperty = targetProperty;
  29666. this.framePerSecond = framePerSecond;
  29667. this.dataType = dataType;
  29668. this.loopMode = loopMode;
  29669. this.enableBlending = enableBlending;
  29670. this._offsetsCache = {};
  29671. this._highLimitsCache = {};
  29672. this._stopped = false;
  29673. this._blendingFactor = 0;
  29674. // The set of event that will be linked to this animation
  29675. this._events = new Array();
  29676. this.allowMatricesInterpolation = false;
  29677. this.blendingSpeed = 0.01;
  29678. this._ranges = {};
  29679. this.targetPropertyPath = targetProperty.split(".");
  29680. this.dataType = dataType;
  29681. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29682. }
  29683. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29684. var dataType = undefined;
  29685. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29686. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29687. }
  29688. else if (from instanceof BABYLON.Quaternion) {
  29689. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29690. }
  29691. else if (from instanceof BABYLON.Vector3) {
  29692. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29693. }
  29694. else if (from instanceof BABYLON.Vector2) {
  29695. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29696. }
  29697. else if (from instanceof BABYLON.Color3) {
  29698. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29699. }
  29700. else if (from instanceof BABYLON.Size) {
  29701. dataType = Animation.ANIMATIONTYPE_SIZE;
  29702. }
  29703. if (dataType == undefined) {
  29704. return null;
  29705. }
  29706. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29707. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29708. animation.setKeys(keys);
  29709. if (easingFunction !== undefined) {
  29710. animation.setEasingFunction(easingFunction);
  29711. }
  29712. return animation;
  29713. };
  29714. /**
  29715. * Sets up an animation.
  29716. * @param property the property to animate
  29717. * @param animationType the animation type to apply
  29718. * @param easingFunction the easing function used in the animation
  29719. * @returns The created animation
  29720. */
  29721. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  29722. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  29723. animation.setEasingFunction(easingFunction);
  29724. return animation;
  29725. };
  29726. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29727. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29728. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29729. };
  29730. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29731. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29732. node.animations.push(animation);
  29733. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29734. };
  29735. /**
  29736. * Transition property of the Camera to the target Value.
  29737. * @param property The property to transition
  29738. * @param targetValue The target Value of the property
  29739. * @param host The object where the property to animate belongs
  29740. * @param scene Scene used to run the animation
  29741. * @param frameRate Framerate (in frame/s) to use
  29742. * @param transition The transition type we want to use
  29743. * @param duration The duration of the animation, in milliseconds
  29744. * @param onAnimationEnd Call back trigger at the end of the animation.
  29745. */
  29746. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  29747. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  29748. if (duration <= 0) {
  29749. host[property] = targetValue;
  29750. if (onAnimationEnd) {
  29751. onAnimationEnd();
  29752. }
  29753. return;
  29754. }
  29755. var endFrame = frameRate * (duration / 1000);
  29756. transition.setKeys([{
  29757. frame: 0,
  29758. value: host[property]
  29759. },
  29760. {
  29761. frame: endFrame,
  29762. value: targetValue
  29763. }]);
  29764. if (!host.animations) {
  29765. host.animations = [];
  29766. }
  29767. host.animations.push(transition);
  29768. var animation = scene.beginAnimation(host, 0, endFrame, false);
  29769. animation.onAnimationEnd = onAnimationEnd;
  29770. return animation;
  29771. };
  29772. // Methods
  29773. /**
  29774. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29775. */
  29776. Animation.prototype.toString = function (fullDetails) {
  29777. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29778. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29779. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29780. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29781. if (fullDetails) {
  29782. ret += ", Ranges: {";
  29783. var first = true;
  29784. for (var name in this._ranges) {
  29785. if (first) {
  29786. ret += ", ";
  29787. first = false;
  29788. }
  29789. ret += name;
  29790. }
  29791. ret += "}";
  29792. }
  29793. return ret;
  29794. };
  29795. /**
  29796. * Add an event to this animation.
  29797. */
  29798. Animation.prototype.addEvent = function (event) {
  29799. this._events.push(event);
  29800. };
  29801. /**
  29802. * Remove all events found at the given frame
  29803. * @param frame
  29804. */
  29805. Animation.prototype.removeEvents = function (frame) {
  29806. for (var index = 0; index < this._events.length; index++) {
  29807. if (this._events[index].frame === frame) {
  29808. this._events.splice(index, 1);
  29809. index--;
  29810. }
  29811. }
  29812. };
  29813. Animation.prototype.createRange = function (name, from, to) {
  29814. // check name not already in use; could happen for bones after serialized
  29815. if (!this._ranges[name]) {
  29816. this._ranges[name] = new AnimationRange(name, from, to);
  29817. }
  29818. };
  29819. Animation.prototype.deleteRange = function (name, deleteFrames) {
  29820. if (deleteFrames === void 0) { deleteFrames = true; }
  29821. if (this._ranges[name]) {
  29822. if (deleteFrames) {
  29823. var from = this._ranges[name].from;
  29824. var to = this._ranges[name].to;
  29825. // this loop MUST go high to low for multiple splices to work
  29826. for (var key = this._keys.length - 1; key >= 0; key--) {
  29827. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  29828. this._keys.splice(key, 1);
  29829. }
  29830. }
  29831. }
  29832. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29833. }
  29834. };
  29835. Animation.prototype.getRange = function (name) {
  29836. return this._ranges[name];
  29837. };
  29838. Animation.prototype.reset = function () {
  29839. this._offsetsCache = {};
  29840. this._highLimitsCache = {};
  29841. this.currentFrame = 0;
  29842. this._blendingFactor = 0;
  29843. this._originalBlendValue = null;
  29844. };
  29845. Animation.prototype.isStopped = function () {
  29846. return this._stopped;
  29847. };
  29848. Animation.prototype.getKeys = function () {
  29849. return this._keys;
  29850. };
  29851. Animation.prototype.getHighestFrame = function () {
  29852. var ret = 0;
  29853. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  29854. if (ret < this._keys[key].frame) {
  29855. ret = this._keys[key].frame;
  29856. }
  29857. }
  29858. return ret;
  29859. };
  29860. Animation.prototype.getEasingFunction = function () {
  29861. return this._easingFunction;
  29862. };
  29863. Animation.prototype.setEasingFunction = function (easingFunction) {
  29864. this._easingFunction = easingFunction;
  29865. };
  29866. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  29867. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  29868. };
  29869. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  29870. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  29871. };
  29872. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  29873. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  29874. };
  29875. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  29876. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  29877. };
  29878. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  29879. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  29880. };
  29881. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  29882. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  29883. };
  29884. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  29885. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  29886. };
  29887. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  29888. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  29889. };
  29890. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  29891. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  29892. };
  29893. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  29894. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  29895. };
  29896. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  29897. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  29898. };
  29899. Animation.prototype.clone = function () {
  29900. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  29901. clone.enableBlending = this.enableBlending;
  29902. clone.blendingSpeed = this.blendingSpeed;
  29903. if (this._keys) {
  29904. clone.setKeys(this._keys);
  29905. }
  29906. if (this._ranges) {
  29907. clone._ranges = {};
  29908. for (var name in this._ranges) {
  29909. clone._ranges[name] = this._ranges[name].clone();
  29910. }
  29911. }
  29912. return clone;
  29913. };
  29914. Animation.prototype.setKeys = function (values) {
  29915. this._keys = values.slice(0);
  29916. this._offsetsCache = {};
  29917. this._highLimitsCache = {};
  29918. };
  29919. Animation.prototype._getKeyValue = function (value) {
  29920. if (typeof value === "function") {
  29921. return value();
  29922. }
  29923. return value;
  29924. };
  29925. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  29926. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  29927. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  29928. }
  29929. this.currentFrame = currentFrame;
  29930. // Try to get a hash to find the right key
  29931. 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));
  29932. if (this._keys[startKeyIndex].frame >= currentFrame) {
  29933. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  29934. startKeyIndex--;
  29935. }
  29936. }
  29937. for (var key = startKeyIndex; key < this._keys.length; key++) {
  29938. var endKey = this._keys[key + 1];
  29939. if (endKey.frame >= currentFrame) {
  29940. var startKey = this._keys[key];
  29941. var startValue = this._getKeyValue(startKey.value);
  29942. var endValue = this._getKeyValue(endKey.value);
  29943. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  29944. var frameDelta = endKey.frame - startKey.frame;
  29945. // gradient : percent of currentFrame between the frame inf and the frame sup
  29946. var gradient = (currentFrame - startKey.frame) / frameDelta;
  29947. // check for easingFunction and correction of gradient
  29948. if (this._easingFunction != null) {
  29949. gradient = this._easingFunction.ease(gradient);
  29950. }
  29951. switch (this.dataType) {
  29952. // Float
  29953. case Animation.ANIMATIONTYPE_FLOAT:
  29954. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  29955. switch (loopMode) {
  29956. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29957. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29958. return floatValue;
  29959. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29960. return offsetValue * repeatCount + floatValue;
  29961. }
  29962. break;
  29963. // Quaternion
  29964. case Animation.ANIMATIONTYPE_QUATERNION:
  29965. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  29966. switch (loopMode) {
  29967. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29968. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29969. return quatValue;
  29970. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29971. return quatValue.add(offsetValue.scale(repeatCount));
  29972. }
  29973. return quatValue;
  29974. // Vector3
  29975. case Animation.ANIMATIONTYPE_VECTOR3:
  29976. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  29977. switch (loopMode) {
  29978. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29979. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29980. return vec3Value;
  29981. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29982. return vec3Value.add(offsetValue.scale(repeatCount));
  29983. }
  29984. // Vector2
  29985. case Animation.ANIMATIONTYPE_VECTOR2:
  29986. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  29987. switch (loopMode) {
  29988. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29989. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29990. return vec2Value;
  29991. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29992. return vec2Value.add(offsetValue.scale(repeatCount));
  29993. }
  29994. // Size
  29995. case Animation.ANIMATIONTYPE_SIZE:
  29996. switch (loopMode) {
  29997. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29998. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29999. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30000. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30001. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30002. }
  30003. // Color3
  30004. case Animation.ANIMATIONTYPE_COLOR3:
  30005. switch (loopMode) {
  30006. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30007. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30008. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30009. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30010. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30011. }
  30012. // Matrix
  30013. case Animation.ANIMATIONTYPE_MATRIX:
  30014. switch (loopMode) {
  30015. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30016. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30017. if (this.allowMatricesInterpolation) {
  30018. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30019. }
  30020. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30021. return startValue;
  30022. }
  30023. default:
  30024. break;
  30025. }
  30026. break;
  30027. }
  30028. }
  30029. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30030. };
  30031. Animation.prototype.setValue = function (currentValue, blend) {
  30032. if (blend === void 0) { blend = false; }
  30033. // Set value
  30034. var path;
  30035. var destination;
  30036. if (this.targetPropertyPath.length > 1) {
  30037. var property = this._target[this.targetPropertyPath[0]];
  30038. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30039. property = property[this.targetPropertyPath[index]];
  30040. }
  30041. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30042. destination = property;
  30043. }
  30044. else {
  30045. path = this.targetPropertyPath[0];
  30046. destination = this._target;
  30047. }
  30048. // Blending
  30049. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30050. if (!this._originalBlendValue) {
  30051. if (destination[path].clone) {
  30052. this._originalBlendValue = destination[path].clone();
  30053. }
  30054. else {
  30055. this._originalBlendValue = destination[path];
  30056. }
  30057. }
  30058. if (this._originalBlendValue.prototype) {
  30059. if (this._originalBlendValue.prototype.Lerp) {
  30060. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30061. }
  30062. else {
  30063. destination[path] = currentValue;
  30064. }
  30065. }
  30066. else if (this._originalBlendValue.m) {
  30067. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30068. }
  30069. else {
  30070. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30071. }
  30072. this._blendingFactor += this.blendingSpeed;
  30073. }
  30074. else {
  30075. destination[path] = currentValue;
  30076. }
  30077. if (this._target.markAsDirty) {
  30078. this._target.markAsDirty(this.targetProperty);
  30079. }
  30080. };
  30081. Animation.prototype.goToFrame = function (frame) {
  30082. if (frame < this._keys[0].frame) {
  30083. frame = this._keys[0].frame;
  30084. }
  30085. else if (frame > this._keys[this._keys.length - 1].frame) {
  30086. frame = this._keys[this._keys.length - 1].frame;
  30087. }
  30088. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30089. this.setValue(currentValue);
  30090. };
  30091. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30092. if (blend === void 0) { blend = false; }
  30093. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30094. this._stopped = true;
  30095. return false;
  30096. }
  30097. var returnValue = true;
  30098. // Adding a start key at frame 0 if missing
  30099. if (this._keys[0].frame !== 0) {
  30100. var newKey = { frame: 0, value: this._keys[0].value };
  30101. this._keys.splice(0, 0, newKey);
  30102. }
  30103. // Check limits
  30104. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30105. from = this._keys[0].frame;
  30106. }
  30107. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30108. to = this._keys[this._keys.length - 1].frame;
  30109. }
  30110. //to and from cannot be the same key
  30111. if (from === to) {
  30112. from++;
  30113. }
  30114. // Compute ratio
  30115. var range = to - from;
  30116. var offsetValue;
  30117. // ratio represents the frame delta between from and to
  30118. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30119. var highLimitValue = 0;
  30120. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  30121. returnValue = false;
  30122. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30123. }
  30124. else {
  30125. // Get max value if required
  30126. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30127. var keyOffset = to.toString() + from.toString();
  30128. if (!this._offsetsCache[keyOffset]) {
  30129. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30130. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30131. switch (this.dataType) {
  30132. // Float
  30133. case Animation.ANIMATIONTYPE_FLOAT:
  30134. this._offsetsCache[keyOffset] = toValue - fromValue;
  30135. break;
  30136. // Quaternion
  30137. case Animation.ANIMATIONTYPE_QUATERNION:
  30138. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30139. break;
  30140. // Vector3
  30141. case Animation.ANIMATIONTYPE_VECTOR3:
  30142. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30143. // Vector2
  30144. case Animation.ANIMATIONTYPE_VECTOR2:
  30145. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30146. // Size
  30147. case Animation.ANIMATIONTYPE_SIZE:
  30148. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30149. // Color3
  30150. case Animation.ANIMATIONTYPE_COLOR3:
  30151. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30152. default:
  30153. break;
  30154. }
  30155. this._highLimitsCache[keyOffset] = toValue;
  30156. }
  30157. highLimitValue = this._highLimitsCache[keyOffset];
  30158. offsetValue = this._offsetsCache[keyOffset];
  30159. }
  30160. }
  30161. if (offsetValue === undefined) {
  30162. switch (this.dataType) {
  30163. // Float
  30164. case Animation.ANIMATIONTYPE_FLOAT:
  30165. offsetValue = 0;
  30166. break;
  30167. // Quaternion
  30168. case Animation.ANIMATIONTYPE_QUATERNION:
  30169. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30170. break;
  30171. // Vector3
  30172. case Animation.ANIMATIONTYPE_VECTOR3:
  30173. offsetValue = BABYLON.Vector3.Zero();
  30174. break;
  30175. // Vector2
  30176. case Animation.ANIMATIONTYPE_VECTOR2:
  30177. offsetValue = BABYLON.Vector2.Zero();
  30178. break;
  30179. // Size
  30180. case Animation.ANIMATIONTYPE_SIZE:
  30181. offsetValue = BABYLON.Size.Zero();
  30182. break;
  30183. // Color3
  30184. case Animation.ANIMATIONTYPE_COLOR3:
  30185. offsetValue = BABYLON.Color3.Black();
  30186. }
  30187. }
  30188. // Compute value
  30189. var repeatCount = (ratio / range) >> 0;
  30190. var currentFrame = returnValue ? from + ratio % range : to;
  30191. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30192. // Set value
  30193. this.setValue(currentValue);
  30194. // Check events
  30195. for (var index = 0; index < this._events.length; index++) {
  30196. // Make sure current frame has passed event frame and that event frame is within the current range
  30197. // Also, handle both forward and reverse animations
  30198. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  30199. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  30200. var event = this._events[index];
  30201. if (!event.isDone) {
  30202. // If event should be done only once, remove it.
  30203. if (event.onlyOnce) {
  30204. this._events.splice(index, 1);
  30205. index--;
  30206. }
  30207. event.isDone = true;
  30208. event.action();
  30209. } // Don't do anything if the event has already be done.
  30210. }
  30211. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30212. // reset event, the animation is looping
  30213. this._events[index].isDone = false;
  30214. }
  30215. }
  30216. if (!returnValue) {
  30217. this._stopped = true;
  30218. }
  30219. return returnValue;
  30220. };
  30221. Animation.prototype.serialize = function () {
  30222. var serializationObject = {};
  30223. serializationObject.name = this.name;
  30224. serializationObject.property = this.targetProperty;
  30225. serializationObject.framePerSecond = this.framePerSecond;
  30226. serializationObject.dataType = this.dataType;
  30227. serializationObject.loopBehavior = this.loopMode;
  30228. serializationObject.enableBlending = this.enableBlending;
  30229. serializationObject.blendingSpeed = this.blendingSpeed;
  30230. var dataType = this.dataType;
  30231. serializationObject.keys = [];
  30232. var keys = this.getKeys();
  30233. for (var index = 0; index < keys.length; index++) {
  30234. var animationKey = keys[index];
  30235. var key = {};
  30236. key.frame = animationKey.frame;
  30237. switch (dataType) {
  30238. case Animation.ANIMATIONTYPE_FLOAT:
  30239. key.values = [animationKey.value];
  30240. break;
  30241. case Animation.ANIMATIONTYPE_QUATERNION:
  30242. case Animation.ANIMATIONTYPE_MATRIX:
  30243. case Animation.ANIMATIONTYPE_VECTOR3:
  30244. case Animation.ANIMATIONTYPE_COLOR3:
  30245. key.values = animationKey.value.asArray();
  30246. break;
  30247. }
  30248. serializationObject.keys.push(key);
  30249. }
  30250. serializationObject.ranges = [];
  30251. for (var name in this._ranges) {
  30252. var range = {};
  30253. range.name = name;
  30254. range.from = this._ranges[name].from;
  30255. range.to = this._ranges[name].to;
  30256. serializationObject.ranges.push(range);
  30257. }
  30258. return serializationObject;
  30259. };
  30260. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30261. get: function () {
  30262. return Animation._ANIMATIONTYPE_FLOAT;
  30263. },
  30264. enumerable: true,
  30265. configurable: true
  30266. });
  30267. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30268. get: function () {
  30269. return Animation._ANIMATIONTYPE_VECTOR3;
  30270. },
  30271. enumerable: true,
  30272. configurable: true
  30273. });
  30274. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30275. get: function () {
  30276. return Animation._ANIMATIONTYPE_VECTOR2;
  30277. },
  30278. enumerable: true,
  30279. configurable: true
  30280. });
  30281. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30282. get: function () {
  30283. return Animation._ANIMATIONTYPE_SIZE;
  30284. },
  30285. enumerable: true,
  30286. configurable: true
  30287. });
  30288. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30289. get: function () {
  30290. return Animation._ANIMATIONTYPE_QUATERNION;
  30291. },
  30292. enumerable: true,
  30293. configurable: true
  30294. });
  30295. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30296. get: function () {
  30297. return Animation._ANIMATIONTYPE_MATRIX;
  30298. },
  30299. enumerable: true,
  30300. configurable: true
  30301. });
  30302. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30303. get: function () {
  30304. return Animation._ANIMATIONTYPE_COLOR3;
  30305. },
  30306. enumerable: true,
  30307. configurable: true
  30308. });
  30309. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30310. get: function () {
  30311. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30312. },
  30313. enumerable: true,
  30314. configurable: true
  30315. });
  30316. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30317. get: function () {
  30318. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30319. },
  30320. enumerable: true,
  30321. configurable: true
  30322. });
  30323. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30324. get: function () {
  30325. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30326. },
  30327. enumerable: true,
  30328. configurable: true
  30329. });
  30330. Animation.Parse = function (parsedAnimation) {
  30331. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30332. var dataType = parsedAnimation.dataType;
  30333. var keys = [];
  30334. var data;
  30335. var index;
  30336. if (parsedAnimation.enableBlending) {
  30337. animation.enableBlending = parsedAnimation.enableBlending;
  30338. }
  30339. if (parsedAnimation.blendingSpeed) {
  30340. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30341. }
  30342. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30343. var key = parsedAnimation.keys[index];
  30344. switch (dataType) {
  30345. case Animation.ANIMATIONTYPE_FLOAT:
  30346. data = key.values[0];
  30347. break;
  30348. case Animation.ANIMATIONTYPE_QUATERNION:
  30349. data = BABYLON.Quaternion.FromArray(key.values);
  30350. break;
  30351. case Animation.ANIMATIONTYPE_MATRIX:
  30352. data = BABYLON.Matrix.FromArray(key.values);
  30353. break;
  30354. case Animation.ANIMATIONTYPE_COLOR3:
  30355. data = BABYLON.Color3.FromArray(key.values);
  30356. break;
  30357. case Animation.ANIMATIONTYPE_VECTOR3:
  30358. default:
  30359. data = BABYLON.Vector3.FromArray(key.values);
  30360. break;
  30361. }
  30362. keys.push({
  30363. frame: key.frame,
  30364. value: data
  30365. });
  30366. }
  30367. animation.setKeys(keys);
  30368. if (parsedAnimation.ranges) {
  30369. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30370. data = parsedAnimation.ranges[index];
  30371. animation.createRange(data.name, data.from, data.to);
  30372. }
  30373. }
  30374. return animation;
  30375. };
  30376. Animation.AppendSerializedAnimations = function (source, destination) {
  30377. if (source.animations) {
  30378. destination.animations = [];
  30379. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30380. var animation = source.animations[animationIndex];
  30381. destination.animations.push(animation.serialize());
  30382. }
  30383. }
  30384. };
  30385. // Statics
  30386. Animation._ANIMATIONTYPE_FLOAT = 0;
  30387. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  30388. Animation._ANIMATIONTYPE_QUATERNION = 2;
  30389. Animation._ANIMATIONTYPE_MATRIX = 3;
  30390. Animation._ANIMATIONTYPE_COLOR3 = 4;
  30391. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  30392. Animation._ANIMATIONTYPE_SIZE = 6;
  30393. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  30394. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  30395. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  30396. return Animation;
  30397. }());
  30398. BABYLON.Animation = Animation;
  30399. })(BABYLON || (BABYLON = {}));
  30400. //# sourceMappingURL=babylon.animation.js.map
  30401. var BABYLON;
  30402. (function (BABYLON) {
  30403. var Animatable = (function () {
  30404. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  30405. if (fromFrame === void 0) { fromFrame = 0; }
  30406. if (toFrame === void 0) { toFrame = 100; }
  30407. if (loopAnimation === void 0) { loopAnimation = false; }
  30408. if (speedRatio === void 0) { speedRatio = 1.0; }
  30409. this.target = target;
  30410. this.fromFrame = fromFrame;
  30411. this.toFrame = toFrame;
  30412. this.loopAnimation = loopAnimation;
  30413. this.speedRatio = speedRatio;
  30414. this.onAnimationEnd = onAnimationEnd;
  30415. this._localDelayOffset = null;
  30416. this._pausedDelay = null;
  30417. this._animations = new Array();
  30418. this._paused = false;
  30419. this.animationStarted = false;
  30420. if (animations) {
  30421. this.appendAnimations(target, animations);
  30422. }
  30423. this._scene = scene;
  30424. scene._activeAnimatables.push(this);
  30425. }
  30426. // Methods
  30427. Animatable.prototype.getAnimations = function () {
  30428. return this._animations;
  30429. };
  30430. Animatable.prototype.appendAnimations = function (target, animations) {
  30431. for (var index = 0; index < animations.length; index++) {
  30432. var animation = animations[index];
  30433. animation._target = target;
  30434. this._animations.push(animation);
  30435. }
  30436. };
  30437. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  30438. var animations = this._animations;
  30439. for (var index = 0; index < animations.length; index++) {
  30440. if (animations[index].targetProperty === property) {
  30441. return animations[index];
  30442. }
  30443. }
  30444. return null;
  30445. };
  30446. Animatable.prototype.reset = function () {
  30447. var animations = this._animations;
  30448. for (var index = 0; index < animations.length; index++) {
  30449. animations[index].reset();
  30450. }
  30451. this._localDelayOffset = null;
  30452. this._pausedDelay = null;
  30453. };
  30454. Animatable.prototype.enableBlending = function (blendingSpeed) {
  30455. var animations = this._animations;
  30456. for (var index = 0; index < animations.length; index++) {
  30457. animations[index].enableBlending = true;
  30458. animations[index].blendingSpeed = blendingSpeed;
  30459. }
  30460. };
  30461. Animatable.prototype.disableBlending = function () {
  30462. var animations = this._animations;
  30463. for (var index = 0; index < animations.length; index++) {
  30464. animations[index].enableBlending = false;
  30465. }
  30466. };
  30467. Animatable.prototype.goToFrame = function (frame) {
  30468. var animations = this._animations;
  30469. if (animations[0]) {
  30470. var fps = animations[0].framePerSecond;
  30471. var currentFrame = animations[0].currentFrame;
  30472. var adjustTime = frame - currentFrame;
  30473. var delay = adjustTime * 1000 / fps;
  30474. this._localDelayOffset -= delay;
  30475. }
  30476. for (var index = 0; index < animations.length; index++) {
  30477. animations[index].goToFrame(frame);
  30478. }
  30479. };
  30480. Animatable.prototype.pause = function () {
  30481. if (this._paused) {
  30482. return;
  30483. }
  30484. this._paused = true;
  30485. };
  30486. Animatable.prototype.restart = function () {
  30487. this._paused = false;
  30488. };
  30489. Animatable.prototype.stop = function (animationName) {
  30490. if (animationName) {
  30491. var idx = this._scene._activeAnimatables.indexOf(this);
  30492. if (idx > -1) {
  30493. var animations = this._animations;
  30494. for (var index = animations.length - 1; index >= 0; index--) {
  30495. if (typeof animationName === "string" && animations[index].name != animationName) {
  30496. continue;
  30497. }
  30498. animations[index].reset();
  30499. animations.splice(index, 1);
  30500. }
  30501. if (animations.length == 0) {
  30502. this._scene._activeAnimatables.splice(idx, 1);
  30503. if (this.onAnimationEnd) {
  30504. this.onAnimationEnd();
  30505. }
  30506. }
  30507. }
  30508. }
  30509. else {
  30510. var index = this._scene._activeAnimatables.indexOf(this);
  30511. if (index > -1) {
  30512. this._scene._activeAnimatables.splice(index, 1);
  30513. var animations = this._animations;
  30514. for (var index = 0; index < animations.length; index++) {
  30515. animations[index].reset();
  30516. }
  30517. if (this.onAnimationEnd) {
  30518. this.onAnimationEnd();
  30519. }
  30520. }
  30521. }
  30522. };
  30523. Animatable.prototype._animate = function (delay) {
  30524. if (this._paused) {
  30525. this.animationStarted = false;
  30526. if (this._pausedDelay === null) {
  30527. this._pausedDelay = delay;
  30528. }
  30529. return true;
  30530. }
  30531. if (this._localDelayOffset === null) {
  30532. this._localDelayOffset = delay;
  30533. }
  30534. else if (this._pausedDelay !== null) {
  30535. this._localDelayOffset += delay - this._pausedDelay;
  30536. this._pausedDelay = null;
  30537. }
  30538. // Animating
  30539. var running = false;
  30540. var animations = this._animations;
  30541. var index;
  30542. for (index = 0; index < animations.length; index++) {
  30543. var animation = animations[index];
  30544. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  30545. running = running || isRunning;
  30546. }
  30547. this.animationStarted = running;
  30548. if (!running) {
  30549. // Remove from active animatables
  30550. index = this._scene._activeAnimatables.indexOf(this);
  30551. this._scene._activeAnimatables.splice(index, 1);
  30552. }
  30553. if (!running && this.onAnimationEnd) {
  30554. this.onAnimationEnd();
  30555. this.onAnimationEnd = null;
  30556. }
  30557. return running;
  30558. };
  30559. return Animatable;
  30560. }());
  30561. BABYLON.Animatable = Animatable;
  30562. })(BABYLON || (BABYLON = {}));
  30563. //# sourceMappingURL=babylon.animatable.js.map
  30564. var BABYLON;
  30565. (function (BABYLON) {
  30566. var EasingFunction = (function () {
  30567. function EasingFunction() {
  30568. // Properties
  30569. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  30570. }
  30571. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  30572. get: function () {
  30573. return EasingFunction._EASINGMODE_EASEIN;
  30574. },
  30575. enumerable: true,
  30576. configurable: true
  30577. });
  30578. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  30579. get: function () {
  30580. return EasingFunction._EASINGMODE_EASEOUT;
  30581. },
  30582. enumerable: true,
  30583. configurable: true
  30584. });
  30585. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  30586. get: function () {
  30587. return EasingFunction._EASINGMODE_EASEINOUT;
  30588. },
  30589. enumerable: true,
  30590. configurable: true
  30591. });
  30592. EasingFunction.prototype.setEasingMode = function (easingMode) {
  30593. var n = Math.min(Math.max(easingMode, 0), 2);
  30594. this._easingMode = n;
  30595. };
  30596. EasingFunction.prototype.getEasingMode = function () {
  30597. return this._easingMode;
  30598. };
  30599. EasingFunction.prototype.easeInCore = function (gradient) {
  30600. throw new Error('You must implement this method');
  30601. };
  30602. EasingFunction.prototype.ease = function (gradient) {
  30603. switch (this._easingMode) {
  30604. case EasingFunction.EASINGMODE_EASEIN:
  30605. return this.easeInCore(gradient);
  30606. case EasingFunction.EASINGMODE_EASEOUT:
  30607. return (1 - this.easeInCore(1 - gradient));
  30608. }
  30609. if (gradient >= 0.5) {
  30610. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  30611. }
  30612. return (this.easeInCore(gradient * 2) * 0.5);
  30613. };
  30614. //Statics
  30615. EasingFunction._EASINGMODE_EASEIN = 0;
  30616. EasingFunction._EASINGMODE_EASEOUT = 1;
  30617. EasingFunction._EASINGMODE_EASEINOUT = 2;
  30618. return EasingFunction;
  30619. }());
  30620. BABYLON.EasingFunction = EasingFunction;
  30621. var CircleEase = (function (_super) {
  30622. __extends(CircleEase, _super);
  30623. function CircleEase() {
  30624. return _super !== null && _super.apply(this, arguments) || this;
  30625. }
  30626. CircleEase.prototype.easeInCore = function (gradient) {
  30627. gradient = Math.max(0, Math.min(1, gradient));
  30628. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  30629. };
  30630. return CircleEase;
  30631. }(EasingFunction));
  30632. BABYLON.CircleEase = CircleEase;
  30633. var BackEase = (function (_super) {
  30634. __extends(BackEase, _super);
  30635. function BackEase(amplitude) {
  30636. if (amplitude === void 0) { amplitude = 1; }
  30637. var _this = _super.call(this) || this;
  30638. _this.amplitude = amplitude;
  30639. return _this;
  30640. }
  30641. BackEase.prototype.easeInCore = function (gradient) {
  30642. var num = Math.max(0, this.amplitude);
  30643. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  30644. };
  30645. return BackEase;
  30646. }(EasingFunction));
  30647. BABYLON.BackEase = BackEase;
  30648. var BounceEase = (function (_super) {
  30649. __extends(BounceEase, _super);
  30650. function BounceEase(bounces, bounciness) {
  30651. if (bounces === void 0) { bounces = 3; }
  30652. if (bounciness === void 0) { bounciness = 2; }
  30653. var _this = _super.call(this) || this;
  30654. _this.bounces = bounces;
  30655. _this.bounciness = bounciness;
  30656. return _this;
  30657. }
  30658. BounceEase.prototype.easeInCore = function (gradient) {
  30659. var y = Math.max(0.0, this.bounces);
  30660. var bounciness = this.bounciness;
  30661. if (bounciness <= 1.0) {
  30662. bounciness = 1.001;
  30663. }
  30664. var num9 = Math.pow(bounciness, y);
  30665. var num5 = 1.0 - bounciness;
  30666. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  30667. var num15 = gradient * num4;
  30668. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  30669. var num3 = Math.floor(num65);
  30670. var num13 = num3 + 1.0;
  30671. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  30672. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  30673. var num7 = (num8 + num12) * 0.5;
  30674. var num6 = gradient - num7;
  30675. var num2 = num7 - num8;
  30676. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  30677. };
  30678. return BounceEase;
  30679. }(EasingFunction));
  30680. BABYLON.BounceEase = BounceEase;
  30681. var CubicEase = (function (_super) {
  30682. __extends(CubicEase, _super);
  30683. function CubicEase() {
  30684. return _super !== null && _super.apply(this, arguments) || this;
  30685. }
  30686. CubicEase.prototype.easeInCore = function (gradient) {
  30687. return (gradient * gradient * gradient);
  30688. };
  30689. return CubicEase;
  30690. }(EasingFunction));
  30691. BABYLON.CubicEase = CubicEase;
  30692. var ElasticEase = (function (_super) {
  30693. __extends(ElasticEase, _super);
  30694. function ElasticEase(oscillations, springiness) {
  30695. if (oscillations === void 0) { oscillations = 3; }
  30696. if (springiness === void 0) { springiness = 3; }
  30697. var _this = _super.call(this) || this;
  30698. _this.oscillations = oscillations;
  30699. _this.springiness = springiness;
  30700. return _this;
  30701. }
  30702. ElasticEase.prototype.easeInCore = function (gradient) {
  30703. var num2;
  30704. var num3 = Math.max(0.0, this.oscillations);
  30705. var num = Math.max(0.0, this.springiness);
  30706. if (num == 0) {
  30707. num2 = gradient;
  30708. }
  30709. else {
  30710. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  30711. }
  30712. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  30713. };
  30714. return ElasticEase;
  30715. }(EasingFunction));
  30716. BABYLON.ElasticEase = ElasticEase;
  30717. var ExponentialEase = (function (_super) {
  30718. __extends(ExponentialEase, _super);
  30719. function ExponentialEase(exponent) {
  30720. if (exponent === void 0) { exponent = 2; }
  30721. var _this = _super.call(this) || this;
  30722. _this.exponent = exponent;
  30723. return _this;
  30724. }
  30725. ExponentialEase.prototype.easeInCore = function (gradient) {
  30726. if (this.exponent <= 0) {
  30727. return gradient;
  30728. }
  30729. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30730. };
  30731. return ExponentialEase;
  30732. }(EasingFunction));
  30733. BABYLON.ExponentialEase = ExponentialEase;
  30734. var PowerEase = (function (_super) {
  30735. __extends(PowerEase, _super);
  30736. function PowerEase(power) {
  30737. if (power === void 0) { power = 2; }
  30738. var _this = _super.call(this) || this;
  30739. _this.power = power;
  30740. return _this;
  30741. }
  30742. PowerEase.prototype.easeInCore = function (gradient) {
  30743. var y = Math.max(0.0, this.power);
  30744. return Math.pow(gradient, y);
  30745. };
  30746. return PowerEase;
  30747. }(EasingFunction));
  30748. BABYLON.PowerEase = PowerEase;
  30749. var QuadraticEase = (function (_super) {
  30750. __extends(QuadraticEase, _super);
  30751. function QuadraticEase() {
  30752. return _super !== null && _super.apply(this, arguments) || this;
  30753. }
  30754. QuadraticEase.prototype.easeInCore = function (gradient) {
  30755. return (gradient * gradient);
  30756. };
  30757. return QuadraticEase;
  30758. }(EasingFunction));
  30759. BABYLON.QuadraticEase = QuadraticEase;
  30760. var QuarticEase = (function (_super) {
  30761. __extends(QuarticEase, _super);
  30762. function QuarticEase() {
  30763. return _super !== null && _super.apply(this, arguments) || this;
  30764. }
  30765. QuarticEase.prototype.easeInCore = function (gradient) {
  30766. return (gradient * gradient * gradient * gradient);
  30767. };
  30768. return QuarticEase;
  30769. }(EasingFunction));
  30770. BABYLON.QuarticEase = QuarticEase;
  30771. var QuinticEase = (function (_super) {
  30772. __extends(QuinticEase, _super);
  30773. function QuinticEase() {
  30774. return _super !== null && _super.apply(this, arguments) || this;
  30775. }
  30776. QuinticEase.prototype.easeInCore = function (gradient) {
  30777. return (gradient * gradient * gradient * gradient * gradient);
  30778. };
  30779. return QuinticEase;
  30780. }(EasingFunction));
  30781. BABYLON.QuinticEase = QuinticEase;
  30782. var SineEase = (function (_super) {
  30783. __extends(SineEase, _super);
  30784. function SineEase() {
  30785. return _super !== null && _super.apply(this, arguments) || this;
  30786. }
  30787. SineEase.prototype.easeInCore = function (gradient) {
  30788. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30789. };
  30790. return SineEase;
  30791. }(EasingFunction));
  30792. BABYLON.SineEase = SineEase;
  30793. var BezierCurveEase = (function (_super) {
  30794. __extends(BezierCurveEase, _super);
  30795. function BezierCurveEase(x1, y1, x2, y2) {
  30796. if (x1 === void 0) { x1 = 0; }
  30797. if (y1 === void 0) { y1 = 0; }
  30798. if (x2 === void 0) { x2 = 1; }
  30799. if (y2 === void 0) { y2 = 1; }
  30800. var _this = _super.call(this) || this;
  30801. _this.x1 = x1;
  30802. _this.y1 = y1;
  30803. _this.x2 = x2;
  30804. _this.y2 = y2;
  30805. return _this;
  30806. }
  30807. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30808. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30809. };
  30810. return BezierCurveEase;
  30811. }(EasingFunction));
  30812. BABYLON.BezierCurveEase = BezierCurveEase;
  30813. })(BABYLON || (BABYLON = {}));
  30814. //# sourceMappingURL=babylon.easing.js.map
  30815. var BABYLON;
  30816. (function (BABYLON) {
  30817. BABYLON.CameraInputTypes = {};
  30818. var CameraInputsManager = (function () {
  30819. function CameraInputsManager(camera) {
  30820. this.attached = {};
  30821. this.camera = camera;
  30822. this.checkInputs = function () { };
  30823. }
  30824. CameraInputsManager.prototype.add = function (input) {
  30825. var type = input.getSimpleName();
  30826. if (this.attached[type]) {
  30827. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  30828. return;
  30829. }
  30830. this.attached[type] = input;
  30831. input.camera = this.camera;
  30832. //for checkInputs, we are dynamically creating a function
  30833. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  30834. if (input.checkInputs) {
  30835. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  30836. }
  30837. if (this.attachedElement) {
  30838. input.attachControl(this.attachedElement);
  30839. }
  30840. };
  30841. CameraInputsManager.prototype.remove = function (inputToRemove) {
  30842. for (var cam in this.attached) {
  30843. var input = this.attached[cam];
  30844. if (input === inputToRemove) {
  30845. input.detachControl(this.attachedElement);
  30846. input.camera = null;
  30847. delete this.attached[cam];
  30848. this.rebuildInputCheck();
  30849. }
  30850. }
  30851. };
  30852. CameraInputsManager.prototype.removeByType = function (inputType) {
  30853. for (var cam in this.attached) {
  30854. var input = this.attached[cam];
  30855. if (input.getClassName() === inputType) {
  30856. input.detachControl(this.attachedElement);
  30857. input.camera = null;
  30858. delete this.attached[cam];
  30859. this.rebuildInputCheck();
  30860. }
  30861. }
  30862. };
  30863. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  30864. var current = this.checkInputs;
  30865. return function () {
  30866. current();
  30867. fn();
  30868. };
  30869. };
  30870. CameraInputsManager.prototype.attachInput = function (input) {
  30871. input.attachControl(this.attachedElement, this.noPreventDefault);
  30872. };
  30873. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  30874. if (this.attachedElement) {
  30875. return;
  30876. }
  30877. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  30878. this.attachedElement = element;
  30879. this.noPreventDefault = noPreventDefault;
  30880. for (var cam in this.attached) {
  30881. var input = this.attached[cam];
  30882. this.attached[cam].attachControl(element, noPreventDefault);
  30883. }
  30884. };
  30885. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  30886. if (disconnect === void 0) { disconnect = false; }
  30887. if (this.attachedElement !== element) {
  30888. return;
  30889. }
  30890. for (var cam in this.attached) {
  30891. var input = this.attached[cam];
  30892. this.attached[cam].detachControl(element);
  30893. if (disconnect) {
  30894. this.attached[cam].camera = null;
  30895. }
  30896. }
  30897. this.attachedElement = null;
  30898. };
  30899. CameraInputsManager.prototype.rebuildInputCheck = function () {
  30900. this.checkInputs = function () { };
  30901. for (var cam in this.attached) {
  30902. var input = this.attached[cam];
  30903. if (input.checkInputs) {
  30904. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  30905. }
  30906. }
  30907. };
  30908. CameraInputsManager.prototype.clear = function () {
  30909. if (this.attachedElement) {
  30910. this.detachElement(this.attachedElement, true);
  30911. }
  30912. this.attached = {};
  30913. this.attachedElement = null;
  30914. this.checkInputs = function () { };
  30915. };
  30916. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  30917. var inputs = {};
  30918. for (var cam in this.attached) {
  30919. var input = this.attached[cam];
  30920. var res = BABYLON.SerializationHelper.Serialize(input);
  30921. inputs[input.getClassName()] = res;
  30922. }
  30923. serializedCamera.inputsmgr = inputs;
  30924. };
  30925. CameraInputsManager.prototype.parse = function (parsedCamera) {
  30926. var parsedInputs = parsedCamera.inputsmgr;
  30927. if (parsedInputs) {
  30928. this.clear();
  30929. for (var n in parsedInputs) {
  30930. var construct = BABYLON.CameraInputTypes[n];
  30931. if (construct) {
  30932. var parsedinput = parsedInputs[n];
  30933. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  30934. this.add(input);
  30935. }
  30936. }
  30937. }
  30938. else {
  30939. //2016-03-08 this part is for managing backward compatibility
  30940. for (var n in this.attached) {
  30941. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  30942. if (construct) {
  30943. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  30944. this.remove(this.attached[n]);
  30945. this.add(input);
  30946. }
  30947. }
  30948. }
  30949. };
  30950. return CameraInputsManager;
  30951. }());
  30952. BABYLON.CameraInputsManager = CameraInputsManager;
  30953. })(BABYLON || (BABYLON = {}));
  30954. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  30955. /// <reference path="babylon.camera.ts" />
  30956. var BABYLON;
  30957. (function (BABYLON) {
  30958. var TargetCamera = (function (_super) {
  30959. __extends(TargetCamera, _super);
  30960. function TargetCamera(name, position, scene) {
  30961. var _this = _super.call(this, name, position, scene) || this;
  30962. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  30963. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  30964. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  30965. _this.speed = 2.0;
  30966. _this.noRotationConstraint = false;
  30967. _this.lockedTarget = null;
  30968. _this._currentTarget = BABYLON.Vector3.Zero();
  30969. _this._viewMatrix = BABYLON.Matrix.Zero();
  30970. _this._camMatrix = BABYLON.Matrix.Zero();
  30971. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  30972. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  30973. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  30974. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  30975. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  30976. _this._lookAtTemp = BABYLON.Matrix.Zero();
  30977. _this._tempMatrix = BABYLON.Matrix.Zero();
  30978. return _this;
  30979. }
  30980. TargetCamera.prototype.getFrontPosition = function (distance) {
  30981. var direction = this.getTarget().subtract(this.position);
  30982. direction.normalize();
  30983. direction.scaleInPlace(distance);
  30984. return this.globalPosition.add(direction);
  30985. };
  30986. TargetCamera.prototype._getLockedTargetPosition = function () {
  30987. if (!this.lockedTarget) {
  30988. return null;
  30989. }
  30990. if (this.lockedTarget.absolutePosition) {
  30991. this.lockedTarget.computeWorldMatrix();
  30992. }
  30993. return this.lockedTarget.absolutePosition || this.lockedTarget;
  30994. };
  30995. // Cache
  30996. TargetCamera.prototype._initCache = function () {
  30997. _super.prototype._initCache.call(this);
  30998. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30999. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31000. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31001. };
  31002. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31003. if (!ignoreParentClass) {
  31004. _super.prototype._updateCache.call(this);
  31005. }
  31006. var lockedTargetPosition = this._getLockedTargetPosition();
  31007. if (!lockedTargetPosition) {
  31008. this._cache.lockedTarget = null;
  31009. }
  31010. else {
  31011. if (!this._cache.lockedTarget) {
  31012. this._cache.lockedTarget = lockedTargetPosition.clone();
  31013. }
  31014. else {
  31015. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31016. }
  31017. }
  31018. this._cache.rotation.copyFrom(this.rotation);
  31019. if (this.rotationQuaternion)
  31020. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31021. };
  31022. // Synchronized
  31023. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31024. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31025. return false;
  31026. }
  31027. var lockedTargetPosition = this._getLockedTargetPosition();
  31028. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31029. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31030. };
  31031. // Methods
  31032. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31033. var engine = this.getEngine();
  31034. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31035. };
  31036. // Target
  31037. TargetCamera.prototype.setTarget = function (target) {
  31038. this.upVector.normalize();
  31039. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31040. this._camMatrix.invert();
  31041. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31042. var vDir = target.subtract(this.position);
  31043. if (vDir.x >= 0.0) {
  31044. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31045. }
  31046. else {
  31047. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31048. }
  31049. this.rotation.z = 0;
  31050. if (isNaN(this.rotation.x)) {
  31051. this.rotation.x = 0;
  31052. }
  31053. if (isNaN(this.rotation.y)) {
  31054. this.rotation.y = 0;
  31055. }
  31056. if (isNaN(this.rotation.z)) {
  31057. this.rotation.z = 0;
  31058. }
  31059. if (this.rotationQuaternion) {
  31060. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31061. }
  31062. };
  31063. /**
  31064. * Return the current target position of the camera. This value is expressed in local space.
  31065. */
  31066. TargetCamera.prototype.getTarget = function () {
  31067. return this._currentTarget;
  31068. };
  31069. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31070. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31071. };
  31072. TargetCamera.prototype._updatePosition = function () {
  31073. if (this.parent) {
  31074. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31075. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31076. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31077. return;
  31078. }
  31079. this.position.addInPlace(this.cameraDirection);
  31080. };
  31081. TargetCamera.prototype._checkInputs = function () {
  31082. var needToMove = this._decideIfNeedsToMove();
  31083. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31084. // Move
  31085. if (needToMove) {
  31086. this._updatePosition();
  31087. }
  31088. // Rotate
  31089. if (needToRotate) {
  31090. this.rotation.x += this.cameraRotation.x;
  31091. this.rotation.y += this.cameraRotation.y;
  31092. //rotate, if quaternion is set and rotation was used
  31093. if (this.rotationQuaternion) {
  31094. var len = this.rotation.lengthSquared();
  31095. if (len) {
  31096. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31097. }
  31098. }
  31099. if (!this.noRotationConstraint) {
  31100. var limit = (Math.PI / 2) * 0.95;
  31101. if (this.rotation.x > limit)
  31102. this.rotation.x = limit;
  31103. if (this.rotation.x < -limit)
  31104. this.rotation.x = -limit;
  31105. }
  31106. }
  31107. // Inertia
  31108. if (needToMove) {
  31109. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31110. this.cameraDirection.x = 0;
  31111. }
  31112. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31113. this.cameraDirection.y = 0;
  31114. }
  31115. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31116. this.cameraDirection.z = 0;
  31117. }
  31118. this.cameraDirection.scaleInPlace(this.inertia);
  31119. }
  31120. if (needToRotate) {
  31121. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31122. this.cameraRotation.x = 0;
  31123. }
  31124. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31125. this.cameraRotation.y = 0;
  31126. }
  31127. this.cameraRotation.scaleInPlace(this.inertia);
  31128. }
  31129. _super.prototype._checkInputs.call(this);
  31130. };
  31131. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31132. if (this.rotationQuaternion) {
  31133. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31134. //update the up vector!
  31135. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31136. }
  31137. else {
  31138. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31139. }
  31140. };
  31141. TargetCamera.prototype._getViewMatrix = function () {
  31142. if (!this.lockedTarget) {
  31143. // Compute
  31144. this._updateCameraRotationMatrix();
  31145. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31146. // Computing target and final matrix
  31147. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  31148. }
  31149. else {
  31150. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  31151. }
  31152. if (this.getScene().useRightHandedSystem) {
  31153. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31154. }
  31155. else {
  31156. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31157. }
  31158. return this._viewMatrix;
  31159. };
  31160. /**
  31161. * @override
  31162. * Override Camera.createRigCamera
  31163. */
  31164. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31165. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  31166. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  31167. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  31168. if (!this.rotationQuaternion) {
  31169. this.rotationQuaternion = new BABYLON.Quaternion();
  31170. }
  31171. rigCamera._cameraRigParams = {};
  31172. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  31173. }
  31174. return rigCamera;
  31175. }
  31176. return null;
  31177. };
  31178. /**
  31179. * @override
  31180. * Override Camera._updateRigCameras
  31181. */
  31182. TargetCamera.prototype._updateRigCameras = function () {
  31183. var camLeft = this._rigCameras[0];
  31184. var camRight = this._rigCameras[1];
  31185. switch (this.cameraRigMode) {
  31186. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31187. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31188. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31189. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31190. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  31191. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  31192. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  31193. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  31194. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  31195. camLeft.setTarget(this.getTarget());
  31196. camRight.setTarget(this.getTarget());
  31197. break;
  31198. case BABYLON.Camera.RIG_MODE_VR:
  31199. if (camLeft.rotationQuaternion) {
  31200. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31201. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31202. }
  31203. else {
  31204. camLeft.rotation.copyFrom(this.rotation);
  31205. camRight.rotation.copyFrom(this.rotation);
  31206. }
  31207. camLeft.position.copyFrom(this.position);
  31208. camRight.position.copyFrom(this.position);
  31209. break;
  31210. }
  31211. _super.prototype._updateRigCameras.call(this);
  31212. };
  31213. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  31214. if (!this._rigCamTransformMatrix) {
  31215. this._rigCamTransformMatrix = new BABYLON.Matrix();
  31216. }
  31217. var target = this.getTarget();
  31218. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  31219. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  31220. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  31221. };
  31222. TargetCamera.prototype.getClassName = function () {
  31223. return "TargetCamera";
  31224. };
  31225. __decorate([
  31226. BABYLON.serializeAsVector3()
  31227. ], TargetCamera.prototype, "rotation", void 0);
  31228. __decorate([
  31229. BABYLON.serialize()
  31230. ], TargetCamera.prototype, "speed", void 0);
  31231. __decorate([
  31232. BABYLON.serializeAsMeshReference("lockedTargetId")
  31233. ], TargetCamera.prototype, "lockedTarget", void 0);
  31234. return TargetCamera;
  31235. }(BABYLON.Camera));
  31236. BABYLON.TargetCamera = TargetCamera;
  31237. })(BABYLON || (BABYLON = {}));
  31238. //# sourceMappingURL=babylon.targetCamera.js.map
  31239. var BABYLON;
  31240. (function (BABYLON) {
  31241. var ArcRotateCameraKeyboardMoveInput = (function () {
  31242. function ArcRotateCameraKeyboardMoveInput() {
  31243. this._keys = [];
  31244. this.keysUp = [38];
  31245. this.keysDown = [40];
  31246. this.keysLeft = [37];
  31247. this.keysRight = [39];
  31248. }
  31249. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31250. var _this = this;
  31251. element.tabIndex = 1;
  31252. this._onKeyDown = function (evt) {
  31253. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31254. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31255. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31256. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31257. var index = _this._keys.indexOf(evt.keyCode);
  31258. if (index === -1) {
  31259. _this._keys.push(evt.keyCode);
  31260. }
  31261. if (evt.preventDefault) {
  31262. if (!noPreventDefault) {
  31263. evt.preventDefault();
  31264. }
  31265. }
  31266. }
  31267. };
  31268. this._onKeyUp = function (evt) {
  31269. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31270. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31271. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31272. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31273. var index = _this._keys.indexOf(evt.keyCode);
  31274. if (index >= 0) {
  31275. _this._keys.splice(index, 1);
  31276. }
  31277. if (evt.preventDefault) {
  31278. if (!noPreventDefault) {
  31279. evt.preventDefault();
  31280. }
  31281. }
  31282. }
  31283. };
  31284. this._onLostFocus = function () {
  31285. _this._keys = [];
  31286. };
  31287. element.addEventListener("keydown", this._onKeyDown, false);
  31288. element.addEventListener("keyup", this._onKeyUp, false);
  31289. BABYLON.Tools.RegisterTopRootEvents([
  31290. { name: "blur", handler: this._onLostFocus }
  31291. ]);
  31292. };
  31293. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31294. if (element) {
  31295. element.removeEventListener("keydown", this._onKeyDown);
  31296. element.removeEventListener("keyup", this._onKeyUp);
  31297. }
  31298. BABYLON.Tools.UnregisterTopRootEvents([
  31299. { name: "blur", handler: this._onLostFocus }
  31300. ]);
  31301. this._keys = [];
  31302. this._onKeyDown = null;
  31303. this._onKeyUp = null;
  31304. this._onLostFocus = null;
  31305. };
  31306. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31307. if (this._onKeyDown) {
  31308. var camera = this.camera;
  31309. for (var index = 0; index < this._keys.length; index++) {
  31310. var keyCode = this._keys[index];
  31311. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31312. camera.inertialAlphaOffset -= 0.01;
  31313. }
  31314. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31315. camera.inertialBetaOffset -= 0.01;
  31316. }
  31317. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31318. camera.inertialAlphaOffset += 0.01;
  31319. }
  31320. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31321. camera.inertialBetaOffset += 0.01;
  31322. }
  31323. }
  31324. }
  31325. };
  31326. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  31327. return "ArcRotateCameraKeyboardMoveInput";
  31328. };
  31329. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31330. return "keyboard";
  31331. };
  31332. __decorate([
  31333. BABYLON.serialize()
  31334. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  31335. __decorate([
  31336. BABYLON.serialize()
  31337. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  31338. __decorate([
  31339. BABYLON.serialize()
  31340. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  31341. __decorate([
  31342. BABYLON.serialize()
  31343. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  31344. return ArcRotateCameraKeyboardMoveInput;
  31345. }());
  31346. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  31347. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  31348. })(BABYLON || (BABYLON = {}));
  31349. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  31350. var BABYLON;
  31351. (function (BABYLON) {
  31352. var ArcRotateCameraMouseWheelInput = (function () {
  31353. function ArcRotateCameraMouseWheelInput() {
  31354. this.wheelPrecision = 3.0;
  31355. }
  31356. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  31357. var _this = this;
  31358. this._wheel = function (p, s) {
  31359. //sanity check - this should be a PointerWheel event.
  31360. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  31361. return;
  31362. var event = p.event;
  31363. var delta = 0;
  31364. if (event.wheelDelta) {
  31365. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  31366. }
  31367. else if (event.detail) {
  31368. delta = -event.detail / _this.wheelPrecision;
  31369. }
  31370. if (delta)
  31371. _this.camera.inertialRadiusOffset += delta;
  31372. if (event.preventDefault) {
  31373. if (!noPreventDefault) {
  31374. event.preventDefault();
  31375. }
  31376. }
  31377. };
  31378. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  31379. };
  31380. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  31381. if (this._observer && element) {
  31382. this.camera.getScene().onPointerObservable.remove(this._observer);
  31383. this._observer = null;
  31384. this._wheel = null;
  31385. }
  31386. };
  31387. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  31388. return "ArcRotateCameraMouseWheelInput";
  31389. };
  31390. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  31391. return "mousewheel";
  31392. };
  31393. __decorate([
  31394. BABYLON.serialize()
  31395. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  31396. return ArcRotateCameraMouseWheelInput;
  31397. }());
  31398. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  31399. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  31400. })(BABYLON || (BABYLON = {}));
  31401. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  31402. var BABYLON;
  31403. (function (BABYLON) {
  31404. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  31405. var ArcRotateCameraPointersInput = (function () {
  31406. function ArcRotateCameraPointersInput() {
  31407. this.buttons = [0, 1, 2];
  31408. this.angularSensibilityX = 1000.0;
  31409. this.angularSensibilityY = 1000.0;
  31410. this.pinchPrecision = 6.0;
  31411. this.panningSensibility = 50.0;
  31412. this._isPanClick = false;
  31413. this.pinchInwards = true;
  31414. }
  31415. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  31416. var _this = this;
  31417. var engine = this.camera.getEngine();
  31418. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  31419. var pointA, pointB;
  31420. var previousPinchDistance = 0;
  31421. this._pointerInput = function (p, s) {
  31422. var evt = p.event;
  31423. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31424. return;
  31425. }
  31426. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31427. try {
  31428. evt.srcElement.setPointerCapture(evt.pointerId);
  31429. }
  31430. catch (e) {
  31431. //Nothing to do with the error. Execution will continue.
  31432. }
  31433. // Manage panning with pan button click
  31434. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  31435. // manage pointers
  31436. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  31437. if (pointA === undefined) {
  31438. pointA = cacheSoloPointer;
  31439. }
  31440. else if (pointB === undefined) {
  31441. pointB = cacheSoloPointer;
  31442. }
  31443. if (!noPreventDefault) {
  31444. evt.preventDefault();
  31445. element.focus();
  31446. }
  31447. }
  31448. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  31449. try {
  31450. evt.srcElement.releasePointerCapture(evt.pointerId);
  31451. }
  31452. catch (e) {
  31453. //Nothing to do with the error.
  31454. }
  31455. cacheSoloPointer = null;
  31456. previousPinchDistance = 0;
  31457. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  31458. //but emptying completly pointers collection is required to fix a bug on iPhone :
  31459. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  31460. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  31461. pointA = pointB = undefined;
  31462. if (!noPreventDefault) {
  31463. evt.preventDefault();
  31464. }
  31465. }
  31466. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  31467. if (!noPreventDefault) {
  31468. evt.preventDefault();
  31469. }
  31470. // One button down
  31471. if (pointA && pointB === undefined) {
  31472. if (_this.panningSensibility !== 0 &&
  31473. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  31474. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  31475. _this.camera
  31476. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  31477. _this.camera
  31478. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  31479. }
  31480. else {
  31481. var offsetX = evt.clientX - cacheSoloPointer.x;
  31482. var offsetY = evt.clientY - cacheSoloPointer.y;
  31483. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31484. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31485. }
  31486. cacheSoloPointer.x = evt.clientX;
  31487. cacheSoloPointer.y = evt.clientY;
  31488. }
  31489. else if (pointA && pointB) {
  31490. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  31491. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  31492. ed.x = evt.clientX;
  31493. ed.y = evt.clientY;
  31494. var direction = _this.pinchInwards ? 1 : -1;
  31495. var distX = pointA.x - pointB.x;
  31496. var distY = pointA.y - pointB.y;
  31497. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  31498. if (previousPinchDistance === 0) {
  31499. previousPinchDistance = pinchSquaredDistance;
  31500. return;
  31501. }
  31502. if (pinchSquaredDistance !== previousPinchDistance) {
  31503. _this.camera
  31504. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  31505. (_this.pinchPrecision *
  31506. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  31507. direction);
  31508. previousPinchDistance = pinchSquaredDistance;
  31509. }
  31510. }
  31511. }
  31512. };
  31513. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  31514. this._onContextMenu = function (evt) {
  31515. evt.preventDefault();
  31516. };
  31517. if (!this.camera._useCtrlForPanning) {
  31518. element.addEventListener("contextmenu", this._onContextMenu, false);
  31519. }
  31520. this._onLostFocus = function () {
  31521. //this._keys = [];
  31522. pointA = pointB = undefined;
  31523. previousPinchDistance = 0;
  31524. cacheSoloPointer = null;
  31525. };
  31526. this._onMouseMove = function (evt) {
  31527. if (!engine.isPointerLock) {
  31528. return;
  31529. }
  31530. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  31531. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  31532. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31533. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31534. if (!noPreventDefault) {
  31535. evt.preventDefault();
  31536. }
  31537. };
  31538. this._onGestureStart = function (e) {
  31539. if (window.MSGesture === undefined) {
  31540. return;
  31541. }
  31542. if (!_this._MSGestureHandler) {
  31543. _this._MSGestureHandler = new MSGesture();
  31544. _this._MSGestureHandler.target = element;
  31545. }
  31546. _this._MSGestureHandler.addPointer(e.pointerId);
  31547. };
  31548. this._onGesture = function (e) {
  31549. _this.camera.radius *= e.scale;
  31550. if (e.preventDefault) {
  31551. if (!noPreventDefault) {
  31552. e.stopPropagation();
  31553. e.preventDefault();
  31554. }
  31555. }
  31556. };
  31557. element.addEventListener("mousemove", this._onMouseMove, false);
  31558. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  31559. element.addEventListener("MSGestureChange", this._onGesture, false);
  31560. BABYLON.Tools.RegisterTopRootEvents([
  31561. { name: "blur", handler: this._onLostFocus }
  31562. ]);
  31563. };
  31564. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  31565. BABYLON.Tools.UnregisterTopRootEvents([
  31566. { name: "blur", handler: this._onLostFocus }
  31567. ]);
  31568. if (element && this._observer) {
  31569. this.camera.getScene().onPointerObservable.remove(this._observer);
  31570. this._observer = null;
  31571. element.removeEventListener("contextmenu", this._onContextMenu);
  31572. element.removeEventListener("mousemove", this._onMouseMove);
  31573. element.removeEventListener("MSPointerDown", this._onGestureStart);
  31574. element.removeEventListener("MSGestureChange", this._onGesture);
  31575. this._isPanClick = false;
  31576. this.pinchInwards = true;
  31577. this._onMouseMove = null;
  31578. this._onGestureStart = null;
  31579. this._onGesture = null;
  31580. this._MSGestureHandler = null;
  31581. this._onLostFocus = null;
  31582. this._onContextMenu = null;
  31583. }
  31584. };
  31585. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  31586. return "ArcRotateCameraPointersInput";
  31587. };
  31588. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  31589. return "pointers";
  31590. };
  31591. __decorate([
  31592. BABYLON.serialize()
  31593. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  31594. __decorate([
  31595. BABYLON.serialize()
  31596. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  31597. __decorate([
  31598. BABYLON.serialize()
  31599. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  31600. __decorate([
  31601. BABYLON.serialize()
  31602. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  31603. __decorate([
  31604. BABYLON.serialize()
  31605. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  31606. return ArcRotateCameraPointersInput;
  31607. }());
  31608. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  31609. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  31610. })(BABYLON || (BABYLON = {}));
  31611. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  31612. /// <reference path="babylon.targetCamera.ts" />
  31613. /// <reference path="..\Tools\babylon.tools.ts" />
  31614. var BABYLON;
  31615. (function (BABYLON) {
  31616. var ArcRotateCamera = (function (_super) {
  31617. __extends(ArcRotateCamera, _super);
  31618. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  31619. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  31620. _this.inertialAlphaOffset = 0;
  31621. _this.inertialBetaOffset = 0;
  31622. _this.inertialRadiusOffset = 0;
  31623. _this.lowerAlphaLimit = null;
  31624. _this.upperAlphaLimit = null;
  31625. _this.lowerBetaLimit = 0.01;
  31626. _this.upperBetaLimit = Math.PI;
  31627. _this.lowerRadiusLimit = null;
  31628. _this.upperRadiusLimit = null;
  31629. _this.inertialPanningX = 0;
  31630. _this.inertialPanningY = 0;
  31631. _this.panningInertia = 0.9;
  31632. //-- end properties for backward compatibility for inputs
  31633. _this.zoomOnFactor = 1;
  31634. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  31635. _this.allowUpsideDown = true;
  31636. _this._viewMatrix = new BABYLON.Matrix();
  31637. // Panning
  31638. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  31639. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  31640. _this.checkCollisions = false;
  31641. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  31642. _this._previousPosition = BABYLON.Vector3.Zero();
  31643. _this._collisionVelocity = BABYLON.Vector3.Zero();
  31644. _this._newPosition = BABYLON.Vector3.Zero();
  31645. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  31646. if (collidedMesh === void 0) { collidedMesh = null; }
  31647. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  31648. newPosition.multiplyInPlace(_this._collider.radius);
  31649. }
  31650. if (!collidedMesh) {
  31651. _this._previousPosition.copyFrom(_this.position);
  31652. }
  31653. else {
  31654. _this.setPosition(newPosition);
  31655. if (_this.onCollide) {
  31656. _this.onCollide(collidedMesh);
  31657. }
  31658. }
  31659. // Recompute because of constraints
  31660. var cosa = Math.cos(_this.alpha);
  31661. var sina = Math.sin(_this.alpha);
  31662. var cosb = Math.cos(_this.beta);
  31663. var sinb = Math.sin(_this.beta);
  31664. if (sinb === 0) {
  31665. sinb = 0.0001;
  31666. }
  31667. var target = _this._getTargetPosition();
  31668. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  31669. _this.position.copyFrom(_this._newPosition);
  31670. var up = _this.upVector;
  31671. if (_this.allowUpsideDown && _this.beta < 0) {
  31672. up = up.clone();
  31673. up = up.negate();
  31674. }
  31675. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  31676. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  31677. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  31678. _this._collisionTriggered = false;
  31679. };
  31680. _this._target = BABYLON.Vector3.Zero();
  31681. if (target) {
  31682. _this.setTarget(target);
  31683. }
  31684. _this.alpha = alpha;
  31685. _this.beta = beta;
  31686. _this.radius = radius;
  31687. _this.getViewMatrix();
  31688. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  31689. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  31690. return _this;
  31691. }
  31692. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  31693. get: function () {
  31694. return this._target;
  31695. },
  31696. set: function (value) {
  31697. this.setTarget(value);
  31698. },
  31699. enumerable: true,
  31700. configurable: true
  31701. });
  31702. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  31703. //-- begin properties for backward compatibility for inputs
  31704. get: function () {
  31705. var pointers = this.inputs.attached["pointers"];
  31706. if (pointers)
  31707. return pointers.angularSensibilityX;
  31708. },
  31709. set: function (value) {
  31710. var pointers = this.inputs.attached["pointers"];
  31711. if (pointers) {
  31712. pointers.angularSensibilityX = value;
  31713. }
  31714. },
  31715. enumerable: true,
  31716. configurable: true
  31717. });
  31718. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  31719. get: function () {
  31720. var pointers = this.inputs.attached["pointers"];
  31721. if (pointers)
  31722. return pointers.angularSensibilityY;
  31723. },
  31724. set: function (value) {
  31725. var pointers = this.inputs.attached["pointers"];
  31726. if (pointers) {
  31727. pointers.angularSensibilityY = value;
  31728. }
  31729. },
  31730. enumerable: true,
  31731. configurable: true
  31732. });
  31733. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  31734. get: function () {
  31735. var pointers = this.inputs.attached["pointers"];
  31736. if (pointers)
  31737. return pointers.pinchPrecision;
  31738. },
  31739. set: function (value) {
  31740. var pointers = this.inputs.attached["pointers"];
  31741. if (pointers) {
  31742. pointers.pinchPrecision = value;
  31743. }
  31744. },
  31745. enumerable: true,
  31746. configurable: true
  31747. });
  31748. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  31749. get: function () {
  31750. var pointers = this.inputs.attached["pointers"];
  31751. if (pointers)
  31752. return pointers.panningSensibility;
  31753. },
  31754. set: function (value) {
  31755. var pointers = this.inputs.attached["pointers"];
  31756. if (pointers) {
  31757. pointers.panningSensibility = value;
  31758. }
  31759. },
  31760. enumerable: true,
  31761. configurable: true
  31762. });
  31763. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  31764. get: function () {
  31765. var keyboard = this.inputs.attached["keyboard"];
  31766. if (keyboard)
  31767. return keyboard.keysUp;
  31768. },
  31769. set: function (value) {
  31770. var keyboard = this.inputs.attached["keyboard"];
  31771. if (keyboard)
  31772. keyboard.keysUp = value;
  31773. },
  31774. enumerable: true,
  31775. configurable: true
  31776. });
  31777. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  31778. get: function () {
  31779. var keyboard = this.inputs.attached["keyboard"];
  31780. if (keyboard)
  31781. return keyboard.keysDown;
  31782. },
  31783. set: function (value) {
  31784. var keyboard = this.inputs.attached["keyboard"];
  31785. if (keyboard)
  31786. keyboard.keysDown = value;
  31787. },
  31788. enumerable: true,
  31789. configurable: true
  31790. });
  31791. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  31792. get: function () {
  31793. var keyboard = this.inputs.attached["keyboard"];
  31794. if (keyboard)
  31795. return keyboard.keysLeft;
  31796. },
  31797. set: function (value) {
  31798. var keyboard = this.inputs.attached["keyboard"];
  31799. if (keyboard)
  31800. keyboard.keysLeft = value;
  31801. },
  31802. enumerable: true,
  31803. configurable: true
  31804. });
  31805. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  31806. get: function () {
  31807. var keyboard = this.inputs.attached["keyboard"];
  31808. if (keyboard)
  31809. return keyboard.keysRight;
  31810. },
  31811. set: function (value) {
  31812. var keyboard = this.inputs.attached["keyboard"];
  31813. if (keyboard)
  31814. keyboard.keysRight = value;
  31815. },
  31816. enumerable: true,
  31817. configurable: true
  31818. });
  31819. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  31820. get: function () {
  31821. var mousewheel = this.inputs.attached["mousewheel"];
  31822. if (mousewheel)
  31823. return mousewheel.wheelPrecision;
  31824. },
  31825. set: function (value) {
  31826. var mousewheel = this.inputs.attached["mousewheel"];
  31827. if (mousewheel)
  31828. mousewheel.wheelPrecision = value;
  31829. },
  31830. enumerable: true,
  31831. configurable: true
  31832. });
  31833. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  31834. get: function () {
  31835. return this._bouncingBehavior != null;
  31836. },
  31837. set: function (value) {
  31838. if (value === this.useBouncingBehavior) {
  31839. return;
  31840. }
  31841. if (value) {
  31842. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  31843. this.addBehavior(this._bouncingBehavior);
  31844. }
  31845. else {
  31846. this.removeBehavior(this._bouncingBehavior);
  31847. this._bouncingBehavior = null;
  31848. }
  31849. },
  31850. enumerable: true,
  31851. configurable: true
  31852. });
  31853. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  31854. get: function () {
  31855. return this._framingBehavior != null;
  31856. },
  31857. set: function (value) {
  31858. if (value === this.useFramingBehavior) {
  31859. return;
  31860. }
  31861. if (value) {
  31862. this._framingBehavior = new BABYLON.FramingBehavior();
  31863. this.addBehavior(this._framingBehavior);
  31864. }
  31865. else {
  31866. this.removeBehavior(this._framingBehavior);
  31867. this._framingBehavior = null;
  31868. }
  31869. },
  31870. enumerable: true,
  31871. configurable: true
  31872. });
  31873. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  31874. get: function () {
  31875. return this._autoRotationBehavior != null;
  31876. },
  31877. set: function (value) {
  31878. if (value === this.useAutoRotationBehavior) {
  31879. return;
  31880. }
  31881. if (value) {
  31882. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  31883. this.addBehavior(this._autoRotationBehavior);
  31884. }
  31885. else {
  31886. this.removeBehavior(this._autoRotationBehavior);
  31887. this._autoRotationBehavior = null;
  31888. }
  31889. },
  31890. enumerable: true,
  31891. configurable: true
  31892. });
  31893. // Cache
  31894. ArcRotateCamera.prototype._initCache = function () {
  31895. _super.prototype._initCache.call(this);
  31896. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31897. this._cache.alpha = undefined;
  31898. this._cache.beta = undefined;
  31899. this._cache.radius = undefined;
  31900. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  31901. };
  31902. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  31903. if (!ignoreParentClass) {
  31904. _super.prototype._updateCache.call(this);
  31905. }
  31906. this._cache._target.copyFrom(this._getTargetPosition());
  31907. this._cache.alpha = this.alpha;
  31908. this._cache.beta = this.beta;
  31909. this._cache.radius = this.radius;
  31910. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  31911. };
  31912. ArcRotateCamera.prototype._getTargetPosition = function () {
  31913. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  31914. var pos = this._targetHost.getAbsolutePosition();
  31915. if (this._targetBoundingCenter) {
  31916. pos.addToRef(this._targetBoundingCenter, this._target);
  31917. }
  31918. else {
  31919. this._target.copyFrom(pos);
  31920. }
  31921. }
  31922. var lockedTargetPosition = this._getLockedTargetPosition();
  31923. if (lockedTargetPosition) {
  31924. return lockedTargetPosition;
  31925. }
  31926. return this._target;
  31927. };
  31928. // Synchronized
  31929. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  31930. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  31931. return false;
  31932. return this._cache._target.equals(this._getTargetPosition())
  31933. && this._cache.alpha === this.alpha
  31934. && this._cache.beta === this.beta
  31935. && this._cache.radius === this.radius
  31936. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  31937. };
  31938. // Methods
  31939. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  31940. var _this = this;
  31941. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  31942. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  31943. this._useCtrlForPanning = useCtrlForPanning;
  31944. this._panningMouseButton = panningMouseButton;
  31945. this.inputs.attachElement(element, noPreventDefault);
  31946. this._reset = function () {
  31947. _this.inertialAlphaOffset = 0;
  31948. _this.inertialBetaOffset = 0;
  31949. _this.inertialRadiusOffset = 0;
  31950. };
  31951. };
  31952. ArcRotateCamera.prototype.detachControl = function (element) {
  31953. this.inputs.detachElement(element);
  31954. if (this._reset) {
  31955. this._reset();
  31956. }
  31957. };
  31958. ArcRotateCamera.prototype._checkInputs = function () {
  31959. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  31960. if (this._collisionTriggered) {
  31961. return;
  31962. }
  31963. this.inputs.checkInputs();
  31964. // Inertia
  31965. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  31966. if (this.getScene().useRightHandedSystem) {
  31967. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  31968. }
  31969. else {
  31970. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  31971. }
  31972. this.beta += this.inertialBetaOffset;
  31973. this.radius -= this.inertialRadiusOffset;
  31974. this.inertialAlphaOffset *= this.inertia;
  31975. this.inertialBetaOffset *= this.inertia;
  31976. this.inertialRadiusOffset *= this.inertia;
  31977. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  31978. this.inertialAlphaOffset = 0;
  31979. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  31980. this.inertialBetaOffset = 0;
  31981. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  31982. this.inertialRadiusOffset = 0;
  31983. }
  31984. // Panning inertia
  31985. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  31986. if (!this._localDirection) {
  31987. this._localDirection = BABYLON.Vector3.Zero();
  31988. this._transformedDirection = BABYLON.Vector3.Zero();
  31989. }
  31990. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  31991. this._localDirection.multiplyInPlace(this.panningAxis);
  31992. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  31993. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  31994. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  31995. if (!this.panningAxis.y) {
  31996. this._transformedDirection.y = 0;
  31997. }
  31998. if (!this._targetHost) {
  31999. this._target.addInPlace(this._transformedDirection);
  32000. }
  32001. this.inertialPanningX *= this.panningInertia;
  32002. this.inertialPanningY *= this.panningInertia;
  32003. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  32004. this.inertialPanningX = 0;
  32005. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  32006. this.inertialPanningY = 0;
  32007. }
  32008. // Limits
  32009. this._checkLimits();
  32010. _super.prototype._checkInputs.call(this);
  32011. };
  32012. ArcRotateCamera.prototype._checkLimits = function () {
  32013. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32014. if (this.allowUpsideDown && this.beta > Math.PI) {
  32015. this.beta = this.beta - (2 * Math.PI);
  32016. }
  32017. }
  32018. else {
  32019. if (this.beta < this.lowerBetaLimit) {
  32020. this.beta = this.lowerBetaLimit;
  32021. }
  32022. }
  32023. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  32024. if (this.allowUpsideDown && this.beta < -Math.PI) {
  32025. this.beta = this.beta + (2 * Math.PI);
  32026. }
  32027. }
  32028. else {
  32029. if (this.beta > this.upperBetaLimit) {
  32030. this.beta = this.upperBetaLimit;
  32031. }
  32032. }
  32033. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  32034. this.alpha = this.lowerAlphaLimit;
  32035. }
  32036. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  32037. this.alpha = this.upperAlphaLimit;
  32038. }
  32039. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  32040. this.radius = this.lowerRadiusLimit;
  32041. }
  32042. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  32043. this.radius = this.upperRadiusLimit;
  32044. }
  32045. };
  32046. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  32047. var radiusv3 = this.position.subtract(this._getTargetPosition());
  32048. this.radius = radiusv3.length();
  32049. if (this.radius === 0) {
  32050. this.radius = 0.0001; // Just to avoid division by zero
  32051. }
  32052. // Alpha
  32053. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  32054. if (radiusv3.z < 0) {
  32055. this.alpha = 2 * Math.PI - this.alpha;
  32056. }
  32057. // Beta
  32058. this.beta = Math.acos(radiusv3.y / this.radius);
  32059. this._checkLimits();
  32060. };
  32061. ArcRotateCamera.prototype.setPosition = function (position) {
  32062. if (this.position.equals(position)) {
  32063. return;
  32064. }
  32065. this.position.copyFrom(position);
  32066. this.rebuildAnglesAndRadius();
  32067. };
  32068. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  32069. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  32070. if (allowSamePosition === void 0) { allowSamePosition = false; }
  32071. if (target.getBoundingInfo) {
  32072. if (toBoundingCenter) {
  32073. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  32074. }
  32075. else {
  32076. this._targetBoundingCenter = null;
  32077. }
  32078. this._targetHost = target;
  32079. this._target = this._getTargetPosition();
  32080. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  32081. }
  32082. else {
  32083. var newTarget = target;
  32084. var currentTarget = this._getTargetPosition();
  32085. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  32086. return;
  32087. }
  32088. this._target = newTarget;
  32089. this._targetBoundingCenter = null;
  32090. this.onMeshTargetChangedObservable.notifyObservers(null);
  32091. }
  32092. this.rebuildAnglesAndRadius();
  32093. };
  32094. ArcRotateCamera.prototype._getViewMatrix = function () {
  32095. // Compute
  32096. var cosa = Math.cos(this.alpha);
  32097. var sina = Math.sin(this.alpha);
  32098. var cosb = Math.cos(this.beta);
  32099. var sinb = Math.sin(this.beta);
  32100. if (sinb === 0) {
  32101. sinb = 0.0001;
  32102. }
  32103. var target = this._getTargetPosition();
  32104. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  32105. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  32106. if (!this._collider) {
  32107. this._collider = new BABYLON.Collider();
  32108. }
  32109. this._collider.radius = this.collisionRadius;
  32110. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  32111. this._collisionTriggered = true;
  32112. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32113. }
  32114. else {
  32115. this.position.copyFrom(this._newPosition);
  32116. var up = this.upVector;
  32117. if (this.allowUpsideDown && sinb < 0) {
  32118. up = up.clone();
  32119. up = up.negate();
  32120. }
  32121. if (this.getScene().useRightHandedSystem) {
  32122. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  32123. }
  32124. else {
  32125. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  32126. }
  32127. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  32128. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  32129. }
  32130. this._currentTarget = target;
  32131. return this._viewMatrix;
  32132. };
  32133. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  32134. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32135. meshes = meshes || this.getScene().meshes;
  32136. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  32137. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  32138. this.radius = distance * this.zoomOnFactor;
  32139. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  32140. };
  32141. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  32142. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32143. var meshesOrMinMaxVector;
  32144. var distance;
  32145. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  32146. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  32147. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  32148. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  32149. }
  32150. else {
  32151. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  32152. distance = meshesOrMinMaxVectorAndDistance.distance;
  32153. }
  32154. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  32155. if (!doNotUpdateMaxZ) {
  32156. this.maxZ = distance * 2;
  32157. }
  32158. };
  32159. /**
  32160. * @override
  32161. * Override Camera.createRigCamera
  32162. */
  32163. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32164. var alphaShift;
  32165. switch (this.cameraRigMode) {
  32166. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32167. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32168. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32169. case BABYLON.Camera.RIG_MODE_VR:
  32170. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  32171. break;
  32172. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32173. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  32174. break;
  32175. }
  32176. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  32177. rigCam._cameraRigParams = {};
  32178. return rigCam;
  32179. };
  32180. /**
  32181. * @override
  32182. * Override Camera._updateRigCameras
  32183. */
  32184. ArcRotateCamera.prototype._updateRigCameras = function () {
  32185. var camLeft = this._rigCameras[0];
  32186. var camRight = this._rigCameras[1];
  32187. camLeft.beta = camRight.beta = this.beta;
  32188. camLeft.radius = camRight.radius = this.radius;
  32189. switch (this.cameraRigMode) {
  32190. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32191. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32192. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32193. case BABYLON.Camera.RIG_MODE_VR:
  32194. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32195. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32196. break;
  32197. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32198. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32199. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32200. break;
  32201. }
  32202. _super.prototype._updateRigCameras.call(this);
  32203. };
  32204. ArcRotateCamera.prototype.dispose = function () {
  32205. this.inputs.clear();
  32206. _super.prototype.dispose.call(this);
  32207. };
  32208. ArcRotateCamera.prototype.getClassName = function () {
  32209. return "ArcRotateCamera";
  32210. };
  32211. __decorate([
  32212. BABYLON.serialize()
  32213. ], ArcRotateCamera.prototype, "alpha", void 0);
  32214. __decorate([
  32215. BABYLON.serialize()
  32216. ], ArcRotateCamera.prototype, "beta", void 0);
  32217. __decorate([
  32218. BABYLON.serialize()
  32219. ], ArcRotateCamera.prototype, "radius", void 0);
  32220. __decorate([
  32221. BABYLON.serializeAsVector3("target")
  32222. ], ArcRotateCamera.prototype, "_target", void 0);
  32223. __decorate([
  32224. BABYLON.serialize()
  32225. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  32226. __decorate([
  32227. BABYLON.serialize()
  32228. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  32229. __decorate([
  32230. BABYLON.serialize()
  32231. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  32232. __decorate([
  32233. BABYLON.serialize()
  32234. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  32235. __decorate([
  32236. BABYLON.serialize()
  32237. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  32238. __decorate([
  32239. BABYLON.serialize()
  32240. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  32241. __decorate([
  32242. BABYLON.serialize()
  32243. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  32244. __decorate([
  32245. BABYLON.serialize()
  32246. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  32247. __decorate([
  32248. BABYLON.serialize()
  32249. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  32250. __decorate([
  32251. BABYLON.serialize()
  32252. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  32253. __decorate([
  32254. BABYLON.serialize()
  32255. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  32256. __decorate([
  32257. BABYLON.serialize()
  32258. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  32259. __decorate([
  32260. BABYLON.serialize()
  32261. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  32262. __decorate([
  32263. BABYLON.serialize()
  32264. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  32265. return ArcRotateCamera;
  32266. }(BABYLON.TargetCamera));
  32267. BABYLON.ArcRotateCamera = ArcRotateCamera;
  32268. })(BABYLON || (BABYLON = {}));
  32269. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  32270. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  32271. var BABYLON;
  32272. (function (BABYLON) {
  32273. var ArcRotateCameraInputsManager = (function (_super) {
  32274. __extends(ArcRotateCameraInputsManager, _super);
  32275. function ArcRotateCameraInputsManager(camera) {
  32276. return _super.call(this, camera) || this;
  32277. }
  32278. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  32279. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  32280. return this;
  32281. };
  32282. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  32283. this.add(new BABYLON.ArcRotateCameraPointersInput());
  32284. return this;
  32285. };
  32286. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  32287. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  32288. return this;
  32289. };
  32290. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  32291. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  32292. return this;
  32293. };
  32294. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  32295. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  32296. return this;
  32297. };
  32298. return ArcRotateCameraInputsManager;
  32299. }(BABYLON.CameraInputsManager));
  32300. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  32301. })(BABYLON || (BABYLON = {}));
  32302. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  32303. var BABYLON;
  32304. (function (BABYLON) {
  32305. var CubeTexture = (function (_super) {
  32306. __extends(CubeTexture, _super);
  32307. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  32308. if (onLoad === void 0) { onLoad = null; }
  32309. if (onError === void 0) { onError = null; }
  32310. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32311. if (prefiltered === void 0) { prefiltered = false; }
  32312. if (forcedExtension === void 0) { forcedExtension = null; }
  32313. var _this = _super.call(this, scene) || this;
  32314. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  32315. _this.name = rootUrl;
  32316. _this.url = rootUrl;
  32317. _this._noMipmap = noMipmap;
  32318. _this.hasAlpha = false;
  32319. _this._format = format;
  32320. _this._prefiltered = prefiltered;
  32321. _this.isCube = true;
  32322. _this._textureMatrix = BABYLON.Matrix.Identity();
  32323. if (prefiltered) {
  32324. _this.gammaSpace = false;
  32325. }
  32326. if (!rootUrl && !files) {
  32327. return _this;
  32328. }
  32329. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  32330. if (!files) {
  32331. if (!extensions) {
  32332. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  32333. }
  32334. files = [];
  32335. for (var index = 0; index < extensions.length; index++) {
  32336. files.push(rootUrl + extensions[index]);
  32337. }
  32338. _this._extensions = extensions;
  32339. }
  32340. _this._files = files;
  32341. if (!_this._texture) {
  32342. if (!scene.useDelayedTextureLoading) {
  32343. if (prefiltered) {
  32344. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  32345. }
  32346. else {
  32347. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  32348. }
  32349. }
  32350. else {
  32351. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32352. }
  32353. }
  32354. else if (onLoad) {
  32355. if (_this._texture.isReady) {
  32356. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  32357. }
  32358. else {
  32359. _this._texture.onLoadedCallbacks.push(onLoad);
  32360. }
  32361. }
  32362. return _this;
  32363. }
  32364. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  32365. return new CubeTexture("", scene, null, noMipmap, files);
  32366. };
  32367. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  32368. if (forcedExtension === void 0) { forcedExtension = null; }
  32369. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  32370. };
  32371. // Methods
  32372. CubeTexture.prototype.delayLoad = function () {
  32373. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32374. return;
  32375. }
  32376. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32377. this._texture = this._getFromCache(this.url, this._noMipmap);
  32378. if (!this._texture) {
  32379. if (this._prefiltered) {
  32380. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  32381. }
  32382. else {
  32383. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  32384. }
  32385. }
  32386. };
  32387. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  32388. return this._textureMatrix;
  32389. };
  32390. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  32391. this._textureMatrix = value;
  32392. };
  32393. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32394. var texture = BABYLON.SerializationHelper.Parse(function () {
  32395. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  32396. }, parsedTexture, scene);
  32397. // Animations
  32398. if (parsedTexture.animations) {
  32399. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  32400. var parsedAnimation = parsedTexture.animations[animationIndex];
  32401. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32402. }
  32403. }
  32404. return texture;
  32405. };
  32406. CubeTexture.prototype.clone = function () {
  32407. var _this = this;
  32408. return BABYLON.SerializationHelper.Clone(function () {
  32409. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  32410. }, this);
  32411. };
  32412. return CubeTexture;
  32413. }(BABYLON.BaseTexture));
  32414. BABYLON.CubeTexture = CubeTexture;
  32415. })(BABYLON || (BABYLON = {}));
  32416. //# sourceMappingURL=babylon.cubeTexture.js.map
  32417. var BABYLON;
  32418. (function (BABYLON) {
  32419. var RenderTargetTexture = (function (_super) {
  32420. __extends(RenderTargetTexture, _super);
  32421. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  32422. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  32423. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32424. if (isCube === void 0) { isCube = false; }
  32425. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32426. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  32427. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  32428. if (isMulti === void 0) { isMulti = false; }
  32429. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  32430. _this.isCube = isCube;
  32431. /**
  32432. * Use this list to define the list of mesh you want to render.
  32433. */
  32434. _this.renderList = new Array();
  32435. _this.renderParticles = true;
  32436. _this.renderSprites = false;
  32437. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  32438. _this.ignoreCameraViewport = false;
  32439. // Events
  32440. /**
  32441. * An event triggered when the texture is unbind.
  32442. * @type {BABYLON.Observable}
  32443. */
  32444. _this.onBeforeBindObservable = new BABYLON.Observable();
  32445. /**
  32446. * An event triggered when the texture is unbind.
  32447. * @type {BABYLON.Observable}
  32448. */
  32449. _this.onAfterUnbindObservable = new BABYLON.Observable();
  32450. /**
  32451. * An event triggered before rendering the texture
  32452. * @type {BABYLON.Observable}
  32453. */
  32454. _this.onBeforeRenderObservable = new BABYLON.Observable();
  32455. /**
  32456. * An event triggered after rendering the texture
  32457. * @type {BABYLON.Observable}
  32458. */
  32459. _this.onAfterRenderObservable = new BABYLON.Observable();
  32460. /**
  32461. * An event triggered after the texture clear
  32462. * @type {BABYLON.Observable}
  32463. */
  32464. _this.onClearObservable = new BABYLON.Observable();
  32465. _this._currentRefreshId = -1;
  32466. _this._refreshRate = 1;
  32467. _this._samples = 1;
  32468. scene = _this.getScene();
  32469. _this.name = name;
  32470. _this.isRenderTarget = true;
  32471. _this._size = size;
  32472. _this._generateMipMaps = generateMipMaps;
  32473. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  32474. // Rendering groups
  32475. _this._renderingManager = new BABYLON.RenderingManager(scene);
  32476. if (isMulti) {
  32477. return _this;
  32478. }
  32479. _this._renderTargetOptions = {
  32480. generateMipMaps: generateMipMaps,
  32481. type: type,
  32482. samplingMode: samplingMode,
  32483. generateDepthBuffer: generateDepthBuffer,
  32484. generateStencilBuffer: generateStencilBuffer
  32485. };
  32486. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  32487. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32488. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32489. }
  32490. if (isCube) {
  32491. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  32492. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  32493. _this._textureMatrix = BABYLON.Matrix.Identity();
  32494. }
  32495. else {
  32496. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  32497. }
  32498. return _this;
  32499. }
  32500. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  32501. get: function () {
  32502. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  32503. },
  32504. enumerable: true,
  32505. configurable: true
  32506. });
  32507. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  32508. get: function () {
  32509. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  32510. },
  32511. enumerable: true,
  32512. configurable: true
  32513. });
  32514. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  32515. get: function () {
  32516. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  32517. },
  32518. enumerable: true,
  32519. configurable: true
  32520. });
  32521. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  32522. set: function (callback) {
  32523. if (this._onAfterUnbindObserver) {
  32524. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  32525. }
  32526. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  32527. },
  32528. enumerable: true,
  32529. configurable: true
  32530. });
  32531. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  32532. set: function (callback) {
  32533. if (this._onBeforeRenderObserver) {
  32534. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32535. }
  32536. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32537. },
  32538. enumerable: true,
  32539. configurable: true
  32540. });
  32541. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  32542. set: function (callback) {
  32543. if (this._onAfterRenderObserver) {
  32544. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32545. }
  32546. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32547. },
  32548. enumerable: true,
  32549. configurable: true
  32550. });
  32551. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  32552. set: function (callback) {
  32553. if (this._onClearObserver) {
  32554. this.onClearObservable.remove(this._onClearObserver);
  32555. }
  32556. this._onClearObserver = this.onClearObservable.add(callback);
  32557. },
  32558. enumerable: true,
  32559. configurable: true
  32560. });
  32561. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  32562. get: function () {
  32563. return this._renderTargetOptions;
  32564. },
  32565. enumerable: true,
  32566. configurable: true
  32567. });
  32568. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  32569. get: function () {
  32570. return this._samples;
  32571. },
  32572. set: function (value) {
  32573. if (this._samples === value) {
  32574. return;
  32575. }
  32576. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  32577. },
  32578. enumerable: true,
  32579. configurable: true
  32580. });
  32581. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  32582. this._currentRefreshId = -1;
  32583. };
  32584. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  32585. get: function () {
  32586. return this._refreshRate;
  32587. },
  32588. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  32589. set: function (value) {
  32590. this._refreshRate = value;
  32591. this.resetRefreshCounter();
  32592. },
  32593. enumerable: true,
  32594. configurable: true
  32595. });
  32596. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  32597. if (!this._postProcessManager) {
  32598. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  32599. this._postProcesses = new Array();
  32600. }
  32601. this._postProcesses.push(postProcess);
  32602. this._postProcesses[0].autoClear = false;
  32603. };
  32604. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  32605. if (!this._postProcesses) {
  32606. return;
  32607. }
  32608. if (dispose) {
  32609. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  32610. var postProcess = _a[_i];
  32611. postProcess.dispose();
  32612. postProcess = null;
  32613. }
  32614. }
  32615. this._postProcesses = [];
  32616. };
  32617. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  32618. if (!this._postProcesses) {
  32619. return;
  32620. }
  32621. var index = this._postProcesses.indexOf(postProcess);
  32622. if (index === -1) {
  32623. return;
  32624. }
  32625. this._postProcesses.splice(index, 1);
  32626. if (this._postProcesses.length > 0) {
  32627. this._postProcesses[0].autoClear = false;
  32628. }
  32629. };
  32630. RenderTargetTexture.prototype._shouldRender = function () {
  32631. if (this._currentRefreshId === -1) {
  32632. this._currentRefreshId = 1;
  32633. return true;
  32634. }
  32635. if (this.refreshRate === this._currentRefreshId) {
  32636. this._currentRefreshId = 1;
  32637. return true;
  32638. }
  32639. this._currentRefreshId++;
  32640. return false;
  32641. };
  32642. RenderTargetTexture.prototype.isReady = function () {
  32643. if (!this.getScene().renderTargetsEnabled) {
  32644. return false;
  32645. }
  32646. return _super.prototype.isReady.call(this);
  32647. };
  32648. RenderTargetTexture.prototype.getRenderSize = function () {
  32649. return this._size;
  32650. };
  32651. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  32652. get: function () {
  32653. return true;
  32654. },
  32655. enumerable: true,
  32656. configurable: true
  32657. });
  32658. RenderTargetTexture.prototype.scale = function (ratio) {
  32659. var newSize = this._size * ratio;
  32660. this.resize(newSize);
  32661. };
  32662. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  32663. if (this.isCube) {
  32664. return this._textureMatrix;
  32665. }
  32666. return _super.prototype.getReflectionTextureMatrix.call(this);
  32667. };
  32668. RenderTargetTexture.prototype.resize = function (size) {
  32669. this.releaseInternalTexture();
  32670. if (this.isCube) {
  32671. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  32672. }
  32673. else {
  32674. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  32675. }
  32676. };
  32677. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  32678. var scene = this.getScene();
  32679. var engine = scene.getEngine();
  32680. if (this.useCameraPostProcesses !== undefined) {
  32681. useCameraPostProcess = this.useCameraPostProcesses;
  32682. }
  32683. if (this._waitingRenderList) {
  32684. this.renderList = [];
  32685. for (var index = 0; index < this._waitingRenderList.length; index++) {
  32686. var id = this._waitingRenderList[index];
  32687. this.renderList.push(scene.getMeshByID(id));
  32688. }
  32689. delete this._waitingRenderList;
  32690. }
  32691. // Is predicate defined?
  32692. if (this.renderListPredicate) {
  32693. this.renderList.splice(0); // Clear previous renderList
  32694. var sceneMeshes = this.getScene().meshes;
  32695. for (var index = 0; index < sceneMeshes.length; index++) {
  32696. var mesh = sceneMeshes[index];
  32697. if (this.renderListPredicate(mesh)) {
  32698. this.renderList.push(mesh);
  32699. }
  32700. }
  32701. }
  32702. if (this.renderList && this.renderList.length === 0) {
  32703. return;
  32704. }
  32705. this.onBeforeBindObservable.notifyObservers(this);
  32706. // Set custom projection.
  32707. // Needs to be before binding to prevent changing the aspect ratio.
  32708. var camera;
  32709. if (this.activeCamera) {
  32710. camera = this.activeCamera;
  32711. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  32712. if (this.activeCamera !== scene.activeCamera) {
  32713. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  32714. }
  32715. }
  32716. else {
  32717. camera = scene.activeCamera;
  32718. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  32719. }
  32720. // Prepare renderingManager
  32721. this._renderingManager.reset();
  32722. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  32723. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  32724. var sceneRenderId = scene.getRenderId();
  32725. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  32726. var mesh = currentRenderList[meshIndex];
  32727. if (mesh) {
  32728. if (!mesh.isReady()) {
  32729. // Reset _currentRefreshId
  32730. this.resetRefreshCounter();
  32731. continue;
  32732. }
  32733. mesh._preActivateForIntermediateRendering(sceneRenderId);
  32734. var isMasked = void 0;
  32735. if (!this.renderList) {
  32736. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  32737. }
  32738. else {
  32739. isMasked = false;
  32740. }
  32741. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  32742. mesh._activate(sceneRenderId);
  32743. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32744. var subMesh = mesh.subMeshes[subIndex];
  32745. scene._activeIndices.addCount(subMesh.indexCount, false);
  32746. this._renderingManager.dispatch(subMesh);
  32747. }
  32748. }
  32749. }
  32750. }
  32751. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  32752. var particleSystem = scene.particleSystems[particleIndex];
  32753. var emitter = particleSystem.emitter;
  32754. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  32755. continue;
  32756. }
  32757. if (currentRenderList.indexOf(emitter) >= 0) {
  32758. this._renderingManager.dispatchParticles(particleSystem);
  32759. }
  32760. }
  32761. if (this.isCube) {
  32762. for (var face = 0; face < 6; face++) {
  32763. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  32764. scene.incrementRenderId();
  32765. scene.resetCachedMaterial();
  32766. }
  32767. }
  32768. else {
  32769. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  32770. }
  32771. this.onAfterUnbindObservable.notifyObservers(this);
  32772. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  32773. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  32774. }
  32775. engine.setViewport(scene.activeCamera.viewport);
  32776. scene.resetCachedMaterial();
  32777. };
  32778. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  32779. var _this = this;
  32780. var scene = this.getScene();
  32781. var engine = scene.getEngine();
  32782. // Bind
  32783. if (this._postProcessManager) {
  32784. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  32785. }
  32786. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  32787. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  32788. }
  32789. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  32790. // Clear
  32791. if (this.onClearObservable.hasObservers()) {
  32792. this.onClearObservable.notifyObservers(engine);
  32793. }
  32794. else {
  32795. engine.clear(scene.clearColor, true, true, true);
  32796. }
  32797. if (!this._doNotChangeAspectRatio) {
  32798. scene.updateTransformMatrix(true);
  32799. }
  32800. // Render
  32801. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  32802. if (this._postProcessManager) {
  32803. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  32804. }
  32805. else if (useCameraPostProcess) {
  32806. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  32807. }
  32808. if (!this._doNotChangeAspectRatio) {
  32809. scene.updateTransformMatrix(true);
  32810. }
  32811. // Dump ?
  32812. if (dumpForDebug) {
  32813. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  32814. }
  32815. // Unbind
  32816. if (!this.isCube || faceIndex === 5) {
  32817. if (this.isCube) {
  32818. if (faceIndex === 5) {
  32819. engine.generateMipMapsForCubemap(this._texture);
  32820. }
  32821. }
  32822. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  32823. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  32824. });
  32825. }
  32826. else {
  32827. this.onAfterRenderObservable.notifyObservers(faceIndex);
  32828. }
  32829. };
  32830. /**
  32831. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  32832. * This allowed control for front to back rendering or reversly depending of the special needs.
  32833. *
  32834. * @param renderingGroupId The rendering group id corresponding to its index
  32835. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  32836. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  32837. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  32838. */
  32839. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  32840. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  32841. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  32842. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  32843. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  32844. };
  32845. /**
  32846. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  32847. *
  32848. * @param renderingGroupId The rendering group id corresponding to its index
  32849. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  32850. */
  32851. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  32852. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  32853. };
  32854. RenderTargetTexture.prototype.clone = function () {
  32855. var textureSize = this.getSize();
  32856. 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);
  32857. // Base texture
  32858. newTexture.hasAlpha = this.hasAlpha;
  32859. newTexture.level = this.level;
  32860. // RenderTarget Texture
  32861. newTexture.coordinatesMode = this.coordinatesMode;
  32862. newTexture.renderList = this.renderList.slice(0);
  32863. return newTexture;
  32864. };
  32865. RenderTargetTexture.prototype.serialize = function () {
  32866. if (!this.name) {
  32867. return null;
  32868. }
  32869. var serializationObject = _super.prototype.serialize.call(this);
  32870. serializationObject.renderTargetSize = this.getRenderSize();
  32871. serializationObject.renderList = [];
  32872. for (var index = 0; index < this.renderList.length; index++) {
  32873. serializationObject.renderList.push(this.renderList[index].id);
  32874. }
  32875. return serializationObject;
  32876. };
  32877. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  32878. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  32879. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  32880. };
  32881. RenderTargetTexture.prototype.dispose = function () {
  32882. if (this._postProcessManager) {
  32883. this._postProcessManager.dispose();
  32884. this._postProcessManager = null;
  32885. }
  32886. this.clearPostProcesses(true);
  32887. this.renderList = null;
  32888. // Remove from custom render targets
  32889. var scene = this.getScene();
  32890. var index = scene.customRenderTargets.indexOf(this);
  32891. if (index >= 0) {
  32892. scene.customRenderTargets.splice(index, 1);
  32893. }
  32894. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  32895. var camera = _a[_i];
  32896. index = camera.customRenderTargets.indexOf(this);
  32897. if (index >= 0) {
  32898. camera.customRenderTargets.splice(index, 1);
  32899. }
  32900. }
  32901. _super.prototype.dispose.call(this);
  32902. };
  32903. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  32904. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  32905. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  32906. return RenderTargetTexture;
  32907. }(BABYLON.Texture));
  32908. BABYLON.RenderTargetTexture = RenderTargetTexture;
  32909. })(BABYLON || (BABYLON = {}));
  32910. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  32911. var BABYLON;
  32912. (function (BABYLON) {
  32913. ;
  32914. var MultiRenderTarget = (function (_super) {
  32915. __extends(MultiRenderTarget, _super);
  32916. function MultiRenderTarget(name, size, count, scene, options) {
  32917. var _this = this;
  32918. options = options || {};
  32919. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  32920. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  32921. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  32922. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  32923. if (!_this.isSupported) {
  32924. _this.dispose();
  32925. return;
  32926. }
  32927. var types = [];
  32928. var samplingModes = [];
  32929. for (var i = 0; i < count; i++) {
  32930. if (options.types && options.types[i]) {
  32931. types.push(options.types[i]);
  32932. }
  32933. else {
  32934. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  32935. }
  32936. if (options.samplingModes && options.samplingModes[i]) {
  32937. samplingModes.push(options.samplingModes[i]);
  32938. }
  32939. else {
  32940. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32941. }
  32942. }
  32943. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  32944. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  32945. _this._count = count;
  32946. _this._size = size;
  32947. _this._multiRenderTargetOptions = {
  32948. samplingModes: samplingModes,
  32949. generateMipMaps: generateMipMaps,
  32950. generateDepthBuffer: generateDepthBuffer,
  32951. generateStencilBuffer: generateStencilBuffer,
  32952. generateDepthTexture: generateDepthTexture,
  32953. types: types,
  32954. textureCount: count
  32955. };
  32956. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  32957. _this._createInternalTextures();
  32958. return _this;
  32959. }
  32960. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  32961. get: function () {
  32962. var engine = this.getScene().getEngine();
  32963. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  32964. },
  32965. enumerable: true,
  32966. configurable: true
  32967. });
  32968. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  32969. get: function () {
  32970. return this._textures;
  32971. },
  32972. enumerable: true,
  32973. configurable: true
  32974. });
  32975. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  32976. get: function () {
  32977. return this._textures[this._textures.length - 1];
  32978. },
  32979. enumerable: true,
  32980. configurable: true
  32981. });
  32982. MultiRenderTarget.prototype._createInternalTextures = function () {
  32983. this._textures = [];
  32984. for (var i = 0; i < this._webGLTextures.length; i++) {
  32985. var texture = new BABYLON.Texture(null, this.getScene());
  32986. texture._texture = this._webGLTextures[i];
  32987. this._textures.push(texture);
  32988. }
  32989. // Keeps references to frame buffer and stencil/depth buffer
  32990. this._texture = this._webGLTextures[0];
  32991. };
  32992. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  32993. get: function () {
  32994. return this._samples;
  32995. },
  32996. set: function (value) {
  32997. if (this._samples === value) {
  32998. return;
  32999. }
  33000. for (var i = 0; i < this._webGLTextures.length; i++) {
  33001. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  33002. }
  33003. },
  33004. enumerable: true,
  33005. configurable: true
  33006. });
  33007. MultiRenderTarget.prototype.resize = function (size) {
  33008. this.releaseInternalTextures();
  33009. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  33010. this._createInternalTextures();
  33011. };
  33012. MultiRenderTarget.prototype.dispose = function () {
  33013. this.releaseInternalTextures();
  33014. _super.prototype.dispose.call(this);
  33015. };
  33016. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  33017. if (!this._webGLTextures) {
  33018. return;
  33019. }
  33020. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  33021. if (this._webGLTextures[i] !== undefined) {
  33022. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  33023. this._webGLTextures.splice(i, 1);
  33024. }
  33025. }
  33026. };
  33027. return MultiRenderTarget;
  33028. }(BABYLON.RenderTargetTexture));
  33029. BABYLON.MultiRenderTarget = MultiRenderTarget;
  33030. })(BABYLON || (BABYLON = {}));
  33031. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  33032. /// <reference path="babylon.renderTargetTexture.ts" />
  33033. var BABYLON;
  33034. (function (BABYLON) {
  33035. var MirrorTexture = (function (_super) {
  33036. __extends(MirrorTexture, _super);
  33037. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  33038. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33039. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33040. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  33041. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  33042. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  33043. _this._transformMatrix = BABYLON.Matrix.Zero();
  33044. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  33045. _this._blurKernelX = 0;
  33046. _this._blurKernelY = 0;
  33047. _this._blurRatio = 1.0;
  33048. _this.onBeforeRenderObservable.add(function () {
  33049. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  33050. _this._savedViewMatrix = scene.getViewMatrix();
  33051. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  33052. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  33053. scene.clipPlane = _this.mirrorPlane;
  33054. scene.getEngine().cullBackFaces = false;
  33055. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  33056. });
  33057. _this.onAfterRenderObservable.add(function () {
  33058. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  33059. scene.getEngine().cullBackFaces = true;
  33060. scene._mirroredCameraPosition = null;
  33061. delete scene.clipPlane;
  33062. });
  33063. return _this;
  33064. }
  33065. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  33066. get: function () {
  33067. return this._blurRatio;
  33068. },
  33069. set: function (value) {
  33070. if (this._blurRatio === value) {
  33071. return;
  33072. }
  33073. this._blurRatio = value;
  33074. this._preparePostProcesses();
  33075. },
  33076. enumerable: true,
  33077. configurable: true
  33078. });
  33079. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  33080. set: function (value) {
  33081. this.blurKernelX = value;
  33082. this.blurKernelY = value;
  33083. },
  33084. enumerable: true,
  33085. configurable: true
  33086. });
  33087. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  33088. get: function () {
  33089. return this._blurKernelX;
  33090. },
  33091. set: function (value) {
  33092. if (this._blurKernelX === value) {
  33093. return;
  33094. }
  33095. this._blurKernelX = value;
  33096. this._preparePostProcesses();
  33097. },
  33098. enumerable: true,
  33099. configurable: true
  33100. });
  33101. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  33102. get: function () {
  33103. return this._blurKernelY;
  33104. },
  33105. set: function (value) {
  33106. if (this._blurKernelY === value) {
  33107. return;
  33108. }
  33109. this._blurKernelY = value;
  33110. this._preparePostProcesses();
  33111. },
  33112. enumerable: true,
  33113. configurable: true
  33114. });
  33115. MirrorTexture.prototype._preparePostProcesses = function () {
  33116. this.clearPostProcesses(true);
  33117. if (this._blurKernelX && this._blurKernelY) {
  33118. var engine = this.getScene().getEngine();
  33119. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33120. this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  33121. this._blurX.autoClear = false;
  33122. if (this._blurRatio === 1 && this.samples < 2) {
  33123. this._blurX.outputTexture = this._texture;
  33124. }
  33125. else {
  33126. this._blurX.alwaysForcePOT = true;
  33127. }
  33128. this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  33129. this._blurY.autoClear = false;
  33130. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  33131. this.addPostProcess(this._blurX);
  33132. this.addPostProcess(this._blurY);
  33133. }
  33134. };
  33135. MirrorTexture.prototype.clone = function () {
  33136. var textureSize = this.getSize();
  33137. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  33138. // Base texture
  33139. newTexture.hasAlpha = this.hasAlpha;
  33140. newTexture.level = this.level;
  33141. // Mirror Texture
  33142. newTexture.mirrorPlane = this.mirrorPlane.clone();
  33143. newTexture.renderList = this.renderList.slice(0);
  33144. return newTexture;
  33145. };
  33146. MirrorTexture.prototype.serialize = function () {
  33147. if (!this.name) {
  33148. return null;
  33149. }
  33150. var serializationObject = _super.prototype.serialize.call(this);
  33151. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  33152. return serializationObject;
  33153. };
  33154. return MirrorTexture;
  33155. }(BABYLON.RenderTargetTexture));
  33156. BABYLON.MirrorTexture = MirrorTexture;
  33157. })(BABYLON || (BABYLON = {}));
  33158. //# sourceMappingURL=babylon.mirrorTexture.js.map
  33159. /// <reference path="babylon.renderTargetTexture.ts" />
  33160. var BABYLON;
  33161. (function (BABYLON) {
  33162. /**
  33163. * Creates a refraction texture used by refraction channel of the standard material.
  33164. * @param name the texture name
  33165. * @param size size of the underlying texture
  33166. * @param scene root scene
  33167. */
  33168. var RefractionTexture = (function (_super) {
  33169. __extends(RefractionTexture, _super);
  33170. function RefractionTexture(name, size, scene, generateMipMaps) {
  33171. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  33172. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  33173. _this.depth = 2.0;
  33174. _this.onBeforeRenderObservable.add(function () {
  33175. scene.clipPlane = _this.refractionPlane;
  33176. });
  33177. _this.onAfterRenderObservable.add(function () {
  33178. delete scene.clipPlane;
  33179. });
  33180. return _this;
  33181. }
  33182. RefractionTexture.prototype.clone = function () {
  33183. var textureSize = this.getSize();
  33184. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  33185. // Base texture
  33186. newTexture.hasAlpha = this.hasAlpha;
  33187. newTexture.level = this.level;
  33188. // Refraction Texture
  33189. newTexture.refractionPlane = this.refractionPlane.clone();
  33190. newTexture.renderList = this.renderList.slice(0);
  33191. newTexture.depth = this.depth;
  33192. return newTexture;
  33193. };
  33194. RefractionTexture.prototype.serialize = function () {
  33195. if (!this.name) {
  33196. return null;
  33197. }
  33198. var serializationObject = _super.prototype.serialize.call(this);
  33199. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  33200. serializationObject.depth = this.depth;
  33201. return serializationObject;
  33202. };
  33203. return RefractionTexture;
  33204. }(BABYLON.RenderTargetTexture));
  33205. BABYLON.RefractionTexture = RefractionTexture;
  33206. })(BABYLON || (BABYLON = {}));
  33207. //# sourceMappingURL=babylon.refractionTexture.js.map
  33208. /// <reference path="babylon.texture.ts" />
  33209. var BABYLON;
  33210. (function (BABYLON) {
  33211. var DynamicTexture = (function (_super) {
  33212. __extends(DynamicTexture, _super);
  33213. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  33214. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33215. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  33216. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  33217. _this.name = name;
  33218. var engine = _this.getScene().getEngine();
  33219. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33220. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33221. _this._generateMipMaps = generateMipMaps;
  33222. if (options.getContext) {
  33223. _this._canvas = options;
  33224. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33225. }
  33226. else {
  33227. _this._canvas = document.createElement("canvas");
  33228. if (options.width) {
  33229. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33230. }
  33231. else {
  33232. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  33233. }
  33234. }
  33235. var textureSize = _this.getSize();
  33236. _this._canvas.width = textureSize.width;
  33237. _this._canvas.height = textureSize.height;
  33238. _this._context = _this._canvas.getContext("2d");
  33239. return _this;
  33240. }
  33241. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  33242. get: function () {
  33243. return true;
  33244. },
  33245. enumerable: true,
  33246. configurable: true
  33247. });
  33248. DynamicTexture.prototype._recreate = function (textureSize) {
  33249. this._canvas.width = textureSize.width;
  33250. this._canvas.height = textureSize.height;
  33251. this.releaseInternalTexture();
  33252. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  33253. };
  33254. DynamicTexture.prototype.scale = function (ratio) {
  33255. var textureSize = this.getSize();
  33256. textureSize.width *= ratio;
  33257. textureSize.height *= ratio;
  33258. this._recreate(textureSize);
  33259. };
  33260. DynamicTexture.prototype.scaleTo = function (width, height) {
  33261. var textureSize = this.getSize();
  33262. textureSize.width = width;
  33263. textureSize.height = height;
  33264. this._recreate(textureSize);
  33265. };
  33266. DynamicTexture.prototype.getContext = function () {
  33267. return this._context;
  33268. };
  33269. DynamicTexture.prototype.clear = function () {
  33270. var size = this.getSize();
  33271. this._context.fillRect(0, 0, size.width, size.height);
  33272. };
  33273. DynamicTexture.prototype.update = function (invertY) {
  33274. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  33275. };
  33276. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  33277. if (update === void 0) { update = true; }
  33278. var size = this.getSize();
  33279. if (clearColor) {
  33280. this._context.fillStyle = clearColor;
  33281. this._context.fillRect(0, 0, size.width, size.height);
  33282. }
  33283. this._context.font = font;
  33284. if (x === null || x === undefined) {
  33285. var textSize = this._context.measureText(text);
  33286. x = (size.width - textSize.width) / 2;
  33287. }
  33288. if (y === null || y === undefined) {
  33289. var fontSize = parseInt((font.replace(/\D/g, '')));
  33290. ;
  33291. y = (size.height / 2) + (fontSize / 3.65);
  33292. }
  33293. this._context.fillStyle = color;
  33294. this._context.fillText(text, x, y);
  33295. if (update) {
  33296. this.update(invertY);
  33297. }
  33298. };
  33299. DynamicTexture.prototype.clone = function () {
  33300. var textureSize = this.getSize();
  33301. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  33302. // Base texture
  33303. newTexture.hasAlpha = this.hasAlpha;
  33304. newTexture.level = this.level;
  33305. // Dynamic Texture
  33306. newTexture.wrapU = this.wrapU;
  33307. newTexture.wrapV = this.wrapV;
  33308. return newTexture;
  33309. };
  33310. return DynamicTexture;
  33311. }(BABYLON.Texture));
  33312. BABYLON.DynamicTexture = DynamicTexture;
  33313. })(BABYLON || (BABYLON = {}));
  33314. //# sourceMappingURL=babylon.dynamicTexture.js.map
  33315. var BABYLON;
  33316. (function (BABYLON) {
  33317. var VideoTexture = (function (_super) {
  33318. __extends(VideoTexture, _super);
  33319. /**
  33320. * Creates a video texture.
  33321. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  33322. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  33323. * @param {BABYLON.Scene} scene is obviously the current scene.
  33324. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  33325. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  33326. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  33327. */
  33328. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  33329. if (generateMipMaps === void 0) { generateMipMaps = false; }
  33330. if (invertY === void 0) { invertY = false; }
  33331. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33332. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33333. _this._autoLaunch = true;
  33334. var urls;
  33335. _this.name = name;
  33336. if (urlsOrVideo instanceof HTMLVideoElement) {
  33337. _this.video = urlsOrVideo;
  33338. }
  33339. else {
  33340. urls = urlsOrVideo;
  33341. _this.video = document.createElement("video");
  33342. _this.video.autoplay = false;
  33343. _this.video.loop = true;
  33344. }
  33345. _this._generateMipMaps = generateMipMaps;
  33346. _this._samplingMode = samplingMode;
  33347. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  33348. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33349. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33350. }
  33351. else {
  33352. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33353. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33354. _this._generateMipMaps = false;
  33355. }
  33356. if (urls) {
  33357. _this.video.addEventListener("canplay", function () {
  33358. _this._createTexture();
  33359. });
  33360. urls.forEach(function (url) {
  33361. var source = document.createElement("source");
  33362. source.src = url;
  33363. _this.video.appendChild(source);
  33364. });
  33365. }
  33366. else {
  33367. _this._createTexture();
  33368. }
  33369. _this._lastUpdate = BABYLON.Tools.Now;
  33370. return _this;
  33371. }
  33372. VideoTexture.prototype.__setTextureReady = function () {
  33373. this._texture.isReady = true;
  33374. };
  33375. VideoTexture.prototype._createTexture = function () {
  33376. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  33377. if (this._autoLaunch) {
  33378. this._autoLaunch = false;
  33379. this.video.play();
  33380. }
  33381. this._setTextureReady = this.__setTextureReady.bind(this);
  33382. this.video.addEventListener("playing", this._setTextureReady);
  33383. };
  33384. VideoTexture.prototype.update = function () {
  33385. var now = BABYLON.Tools.Now;
  33386. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  33387. return false;
  33388. }
  33389. this._lastUpdate = now;
  33390. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  33391. return true;
  33392. };
  33393. VideoTexture.prototype.dispose = function () {
  33394. _super.prototype.dispose.call(this);
  33395. this.video.removeEventListener("playing", this._setTextureReady);
  33396. };
  33397. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  33398. var video = document.createElement("video");
  33399. var constraintsDeviceId;
  33400. if (constraints && constraints.deviceId) {
  33401. constraintsDeviceId = {
  33402. exact: constraints.deviceId
  33403. };
  33404. }
  33405. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  33406. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  33407. if (navigator.getUserMedia) {
  33408. navigator.getUserMedia({
  33409. video: {
  33410. deviceId: constraintsDeviceId,
  33411. width: {
  33412. min: (constraints && constraints.minWidth) || 256,
  33413. max: (constraints && constraints.maxWidth) || 640
  33414. },
  33415. height: {
  33416. min: (constraints && constraints.minHeight) || 256,
  33417. max: (constraints && constraints.maxHeight) || 480
  33418. }
  33419. }
  33420. }, function (stream) {
  33421. if (video.mozSrcObject !== undefined) {
  33422. video.mozSrcObject = stream;
  33423. }
  33424. else {
  33425. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  33426. }
  33427. video.play();
  33428. if (onReady) {
  33429. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  33430. }
  33431. }, function (e) {
  33432. BABYLON.Tools.Error(e.name);
  33433. });
  33434. }
  33435. };
  33436. return VideoTexture;
  33437. }(BABYLON.Texture));
  33438. BABYLON.VideoTexture = VideoTexture;
  33439. })(BABYLON || (BABYLON = {}));
  33440. //# sourceMappingURL=babylon.videoTexture.js.map
  33441. var BABYLON;
  33442. (function (BABYLON) {
  33443. var RawTexture = (function (_super) {
  33444. __extends(RawTexture, _super);
  33445. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  33446. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33447. if (invertY === void 0) { invertY = false; }
  33448. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33449. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33450. _this.format = format;
  33451. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  33452. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33453. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33454. return _this;
  33455. }
  33456. RawTexture.prototype.update = function (data) {
  33457. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  33458. };
  33459. // Statics
  33460. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33461. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33462. if (invertY === void 0) { invertY = false; }
  33463. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33464. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  33465. };
  33466. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33467. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33468. if (invertY === void 0) { invertY = false; }
  33469. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33470. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33471. };
  33472. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33473. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33474. if (invertY === void 0) { invertY = false; }
  33475. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33476. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33477. };
  33478. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33479. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33480. if (invertY === void 0) { invertY = false; }
  33481. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33482. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  33483. };
  33484. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33485. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33486. if (invertY === void 0) { invertY = false; }
  33487. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33488. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  33489. };
  33490. return RawTexture;
  33491. }(BABYLON.Texture));
  33492. BABYLON.RawTexture = RawTexture;
  33493. })(BABYLON || (BABYLON = {}));
  33494. //# sourceMappingURL=babylon.rawTexture.js.map
  33495. var BABYLON;
  33496. (function (BABYLON) {
  33497. var Internals;
  33498. (function (Internals) {
  33499. /*
  33500. * Based on jsTGALoader - Javascript loader for TGA file
  33501. * By Vincent Thibault
  33502. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  33503. */
  33504. var TGATools = (function () {
  33505. function TGATools() {
  33506. }
  33507. TGATools.GetTGAHeader = function (data) {
  33508. var offset = 0;
  33509. var header = {
  33510. id_length: data[offset++],
  33511. colormap_type: data[offset++],
  33512. image_type: data[offset++],
  33513. colormap_index: data[offset++] | data[offset++] << 8,
  33514. colormap_length: data[offset++] | data[offset++] << 8,
  33515. colormap_size: data[offset++],
  33516. origin: [
  33517. data[offset++] | data[offset++] << 8,
  33518. data[offset++] | data[offset++] << 8
  33519. ],
  33520. width: data[offset++] | data[offset++] << 8,
  33521. height: data[offset++] | data[offset++] << 8,
  33522. pixel_size: data[offset++],
  33523. flags: data[offset++]
  33524. };
  33525. return header;
  33526. };
  33527. TGATools.UploadContent = function (gl, data) {
  33528. // Not enough data to contain header ?
  33529. if (data.length < 19) {
  33530. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  33531. return;
  33532. }
  33533. // Read Header
  33534. var offset = 18;
  33535. var header = TGATools.GetTGAHeader(data);
  33536. // Assume it's a valid Targa file.
  33537. if (header.id_length + offset > data.length) {
  33538. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  33539. return;
  33540. }
  33541. // Skip not needed data
  33542. offset += header.id_length;
  33543. var use_rle = false;
  33544. var use_pal = false;
  33545. var use_rgb = false;
  33546. var use_grey = false;
  33547. // Get some informations.
  33548. switch (header.image_type) {
  33549. case TGATools._TYPE_RLE_INDEXED:
  33550. use_rle = true;
  33551. case TGATools._TYPE_INDEXED:
  33552. use_pal = true;
  33553. break;
  33554. case TGATools._TYPE_RLE_RGB:
  33555. use_rle = true;
  33556. case TGATools._TYPE_RGB:
  33557. use_rgb = true;
  33558. break;
  33559. case TGATools._TYPE_RLE_GREY:
  33560. use_rle = true;
  33561. case TGATools._TYPE_GREY:
  33562. use_grey = true;
  33563. break;
  33564. }
  33565. var pixel_data;
  33566. var numAlphaBits = header.flags & 0xf;
  33567. var pixel_size = header.pixel_size >> 3;
  33568. var pixel_total = header.width * header.height * pixel_size;
  33569. // Read palettes
  33570. var palettes;
  33571. if (use_pal) {
  33572. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  33573. }
  33574. // Read LRE
  33575. if (use_rle) {
  33576. pixel_data = new Uint8Array(pixel_total);
  33577. var c, count, i;
  33578. var localOffset = 0;
  33579. var pixels = new Uint8Array(pixel_size);
  33580. while (offset < pixel_total && localOffset < pixel_total) {
  33581. c = data[offset++];
  33582. count = (c & 0x7f) + 1;
  33583. // RLE pixels
  33584. if (c & 0x80) {
  33585. // Bind pixel tmp array
  33586. for (i = 0; i < pixel_size; ++i) {
  33587. pixels[i] = data[offset++];
  33588. }
  33589. // Copy pixel array
  33590. for (i = 0; i < count; ++i) {
  33591. pixel_data.set(pixels, localOffset + i * pixel_size);
  33592. }
  33593. localOffset += pixel_size * count;
  33594. }
  33595. else {
  33596. count *= pixel_size;
  33597. for (i = 0; i < count; ++i) {
  33598. pixel_data[localOffset + i] = data[offset++];
  33599. }
  33600. localOffset += count;
  33601. }
  33602. }
  33603. }
  33604. else {
  33605. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  33606. }
  33607. // Load to texture
  33608. var x_start, y_start, x_step, y_step, y_end, x_end;
  33609. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  33610. default:
  33611. case TGATools._ORIGIN_UL:
  33612. x_start = 0;
  33613. x_step = 1;
  33614. x_end = header.width;
  33615. y_start = 0;
  33616. y_step = 1;
  33617. y_end = header.height;
  33618. break;
  33619. case TGATools._ORIGIN_BL:
  33620. x_start = 0;
  33621. x_step = 1;
  33622. x_end = header.width;
  33623. y_start = header.height - 1;
  33624. y_step = -1;
  33625. y_end = -1;
  33626. break;
  33627. case TGATools._ORIGIN_UR:
  33628. x_start = header.width - 1;
  33629. x_step = -1;
  33630. x_end = -1;
  33631. y_start = 0;
  33632. y_step = 1;
  33633. y_end = header.height;
  33634. break;
  33635. case TGATools._ORIGIN_BR:
  33636. x_start = header.width - 1;
  33637. x_step = -1;
  33638. x_end = -1;
  33639. y_start = header.height - 1;
  33640. y_step = -1;
  33641. y_end = -1;
  33642. break;
  33643. }
  33644. // Load the specify method
  33645. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  33646. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  33647. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  33648. };
  33649. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33650. var image = pixel_data, colormap = palettes;
  33651. var width = header.width, height = header.height;
  33652. var color, i = 0, x, y;
  33653. var imageData = new Uint8Array(width * height * 4);
  33654. for (y = y_start; y !== y_end; y += y_step) {
  33655. for (x = x_start; x !== x_end; x += x_step, i++) {
  33656. color = image[i];
  33657. imageData[(x + width * y) * 4 + 3] = 255;
  33658. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  33659. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  33660. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  33661. }
  33662. }
  33663. return imageData;
  33664. };
  33665. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33666. var image = pixel_data;
  33667. var width = header.width, height = header.height;
  33668. var color, i = 0, x, y;
  33669. var imageData = new Uint8Array(width * height * 4);
  33670. for (y = y_start; y !== y_end; y += y_step) {
  33671. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  33672. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  33673. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  33674. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  33675. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  33676. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  33677. }
  33678. }
  33679. return imageData;
  33680. };
  33681. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33682. var image = pixel_data;
  33683. var width = header.width, height = header.height;
  33684. var i = 0, x, y;
  33685. var imageData = new Uint8Array(width * height * 4);
  33686. for (y = y_start; y !== y_end; y += y_step) {
  33687. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  33688. imageData[(x + width * y) * 4 + 3] = 255;
  33689. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  33690. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  33691. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  33692. }
  33693. }
  33694. return imageData;
  33695. };
  33696. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33697. var image = pixel_data;
  33698. var width = header.width, height = header.height;
  33699. var i = 0, x, y;
  33700. var imageData = new Uint8Array(width * height * 4);
  33701. for (y = y_start; y !== y_end; y += y_step) {
  33702. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  33703. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  33704. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  33705. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  33706. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  33707. }
  33708. }
  33709. return imageData;
  33710. };
  33711. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33712. var image = pixel_data;
  33713. var width = header.width, height = header.height;
  33714. var color, i = 0, x, y;
  33715. var imageData = new Uint8Array(width * height * 4);
  33716. for (y = y_start; y !== y_end; y += y_step) {
  33717. for (x = x_start; x !== x_end; x += x_step, i++) {
  33718. color = image[i];
  33719. imageData[(x + width * y) * 4 + 0] = color;
  33720. imageData[(x + width * y) * 4 + 1] = color;
  33721. imageData[(x + width * y) * 4 + 2] = color;
  33722. imageData[(x + width * y) * 4 + 3] = 255;
  33723. }
  33724. }
  33725. return imageData;
  33726. };
  33727. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33728. var image = pixel_data;
  33729. var width = header.width, height = header.height;
  33730. var i = 0, x, y;
  33731. var imageData = new Uint8Array(width * height * 4);
  33732. for (y = y_start; y !== y_end; y += y_step) {
  33733. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  33734. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  33735. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  33736. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  33737. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  33738. }
  33739. }
  33740. return imageData;
  33741. };
  33742. TGATools._TYPE_NO_DATA = 0;
  33743. TGATools._TYPE_INDEXED = 1;
  33744. TGATools._TYPE_RGB = 2;
  33745. TGATools._TYPE_GREY = 3;
  33746. TGATools._TYPE_RLE_INDEXED = 9;
  33747. TGATools._TYPE_RLE_RGB = 10;
  33748. TGATools._TYPE_RLE_GREY = 11;
  33749. TGATools._ORIGIN_MASK = 0x30;
  33750. TGATools._ORIGIN_SHIFT = 0x04;
  33751. TGATools._ORIGIN_BL = 0x00;
  33752. TGATools._ORIGIN_BR = 0x01;
  33753. TGATools._ORIGIN_UL = 0x02;
  33754. TGATools._ORIGIN_UR = 0x03;
  33755. return TGATools;
  33756. }());
  33757. Internals.TGATools = TGATools;
  33758. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33759. })(BABYLON || (BABYLON = {}));
  33760. //# sourceMappingURL=babylon.tga.js.map
  33761. var BABYLON;
  33762. (function (BABYLON) {
  33763. var Internals;
  33764. (function (Internals) {
  33765. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  33766. // All values and structures referenced from:
  33767. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  33768. var DDS_MAGIC = 0x20534444;
  33769. 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;
  33770. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  33771. 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;
  33772. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  33773. function FourCCToInt32(value) {
  33774. return value.charCodeAt(0) +
  33775. (value.charCodeAt(1) << 8) +
  33776. (value.charCodeAt(2) << 16) +
  33777. (value.charCodeAt(3) << 24);
  33778. }
  33779. function Int32ToFourCC(value) {
  33780. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  33781. }
  33782. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  33783. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  33784. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  33785. var FOURCC_DX10 = FourCCToInt32("DX10");
  33786. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  33787. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  33788. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  33789. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  33790. var headerLengthInt = 31; // The header length in 32 bit ints
  33791. // Offsets into the header array
  33792. var off_magic = 0;
  33793. var off_size = 1;
  33794. var off_flags = 2;
  33795. var off_height = 3;
  33796. var off_width = 4;
  33797. var off_mipmapCount = 7;
  33798. var off_pfFlags = 20;
  33799. var off_pfFourCC = 21;
  33800. var off_RGBbpp = 22;
  33801. var off_RMask = 23;
  33802. var off_GMask = 24;
  33803. var off_BMask = 25;
  33804. var off_AMask = 26;
  33805. var off_caps1 = 27;
  33806. var off_caps2 = 28;
  33807. var off_caps3 = 29;
  33808. var off_caps4 = 30;
  33809. var off_dxgiFormat = 32;
  33810. ;
  33811. var DDSTools = (function () {
  33812. function DDSTools() {
  33813. }
  33814. DDSTools.GetDDSInfo = function (arrayBuffer) {
  33815. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  33816. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  33817. var mipmapCount = 1;
  33818. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  33819. mipmapCount = Math.max(1, header[off_mipmapCount]);
  33820. }
  33821. var fourCC = header[off_pfFourCC];
  33822. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  33823. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  33824. switch (fourCC) {
  33825. case FOURCC_D3DFMT_R16G16B16A16F:
  33826. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33827. break;
  33828. case FOURCC_D3DFMT_R32G32B32A32F:
  33829. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  33830. break;
  33831. case FOURCC_DX10:
  33832. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  33833. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33834. break;
  33835. }
  33836. }
  33837. return {
  33838. width: header[off_width],
  33839. height: header[off_height],
  33840. mipmapCount: mipmapCount,
  33841. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  33842. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  33843. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  33844. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  33845. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  33846. dxgiFormat: dxgiFormat,
  33847. textureType: textureType
  33848. };
  33849. };
  33850. DDSTools._ToHalfFloat = function (value) {
  33851. if (!DDSTools._FloatView) {
  33852. DDSTools._FloatView = new Float32Array(1);
  33853. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  33854. }
  33855. DDSTools._FloatView[0] = value;
  33856. var x = DDSTools._Int32View[0];
  33857. var bits = (x >> 16) & 0x8000; /* Get the sign */
  33858. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  33859. var e = (x >> 23) & 0xff; /* Using int is faster here */
  33860. /* If zero, or denormal, or exponent underflows too much for a denormal
  33861. * half, return signed zero. */
  33862. if (e < 103) {
  33863. return bits;
  33864. }
  33865. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  33866. if (e > 142) {
  33867. bits |= 0x7c00;
  33868. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  33869. * not Inf, so make sure we set one mantissa bit too. */
  33870. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  33871. return bits;
  33872. }
  33873. /* If exponent underflows but not too much, return a denormal */
  33874. if (e < 113) {
  33875. m |= 0x0800;
  33876. /* Extra rounding may overflow and set mantissa to 0 and exponent
  33877. * to 1, which is OK. */
  33878. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  33879. return bits;
  33880. }
  33881. bits |= ((e - 112) << 10) | (m >> 1);
  33882. bits += m & 1;
  33883. return bits;
  33884. };
  33885. DDSTools._FromHalfFloat = function (value) {
  33886. var s = (value & 0x8000) >> 15;
  33887. var e = (value & 0x7C00) >> 10;
  33888. var f = value & 0x03FF;
  33889. if (e === 0) {
  33890. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  33891. }
  33892. else if (e == 0x1F) {
  33893. return f ? NaN : ((s ? -1 : 1) * Infinity);
  33894. }
  33895. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  33896. };
  33897. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  33898. var destArray = new Float32Array(dataLength);
  33899. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  33900. var index = 0;
  33901. for (var y = 0; y < height; y++) {
  33902. for (var x = 0; x < width; x++) {
  33903. var srcPos = (x + y * width) * 4;
  33904. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  33905. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  33906. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  33907. if (DDSTools.StoreLODInAlphaChannel) {
  33908. destArray[index + 3] = lod;
  33909. }
  33910. else {
  33911. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  33912. }
  33913. index += 4;
  33914. }
  33915. }
  33916. return destArray;
  33917. };
  33918. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  33919. if (DDSTools.StoreLODInAlphaChannel) {
  33920. var destArray = new Uint16Array(dataLength);
  33921. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  33922. var index = 0;
  33923. for (var y = 0; y < height; y++) {
  33924. for (var x = 0; x < width; x++) {
  33925. var srcPos = (x + y * width) * 4;
  33926. destArray[index] = srcData[srcPos];
  33927. destArray[index + 1] = srcData[srcPos + 1];
  33928. destArray[index + 2] = srcData[srcPos + 2];
  33929. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  33930. index += 4;
  33931. }
  33932. }
  33933. return destArray;
  33934. }
  33935. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  33936. };
  33937. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  33938. if (DDSTools.StoreLODInAlphaChannel) {
  33939. var destArray = new Float32Array(dataLength);
  33940. var srcData = new Float32Array(arrayBuffer, dataOffset);
  33941. var index = 0;
  33942. for (var y = 0; y < height; y++) {
  33943. for (var x = 0; x < width; x++) {
  33944. var srcPos = (x + y * width) * 4;
  33945. destArray[index] = srcData[srcPos];
  33946. destArray[index + 1] = srcData[srcPos + 1];
  33947. destArray[index + 2] = srcData[srcPos + 2];
  33948. destArray[index + 3] = lod;
  33949. index += 4;
  33950. }
  33951. }
  33952. return destArray;
  33953. }
  33954. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  33955. };
  33956. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  33957. var destArray = new Uint8Array(dataLength);
  33958. var srcData = new Float32Array(arrayBuffer, dataOffset);
  33959. var index = 0;
  33960. for (var y = 0; y < height; y++) {
  33961. for (var x = 0; x < width; x++) {
  33962. var srcPos = (x + y * width) * 4;
  33963. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  33964. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  33965. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  33966. if (DDSTools.StoreLODInAlphaChannel) {
  33967. destArray[index + 3] = lod;
  33968. }
  33969. else {
  33970. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  33971. }
  33972. index += 4;
  33973. }
  33974. }
  33975. return destArray;
  33976. };
  33977. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  33978. var destArray = new Uint8Array(dataLength);
  33979. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  33980. var index = 0;
  33981. for (var y = 0; y < height; y++) {
  33982. for (var x = 0; x < width; x++) {
  33983. var srcPos = (x + y * width) * 4;
  33984. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  33985. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  33986. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  33987. if (DDSTools.StoreLODInAlphaChannel) {
  33988. destArray[index + 3] = lod;
  33989. }
  33990. else {
  33991. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  33992. }
  33993. index += 4;
  33994. }
  33995. }
  33996. return destArray;
  33997. };
  33998. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33999. var byteArray = new Uint8Array(dataLength);
  34000. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34001. var index = 0;
  34002. for (var y = 0; y < height; y++) {
  34003. for (var x = 0; x < width; x++) {
  34004. var srcPos = (x + y * width) * 4;
  34005. byteArray[index] = srcData[srcPos + 2];
  34006. byteArray[index + 1] = srcData[srcPos + 1];
  34007. byteArray[index + 2] = srcData[srcPos];
  34008. byteArray[index + 3] = srcData[srcPos + 3];
  34009. index += 4;
  34010. }
  34011. }
  34012. return byteArray;
  34013. };
  34014. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34015. var byteArray = new Uint8Array(dataLength);
  34016. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34017. var index = 0;
  34018. for (var y = 0; y < height; y++) {
  34019. for (var x = 0; x < width; x++) {
  34020. var srcPos = (x + y * width) * 3;
  34021. byteArray[index] = srcData[srcPos + 2];
  34022. byteArray[index + 1] = srcData[srcPos + 1];
  34023. byteArray[index + 2] = srcData[srcPos];
  34024. index += 3;
  34025. }
  34026. }
  34027. return byteArray;
  34028. };
  34029. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34030. var byteArray = new Uint8Array(dataLength);
  34031. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34032. var index = 0;
  34033. for (var y = 0; y < height; y++) {
  34034. for (var x = 0; x < width; x++) {
  34035. var srcPos = (x + y * width);
  34036. byteArray[index] = srcData[srcPos];
  34037. index++;
  34038. }
  34039. }
  34040. return byteArray;
  34041. };
  34042. DDSTools.UploadDDSLevels = function (engine, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  34043. if (lodIndex === void 0) { lodIndex = -1; }
  34044. var gl = engine._gl;
  34045. var ext = engine.getCaps().s3tc;
  34046. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  34047. if (header[off_magic] != DDS_MAGIC) {
  34048. BABYLON.Tools.Error("Invalid magic number in DDS header");
  34049. return;
  34050. }
  34051. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  34052. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  34053. return;
  34054. }
  34055. if (info.isCompressed && !ext) {
  34056. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  34057. return;
  34058. }
  34059. var bpp = header[off_RGBbpp];
  34060. dataOffset = header[off_size] + 4;
  34061. var computeFormats = false;
  34062. if (info.isFourCC) {
  34063. fourCC = header[off_pfFourCC];
  34064. switch (fourCC) {
  34065. case FOURCC_DXT1:
  34066. blockBytes = 8;
  34067. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  34068. break;
  34069. case FOURCC_DXT3:
  34070. blockBytes = 16;
  34071. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  34072. break;
  34073. case FOURCC_DXT5:
  34074. blockBytes = 16;
  34075. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  34076. break;
  34077. case FOURCC_D3DFMT_R16G16B16A16F:
  34078. computeFormats = true;
  34079. break;
  34080. case FOURCC_D3DFMT_R32G32B32A32F:
  34081. computeFormats = true;
  34082. break;
  34083. case FOURCC_DX10:
  34084. // There is an additionnal header so dataOffset need to be changed
  34085. dataOffset += 5 * 4; // 5 uints
  34086. var supported = false;
  34087. switch (info.dxgiFormat) {
  34088. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  34089. computeFormats = true;
  34090. supported = true;
  34091. break;
  34092. case DXGI_FORMAT_B8G8R8X8_UNORM:
  34093. info.isRGB = true;
  34094. info.isFourCC = false;
  34095. bpp = 32;
  34096. supported = true;
  34097. break;
  34098. }
  34099. if (supported) {
  34100. break;
  34101. }
  34102. default:
  34103. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  34104. return;
  34105. }
  34106. }
  34107. if (computeFormats) {
  34108. format = engine._getWebGLTextureType(info.textureType);
  34109. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34110. }
  34111. mipmapCount = 1;
  34112. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  34113. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34114. }
  34115. for (var face = 0; face < faces; face++) {
  34116. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34117. width = header[off_width];
  34118. height = header[off_height];
  34119. for (mip = 0; mip < mipmapCount; ++mip) {
  34120. if (lodIndex === -1 || lodIndex === mip) {
  34121. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  34122. var i = (lodIndex === -1) ? mip : 0;
  34123. if (!info.isCompressed && info.isFourCC) {
  34124. dataLength = width * height * 4;
  34125. var floatArray;
  34126. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  34127. if (bpp === 128) {
  34128. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34129. }
  34130. else if (bpp === 64) {
  34131. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34132. }
  34133. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34134. format = engine._getWebGLTextureType(info.textureType);
  34135. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34136. }
  34137. else {
  34138. if (bpp === 128) {
  34139. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34140. }
  34141. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  34142. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34143. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34144. format = engine._getWebGLTextureType(info.textureType);
  34145. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34146. }
  34147. else {
  34148. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34149. }
  34150. }
  34151. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  34152. }
  34153. else if (info.isRGB) {
  34154. if (bpp === 24) {
  34155. dataLength = width * height * 3;
  34156. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34157. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  34158. }
  34159. else {
  34160. dataLength = width * height * 4;
  34161. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34162. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  34163. }
  34164. }
  34165. else if (info.isLuminance) {
  34166. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  34167. var unpaddedRowSize = width;
  34168. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  34169. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  34170. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34171. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  34172. }
  34173. else {
  34174. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  34175. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  34176. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  34177. }
  34178. }
  34179. dataOffset += width * height * (bpp / 8);
  34180. width *= 0.5;
  34181. height *= 0.5;
  34182. width = Math.max(1.0, width);
  34183. height = Math.max(1.0, height);
  34184. }
  34185. }
  34186. };
  34187. DDSTools.StoreLODInAlphaChannel = false;
  34188. return DDSTools;
  34189. }());
  34190. Internals.DDSTools = DDSTools;
  34191. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34192. })(BABYLON || (BABYLON = {}));
  34193. //# sourceMappingURL=babylon.dds.js.map
  34194. var BABYLON;
  34195. (function (BABYLON) {
  34196. var Internals;
  34197. (function (Internals) {
  34198. /**
  34199. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  34200. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  34201. */
  34202. var KhronosTextureContainer = (function () {
  34203. /**
  34204. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  34205. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  34206. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  34207. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  34208. */
  34209. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  34210. this.arrayBuffer = arrayBuffer;
  34211. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  34212. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  34213. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  34214. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  34215. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  34216. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  34217. BABYLON.Tools.Error("texture missing KTX identifier");
  34218. return;
  34219. }
  34220. // load the reset of the header in native 32 bit int
  34221. var header = new Int32Array(this.arrayBuffer, 12, 13);
  34222. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  34223. var oppositeEndianess = header[0] === 0x01020304;
  34224. // read all the header elements in order they exist in the file, without modification (sans endainness)
  34225. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  34226. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  34227. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  34228. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  34229. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  34230. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  34231. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  34232. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  34233. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  34234. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  34235. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  34236. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  34237. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  34238. if (this.glType !== 0) {
  34239. BABYLON.Tools.Error("only compressed formats currently supported");
  34240. return;
  34241. }
  34242. else {
  34243. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  34244. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  34245. }
  34246. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  34247. BABYLON.Tools.Error("only 2D textures currently supported");
  34248. return;
  34249. }
  34250. if (this.numberOfArrayElements !== 0) {
  34251. BABYLON.Tools.Error("texture arrays not currently supported");
  34252. return;
  34253. }
  34254. if (this.numberOfFaces !== facesExpected) {
  34255. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  34256. return;
  34257. }
  34258. // we now have a completely validated file, so could use existence of loadType as success
  34259. // would need to make this more elaborate & adjust checks above to support more than one load type
  34260. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  34261. }
  34262. // not as fast hardware based, but will probably never need to use
  34263. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  34264. return ((val & 0xFF) << 24)
  34265. | ((val & 0xFF00) << 8)
  34266. | ((val >> 8) & 0xFF00)
  34267. | ((val >> 24) & 0xFF);
  34268. };
  34269. /**
  34270. * It is assumed that the texture has already been created & is currently bound
  34271. */
  34272. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  34273. switch (this.loadType) {
  34274. case KhronosTextureContainer.COMPRESSED_2D:
  34275. this._upload2DCompressedLevels(gl, loadMipmaps);
  34276. break;
  34277. case KhronosTextureContainer.TEX_2D:
  34278. case KhronosTextureContainer.COMPRESSED_3D:
  34279. case KhronosTextureContainer.TEX_3D:
  34280. }
  34281. };
  34282. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  34283. // initialize width & height for level 1
  34284. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  34285. var width = this.pixelWidth;
  34286. var height = this.pixelHeight;
  34287. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  34288. for (var level = 0; level < mipmapCount; level++) {
  34289. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  34290. for (var face = 0; face < this.numberOfFaces; face++) {
  34291. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34292. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  34293. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  34294. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  34295. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  34296. }
  34297. width = Math.max(1.0, width * 0.5);
  34298. height = Math.max(1.0, height * 0.5);
  34299. }
  34300. };
  34301. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  34302. // load types
  34303. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  34304. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  34305. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  34306. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  34307. return KhronosTextureContainer;
  34308. }());
  34309. Internals.KhronosTextureContainer = KhronosTextureContainer;
  34310. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34311. })(BABYLON || (BABYLON = {}));
  34312. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  34313. var BABYLON;
  34314. (function (BABYLON) {
  34315. var PostProcess = (function () {
  34316. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  34317. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  34318. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34319. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  34320. if (blockCompilation === void 0) { blockCompilation = false; }
  34321. this.name = name;
  34322. this.width = -1;
  34323. this.height = -1;
  34324. this.autoClear = true;
  34325. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  34326. /*
  34327. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  34328. Can only be used on a single postprocess or on the last one of a chain.
  34329. */
  34330. this.enablePixelPerfectMode = false;
  34331. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  34332. this.alwaysForcePOT = false;
  34333. this.samples = 1;
  34334. this._reusable = false;
  34335. this._textures = new BABYLON.SmartArray(2);
  34336. this._currentRenderTextureInd = 0;
  34337. this._scaleRatio = new BABYLON.Vector2(1, 1);
  34338. this._texelSize = BABYLON.Vector2.Zero();
  34339. // Events
  34340. /**
  34341. * An event triggered when the postprocess is activated.
  34342. * @type {BABYLON.Observable}
  34343. */
  34344. this.onActivateObservable = new BABYLON.Observable();
  34345. /**
  34346. * An event triggered when the postprocess changes its size.
  34347. * @type {BABYLON.Observable}
  34348. */
  34349. this.onSizeChangedObservable = new BABYLON.Observable();
  34350. /**
  34351. * An event triggered when the postprocess applies its effect.
  34352. * @type {BABYLON.Observable}
  34353. */
  34354. this.onApplyObservable = new BABYLON.Observable();
  34355. /**
  34356. * An event triggered before rendering the postprocess
  34357. * @type {BABYLON.Observable}
  34358. */
  34359. this.onBeforeRenderObservable = new BABYLON.Observable();
  34360. /**
  34361. * An event triggered after rendering the postprocess
  34362. * @type {BABYLON.Observable}
  34363. */
  34364. this.onAfterRenderObservable = new BABYLON.Observable();
  34365. if (camera != null) {
  34366. this._camera = camera;
  34367. this._scene = camera.getScene();
  34368. camera.attachPostProcess(this);
  34369. this._engine = this._scene.getEngine();
  34370. }
  34371. else {
  34372. this._engine = engine;
  34373. }
  34374. this._options = options;
  34375. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  34376. this._reusable = reusable || false;
  34377. this._textureType = textureType;
  34378. this._samplers = samplers || [];
  34379. this._samplers.push("textureSampler");
  34380. this._fragmentUrl = fragmentUrl;
  34381. this._vertexUrl = vertexUrl;
  34382. this._parameters = parameters || [];
  34383. this._parameters.push("scale");
  34384. this._indexParameters = indexParameters;
  34385. if (!blockCompilation) {
  34386. this.updateEffect(defines);
  34387. }
  34388. }
  34389. Object.defineProperty(PostProcess.prototype, "onActivate", {
  34390. set: function (callback) {
  34391. if (this._onActivateObserver) {
  34392. this.onActivateObservable.remove(this._onActivateObserver);
  34393. }
  34394. this._onActivateObserver = this.onActivateObservable.add(callback);
  34395. },
  34396. enumerable: true,
  34397. configurable: true
  34398. });
  34399. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  34400. set: function (callback) {
  34401. if (this._onSizeChangedObserver) {
  34402. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  34403. }
  34404. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  34405. },
  34406. enumerable: true,
  34407. configurable: true
  34408. });
  34409. Object.defineProperty(PostProcess.prototype, "onApply", {
  34410. set: function (callback) {
  34411. if (this._onApplyObserver) {
  34412. this.onApplyObservable.remove(this._onApplyObserver);
  34413. }
  34414. this._onApplyObserver = this.onApplyObservable.add(callback);
  34415. },
  34416. enumerable: true,
  34417. configurable: true
  34418. });
  34419. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  34420. set: function (callback) {
  34421. if (this._onBeforeRenderObserver) {
  34422. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  34423. }
  34424. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  34425. },
  34426. enumerable: true,
  34427. configurable: true
  34428. });
  34429. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  34430. set: function (callback) {
  34431. if (this._onAfterRenderObserver) {
  34432. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  34433. }
  34434. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  34435. },
  34436. enumerable: true,
  34437. configurable: true
  34438. });
  34439. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  34440. get: function () {
  34441. return this._textures.data[this._currentRenderTextureInd];
  34442. },
  34443. set: function (value) {
  34444. this._forcedOutputTexture = value;
  34445. },
  34446. enumerable: true,
  34447. configurable: true
  34448. });
  34449. PostProcess.prototype.getCamera = function () {
  34450. return this._camera;
  34451. };
  34452. Object.defineProperty(PostProcess.prototype, "texelSize", {
  34453. get: function () {
  34454. if (this._shareOutputWithPostProcess) {
  34455. return this._shareOutputWithPostProcess.texelSize;
  34456. }
  34457. if (this._forcedOutputTexture) {
  34458. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  34459. }
  34460. return this._texelSize;
  34461. },
  34462. enumerable: true,
  34463. configurable: true
  34464. });
  34465. PostProcess.prototype.getEngine = function () {
  34466. return this._engine;
  34467. };
  34468. PostProcess.prototype.getEffect = function () {
  34469. return this._effect;
  34470. };
  34471. PostProcess.prototype.shareOutputWith = function (postProcess) {
  34472. this._disposeTextures();
  34473. this._shareOutputWithPostProcess = postProcess;
  34474. return this;
  34475. };
  34476. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  34477. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, onCompiled, onError, indexParameters || this._indexParameters);
  34478. };
  34479. PostProcess.prototype.isReusable = function () {
  34480. return this._reusable;
  34481. };
  34482. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  34483. PostProcess.prototype.markTextureDirty = function () {
  34484. this.width = -1;
  34485. };
  34486. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  34487. var _this = this;
  34488. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  34489. camera = camera || this._camera;
  34490. var scene = camera.getScene();
  34491. var engine = scene.getEngine();
  34492. var maxSize = engine.getCaps().maxTextureSize;
  34493. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  34494. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  34495. var desiredWidth = this._options.width || requiredWidth;
  34496. var desiredHeight = this._options.height || requiredHeight;
  34497. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  34498. if (!this._options.width) {
  34499. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  34500. }
  34501. if (!this._options.height) {
  34502. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  34503. }
  34504. }
  34505. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  34506. if (this._textures.length > 0) {
  34507. for (var i = 0; i < this._textures.length; i++) {
  34508. this._engine._releaseTexture(this._textures.data[i]);
  34509. }
  34510. this._textures.reset();
  34511. }
  34512. this.width = desiredWidth;
  34513. this.height = desiredHeight;
  34514. var textureSize = { width: this.width, height: this.height };
  34515. var textureOptions = {
  34516. generateMipMaps: false,
  34517. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  34518. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  34519. samplingMode: this.renderTargetSamplingMode,
  34520. type: this._textureType
  34521. };
  34522. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  34523. if (this._reusable) {
  34524. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  34525. }
  34526. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  34527. this.onSizeChangedObservable.notifyObservers(this);
  34528. }
  34529. this._textures.forEach(function (texture) {
  34530. if (texture.samples !== _this.samples) {
  34531. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  34532. }
  34533. });
  34534. }
  34535. var target;
  34536. if (this._shareOutputWithPostProcess) {
  34537. target = this._shareOutputWithPostProcess.outputTexture;
  34538. }
  34539. else if (this._forcedOutputTexture) {
  34540. target = this._forcedOutputTexture;
  34541. this.width = this._forcedOutputTexture._width;
  34542. this.height = this._forcedOutputTexture._height;
  34543. }
  34544. else {
  34545. target = this.outputTexture;
  34546. }
  34547. if (this.enablePixelPerfectMode) {
  34548. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  34549. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  34550. }
  34551. else {
  34552. this._scaleRatio.copyFromFloats(1, 1);
  34553. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  34554. }
  34555. this.onActivateObservable.notifyObservers(camera);
  34556. // Clear
  34557. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  34558. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  34559. }
  34560. if (this._reusable) {
  34561. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  34562. }
  34563. };
  34564. Object.defineProperty(PostProcess.prototype, "isSupported", {
  34565. get: function () {
  34566. return this._effect.isSupported;
  34567. },
  34568. enumerable: true,
  34569. configurable: true
  34570. });
  34571. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  34572. get: function () {
  34573. if (this._shareOutputWithPostProcess) {
  34574. return this._shareOutputWithPostProcess.aspectRatio;
  34575. }
  34576. if (this._forcedOutputTexture) {
  34577. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  34578. }
  34579. return this.width / this.height;
  34580. },
  34581. enumerable: true,
  34582. configurable: true
  34583. });
  34584. PostProcess.prototype.apply = function () {
  34585. // Check
  34586. if (!this._effect || !this._effect.isReady())
  34587. return null;
  34588. // States
  34589. this._engine.enableEffect(this._effect);
  34590. this._engine.setState(false);
  34591. this._engine.setDepthBuffer(false);
  34592. this._engine.setDepthWrite(false);
  34593. // Alpha
  34594. this._engine.setAlphaMode(this.alphaMode);
  34595. if (this.alphaConstants) {
  34596. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  34597. }
  34598. // Texture
  34599. var source;
  34600. if (this._shareOutputWithPostProcess) {
  34601. source = this._shareOutputWithPostProcess.outputTexture;
  34602. }
  34603. else if (this._forcedOutputTexture) {
  34604. source = this._forcedOutputTexture;
  34605. }
  34606. else {
  34607. source = this.outputTexture;
  34608. }
  34609. this._effect._bindTexture("textureSampler", source);
  34610. // Parameters
  34611. this._effect.setVector2("scale", this._scaleRatio);
  34612. this.onApplyObservable.notifyObservers(this._effect);
  34613. return this._effect;
  34614. };
  34615. PostProcess.prototype._disposeTextures = function () {
  34616. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  34617. return;
  34618. }
  34619. if (this._textures.length > 0) {
  34620. for (var i = 0; i < this._textures.length; i++) {
  34621. this._engine._releaseTexture(this._textures.data[i]);
  34622. }
  34623. }
  34624. this._textures.dispose();
  34625. };
  34626. PostProcess.prototype.dispose = function (camera) {
  34627. camera = camera || this._camera;
  34628. this._disposeTextures();
  34629. if (!camera) {
  34630. return;
  34631. }
  34632. camera.detachPostProcess(this);
  34633. var index = camera._postProcesses.indexOf(this);
  34634. if (index === 0 && camera._postProcesses.length > 0) {
  34635. this._camera._postProcesses[0].markTextureDirty();
  34636. }
  34637. this.onActivateObservable.clear();
  34638. this.onAfterRenderObservable.clear();
  34639. this.onApplyObservable.clear();
  34640. this.onBeforeRenderObservable.clear();
  34641. this.onSizeChangedObservable.clear();
  34642. };
  34643. return PostProcess;
  34644. }());
  34645. BABYLON.PostProcess = PostProcess;
  34646. })(BABYLON || (BABYLON = {}));
  34647. //# sourceMappingURL=babylon.postProcess.js.map
  34648. var BABYLON;
  34649. (function (BABYLON) {
  34650. var PassPostProcess = (function (_super) {
  34651. __extends(PassPostProcess, _super);
  34652. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  34653. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34654. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  34655. }
  34656. return PassPostProcess;
  34657. }(BABYLON.PostProcess));
  34658. BABYLON.PassPostProcess = PassPostProcess;
  34659. })(BABYLON || (BABYLON = {}));
  34660. //# sourceMappingURL=babylon.passPostProcess.js.map
  34661. var BABYLON;
  34662. (function (BABYLON) {
  34663. var ShadowGenerator = (function () {
  34664. /**
  34665. * Creates a ShadowGenerator object.
  34666. * A ShadowGenerator is the required tool to use the shadows.
  34667. * Each light casting shadows needs to use its own ShadowGenerator.
  34668. * Required parameters :
  34669. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  34670. * - `light`: the light object generating the shadows.
  34671. * - `useFullFloatFirst`: by default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  34672. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  34673. */
  34674. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  34675. // Members
  34676. this._bias = 0.00005;
  34677. this._blurBoxOffset = 1;
  34678. this._blurScale = 2;
  34679. this._blurKernel = 1;
  34680. this._useKernelBlur = false;
  34681. this._filter = ShadowGenerator.FILTER_NONE;
  34682. this._darkness = 0;
  34683. this._transparencyShadow = false;
  34684. /**
  34685. * Controls the extent to which the shadows fade out at the edge of the frustum
  34686. * Used only by directionals and spots
  34687. */
  34688. this.frustumEdgeFalloff = 0;
  34689. this.forceBackFacesOnly = false;
  34690. this._lightDirection = BABYLON.Vector3.Zero();
  34691. this._viewMatrix = BABYLON.Matrix.Zero();
  34692. this._projectionMatrix = BABYLON.Matrix.Zero();
  34693. this._transformMatrix = BABYLON.Matrix.Zero();
  34694. this._worldViewProjection = BABYLON.Matrix.Zero();
  34695. this._currentFaceIndex = 0;
  34696. this._currentFaceIndexCache = 0;
  34697. this._isCube = false;
  34698. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  34699. this._mapSize = mapSize;
  34700. this._light = light;
  34701. this._scene = light.getScene();
  34702. light._shadowGenerator = this;
  34703. // Texture type fallback from float to int if not supported.
  34704. var caps = this._scene.getEngine().getCaps();
  34705. if (!useFullFloatFirst) {
  34706. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  34707. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34708. }
  34709. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  34710. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34711. }
  34712. else {
  34713. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34714. }
  34715. }
  34716. else {
  34717. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  34718. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34719. }
  34720. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  34721. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34722. }
  34723. else {
  34724. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34725. }
  34726. }
  34727. this._initializeGenerator();
  34728. }
  34729. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  34730. // Static
  34731. get: function () {
  34732. return ShadowGenerator._FILTER_NONE;
  34733. },
  34734. enumerable: true,
  34735. configurable: true
  34736. });
  34737. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  34738. get: function () {
  34739. return ShadowGenerator._FILTER_POISSONSAMPLING;
  34740. },
  34741. enumerable: true,
  34742. configurable: true
  34743. });
  34744. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  34745. get: function () {
  34746. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  34747. },
  34748. enumerable: true,
  34749. configurable: true
  34750. });
  34751. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  34752. get: function () {
  34753. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  34754. },
  34755. enumerable: true,
  34756. configurable: true
  34757. });
  34758. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  34759. get: function () {
  34760. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  34761. },
  34762. enumerable: true,
  34763. configurable: true
  34764. });
  34765. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  34766. get: function () {
  34767. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  34768. },
  34769. enumerable: true,
  34770. configurable: true
  34771. });
  34772. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  34773. get: function () {
  34774. return this._bias;
  34775. },
  34776. set: function (bias) {
  34777. this._bias = bias;
  34778. },
  34779. enumerable: true,
  34780. configurable: true
  34781. });
  34782. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  34783. get: function () {
  34784. return this._blurBoxOffset;
  34785. },
  34786. set: function (value) {
  34787. if (this._blurBoxOffset === value) {
  34788. return;
  34789. }
  34790. this._blurBoxOffset = value;
  34791. this._disposeBlurPostProcesses();
  34792. },
  34793. enumerable: true,
  34794. configurable: true
  34795. });
  34796. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  34797. get: function () {
  34798. return this._blurScale;
  34799. },
  34800. set: function (value) {
  34801. if (this._blurScale === value) {
  34802. return;
  34803. }
  34804. this._blurScale = value;
  34805. this._disposeBlurPostProcesses();
  34806. },
  34807. enumerable: true,
  34808. configurable: true
  34809. });
  34810. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  34811. get: function () {
  34812. return this._blurKernel;
  34813. },
  34814. set: function (value) {
  34815. if (this._blurKernel === value) {
  34816. return;
  34817. }
  34818. this._blurKernel = value;
  34819. this._disposeBlurPostProcesses();
  34820. },
  34821. enumerable: true,
  34822. configurable: true
  34823. });
  34824. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  34825. get: function () {
  34826. return this._useKernelBlur;
  34827. },
  34828. set: function (value) {
  34829. if (this._useKernelBlur === value) {
  34830. return;
  34831. }
  34832. this._useKernelBlur = value;
  34833. this._disposeBlurPostProcesses();
  34834. },
  34835. enumerable: true,
  34836. configurable: true
  34837. });
  34838. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  34839. get: function () {
  34840. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  34841. },
  34842. set: function (value) {
  34843. this._depthScale = value;
  34844. },
  34845. enumerable: true,
  34846. configurable: true
  34847. });
  34848. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  34849. get: function () {
  34850. return this._filter;
  34851. },
  34852. set: function (value) {
  34853. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  34854. if (this._light.needCube()) {
  34855. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  34856. this.useExponentialShadowMap = true;
  34857. return;
  34858. }
  34859. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  34860. this.useCloseExponentialShadowMap = true;
  34861. return;
  34862. }
  34863. }
  34864. if (this._filter === value) {
  34865. return;
  34866. }
  34867. this._filter = value;
  34868. this._disposeBlurPostProcesses();
  34869. this._applyFilterValues();
  34870. this._light._markMeshesAsLightDirty();
  34871. },
  34872. enumerable: true,
  34873. configurable: true
  34874. });
  34875. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  34876. get: function () {
  34877. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  34878. },
  34879. set: function (value) {
  34880. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  34881. },
  34882. enumerable: true,
  34883. configurable: true
  34884. });
  34885. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  34886. get: function () {
  34887. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  34888. return this.useExponentialShadowMap;
  34889. },
  34890. set: function (value) {
  34891. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  34892. this.useExponentialShadowMap = value;
  34893. },
  34894. enumerable: true,
  34895. configurable: true
  34896. });
  34897. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  34898. get: function () {
  34899. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  34900. return this.useBlurExponentialShadowMap;
  34901. },
  34902. set: function (value) {
  34903. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  34904. this.useBlurExponentialShadowMap = value;
  34905. },
  34906. enumerable: true,
  34907. configurable: true
  34908. });
  34909. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  34910. get: function () {
  34911. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  34912. },
  34913. set: function (value) {
  34914. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  34915. },
  34916. enumerable: true,
  34917. configurable: true
  34918. });
  34919. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  34920. get: function () {
  34921. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  34922. },
  34923. set: function (value) {
  34924. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  34925. },
  34926. enumerable: true,
  34927. configurable: true
  34928. });
  34929. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  34930. get: function () {
  34931. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  34932. },
  34933. set: function (value) {
  34934. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  34935. },
  34936. enumerable: true,
  34937. configurable: true
  34938. });
  34939. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  34940. get: function () {
  34941. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  34942. },
  34943. set: function (value) {
  34944. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  34945. },
  34946. enumerable: true,
  34947. configurable: true
  34948. });
  34949. /**
  34950. * Returns the darkness value (float).
  34951. */
  34952. ShadowGenerator.prototype.getDarkness = function () {
  34953. return this._darkness;
  34954. };
  34955. /**
  34956. * Sets the ShadowGenerator darkness value (float <= 1.0).
  34957. * Returns the ShadowGenerator.
  34958. */
  34959. ShadowGenerator.prototype.setDarkness = function (darkness) {
  34960. if (darkness >= 1.0)
  34961. this._darkness = 1.0;
  34962. else if (darkness <= 0.0)
  34963. this._darkness = 0.0;
  34964. else
  34965. this._darkness = darkness;
  34966. return this;
  34967. };
  34968. /**
  34969. * Sets the ability to have transparent shadow (boolean).
  34970. * Returns the ShadowGenerator.
  34971. */
  34972. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  34973. this._transparencyShadow = hasShadow;
  34974. return this;
  34975. };
  34976. /**
  34977. * Returns a RenderTargetTexture object : the shadow map texture.
  34978. */
  34979. ShadowGenerator.prototype.getShadowMap = function () {
  34980. return this._shadowMap;
  34981. };
  34982. /**
  34983. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  34984. */
  34985. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  34986. if (this._shadowMap2) {
  34987. return this._shadowMap2;
  34988. }
  34989. return this._shadowMap;
  34990. };
  34991. /**
  34992. * Returns the associated light object.
  34993. */
  34994. ShadowGenerator.prototype.getLight = function () {
  34995. return this._light;
  34996. };
  34997. ShadowGenerator.prototype._initializeGenerator = function () {
  34998. this._light._markMeshesAsLightDirty();
  34999. this._initializeShadowMap();
  35000. };
  35001. ShadowGenerator.prototype._initializeShadowMap = function () {
  35002. var _this = this;
  35003. // Render target
  35004. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  35005. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35006. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35007. this._shadowMap.anisotropicFilteringLevel = 1;
  35008. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35009. this._shadowMap.renderParticles = false;
  35010. // Record Face Index before render.
  35011. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  35012. _this._currentFaceIndex = faceIndex;
  35013. });
  35014. // Custom render function.
  35015. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  35016. // Blur if required afer render.
  35017. this._shadowMap.onAfterUnbindObservable.add(function () {
  35018. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  35019. return;
  35020. }
  35021. if (!_this._blurPostProcesses) {
  35022. _this._initializeBlurRTTAndPostProcesses();
  35023. }
  35024. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  35025. });
  35026. // Clear according to the chosen filter.
  35027. this._shadowMap.onClearObservable.add(function (engine) {
  35028. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  35029. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  35030. }
  35031. else {
  35032. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  35033. }
  35034. });
  35035. };
  35036. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  35037. var _this = this;
  35038. var engine = this._scene.getEngine();
  35039. var targetSize = this._mapSize / this.blurScale;
  35040. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  35041. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  35042. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35043. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35044. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35045. }
  35046. if (this.useKernelBlur) {
  35047. this._kernelBlurXPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurX", new BABYLON.Vector2(1, 0), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  35048. this._kernelBlurXPostprocess.width = targetSize;
  35049. this._kernelBlurXPostprocess.height = targetSize;
  35050. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  35051. effect.setTexture("textureSampler", _this._shadowMap);
  35052. });
  35053. this._kernelBlurYPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurY", new BABYLON.Vector2(0, 1), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  35054. this._kernelBlurXPostprocess.autoClear = false;
  35055. this._kernelBlurYPostprocess.autoClear = false;
  35056. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35057. this._kernelBlurXPostprocess.packedFloat = true;
  35058. this._kernelBlurYPostprocess.packedFloat = true;
  35059. }
  35060. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  35061. }
  35062. else {
  35063. this._boxBlurPostprocess = new BABYLON.PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
  35064. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  35065. effect.setFloat2("screenSize", targetSize, targetSize);
  35066. effect.setTexture("textureSampler", _this._shadowMap);
  35067. });
  35068. this._boxBlurPostprocess.autoClear = false;
  35069. this._blurPostProcesses = [this._boxBlurPostprocess];
  35070. }
  35071. };
  35072. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35073. var index;
  35074. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35075. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  35076. }
  35077. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35078. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  35079. }
  35080. if (this._transparencyShadow) {
  35081. for (index = 0; index < transparentSubMeshes.length; index++) {
  35082. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  35083. }
  35084. }
  35085. };
  35086. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  35087. var _this = this;
  35088. var mesh = subMesh.getRenderingMesh();
  35089. var scene = this._scene;
  35090. var engine = scene.getEngine();
  35091. // Culling
  35092. engine.setState(subMesh.getMaterial().backFaceCulling);
  35093. // Managing instances
  35094. var batch = mesh._getInstancesRenderList(subMesh._id);
  35095. if (batch.mustReturn) {
  35096. return;
  35097. }
  35098. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  35099. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  35100. engine.enableEffect(this._effect);
  35101. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  35102. var material = subMesh.getMaterial();
  35103. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  35104. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  35105. this._effect.setVector3("lightPosition", this.getLight().position);
  35106. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  35107. // Alpha test
  35108. if (material && material.needAlphaTesting()) {
  35109. var alphaTexture = material.getAlphaTestTexture();
  35110. if (alphaTexture) {
  35111. this._effect.setTexture("diffuseSampler", alphaTexture);
  35112. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  35113. }
  35114. }
  35115. // Bones
  35116. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35117. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35118. }
  35119. if (this.forceBackFacesOnly) {
  35120. engine.setState(true, 0, false, true);
  35121. }
  35122. // Draw
  35123. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35124. if (this.forceBackFacesOnly) {
  35125. engine.setState(true, 0, false, false);
  35126. }
  35127. }
  35128. else {
  35129. // Need to reset refresh rate of the shadowMap
  35130. this._shadowMap.resetRefreshCounter();
  35131. }
  35132. };
  35133. ShadowGenerator.prototype._applyFilterValues = function () {
  35134. if (this.filter === ShadowGenerator.FILTER_NONE) {
  35135. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  35136. }
  35137. else {
  35138. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35139. }
  35140. };
  35141. /**
  35142. * Force shader compilation including textures ready check
  35143. */
  35144. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  35145. var _this = this;
  35146. var scene = this._scene;
  35147. var engine = scene.getEngine();
  35148. var subMeshes = new Array();
  35149. var currentIndex = 0;
  35150. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  35151. var mesh = _a[_i];
  35152. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  35153. }
  35154. var checkReady = function () {
  35155. if (!_this._scene || !_this._scene.getEngine()) {
  35156. return;
  35157. }
  35158. var subMesh = subMeshes[currentIndex];
  35159. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  35160. currentIndex++;
  35161. if (currentIndex >= subMeshes.length) {
  35162. if (onCompiled) {
  35163. onCompiled(_this);
  35164. }
  35165. return;
  35166. }
  35167. }
  35168. setTimeout(checkReady, 16);
  35169. };
  35170. if (subMeshes.length > 0) {
  35171. checkReady();
  35172. }
  35173. };
  35174. /**
  35175. * Boolean : true when the ShadowGenerator is finally computed.
  35176. */
  35177. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  35178. var defines = [];
  35179. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35180. defines.push("#define FLOAT");
  35181. }
  35182. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  35183. defines.push("#define ESM");
  35184. }
  35185. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35186. var mesh = subMesh.getMesh();
  35187. var material = subMesh.getMaterial();
  35188. // Alpha test
  35189. if (material && material.needAlphaTesting()) {
  35190. var alphaTexture = material.getAlphaTestTexture();
  35191. if (alphaTexture) {
  35192. defines.push("#define ALPHATEST");
  35193. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35194. attribs.push(BABYLON.VertexBuffer.UVKind);
  35195. defines.push("#define UV1");
  35196. }
  35197. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35198. if (alphaTexture.coordinatesIndex === 1) {
  35199. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35200. defines.push("#define UV2");
  35201. }
  35202. }
  35203. }
  35204. }
  35205. // Bones
  35206. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35207. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35208. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35209. if (mesh.numBoneInfluencers > 4) {
  35210. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35211. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35212. }
  35213. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35214. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35215. }
  35216. else {
  35217. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35218. }
  35219. // Instances
  35220. if (useInstances) {
  35221. defines.push("#define INSTANCES");
  35222. attribs.push("world0");
  35223. attribs.push("world1");
  35224. attribs.push("world2");
  35225. attribs.push("world3");
  35226. }
  35227. // Get correct effect
  35228. var join = defines.join("\n");
  35229. if (this._cachedDefines !== join) {
  35230. this._cachedDefines = join;
  35231. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  35232. }
  35233. return this._effect.isReady();
  35234. };
  35235. /**
  35236. * This creates the defines related to the standard BJS materials.
  35237. */
  35238. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  35239. var scene = this._scene;
  35240. var light = this._light;
  35241. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  35242. return;
  35243. }
  35244. defines["SHADOW" + lightIndex] = true;
  35245. if (this.usePoissonSampling) {
  35246. defines["SHADOWPCF" + lightIndex] = true;
  35247. }
  35248. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  35249. defines["SHADOWESM" + lightIndex] = true;
  35250. }
  35251. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  35252. defines["SHADOWCLOSEESM" + lightIndex] = true;
  35253. }
  35254. if (light.needCube()) {
  35255. defines["SHADOWCUBE" + lightIndex] = true;
  35256. }
  35257. };
  35258. /**
  35259. * This binds shadow lights related to the standard BJS materials.
  35260. * It implies the unifroms available on the materials are the standard BJS ones.
  35261. */
  35262. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  35263. var light = this._light;
  35264. var scene = this._scene;
  35265. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  35266. return;
  35267. }
  35268. if (!light.needCube()) {
  35269. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  35270. }
  35271. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  35272. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  35273. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  35274. };
  35275. // Methods
  35276. /**
  35277. * Returns a Matrix object : the updated transformation matrix.
  35278. */
  35279. ShadowGenerator.prototype.getTransformMatrix = function () {
  35280. var scene = this._scene;
  35281. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  35282. return this._transformMatrix;
  35283. }
  35284. this._currentRenderID = scene.getRenderId();
  35285. this._currentFaceIndexCache = this._currentFaceIndex;
  35286. var lightPosition = this._light.position;
  35287. if (this._light.computeTransformedInformation()) {
  35288. lightPosition = this._light.transformedPosition;
  35289. }
  35290. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  35291. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  35292. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  35293. }
  35294. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  35295. this._cachedPosition = lightPosition.clone();
  35296. this._cachedDirection = this._lightDirection.clone();
  35297. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  35298. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  35299. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  35300. }
  35301. return this._transformMatrix;
  35302. };
  35303. ShadowGenerator.prototype.recreateShadowMap = function () {
  35304. // Track render list.
  35305. var renderList = this._shadowMap.renderList;
  35306. // Clean up existing data.
  35307. this._disposeRTTandPostProcesses();
  35308. // Reinitializes.
  35309. this._initializeGenerator();
  35310. // Reaffect the filter to ensure a correct fallback if necessary.
  35311. this.filter = this.filter;
  35312. // Reaffect the filter.
  35313. this._applyFilterValues();
  35314. // Reaffect Render List.
  35315. this._shadowMap.renderList = renderList;
  35316. };
  35317. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  35318. if (this._shadowMap2) {
  35319. this._shadowMap2.dispose();
  35320. this._shadowMap2 = null;
  35321. }
  35322. if (this._downSamplePostprocess) {
  35323. this._downSamplePostprocess.dispose();
  35324. this._downSamplePostprocess = null;
  35325. }
  35326. if (this._boxBlurPostprocess) {
  35327. this._boxBlurPostprocess.dispose();
  35328. this._boxBlurPostprocess = null;
  35329. }
  35330. if (this._kernelBlurXPostprocess) {
  35331. this._kernelBlurXPostprocess.dispose();
  35332. this._kernelBlurXPostprocess = null;
  35333. }
  35334. if (this._kernelBlurYPostprocess) {
  35335. this._kernelBlurYPostprocess.dispose();
  35336. this._kernelBlurYPostprocess = null;
  35337. }
  35338. this._blurPostProcesses = null;
  35339. };
  35340. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  35341. if (this._shadowMap) {
  35342. this._shadowMap.dispose();
  35343. this._shadowMap = null;
  35344. }
  35345. this._disposeBlurPostProcesses();
  35346. };
  35347. /**
  35348. * Disposes the ShadowGenerator.
  35349. * Returns nothing.
  35350. */
  35351. ShadowGenerator.prototype.dispose = function () {
  35352. this._disposeRTTandPostProcesses();
  35353. this._light._shadowGenerator = null;
  35354. this._light._markMeshesAsLightDirty();
  35355. };
  35356. /**
  35357. * Serializes the ShadowGenerator and returns a serializationObject.
  35358. */
  35359. ShadowGenerator.prototype.serialize = function () {
  35360. var serializationObject = {};
  35361. var shadowMap = this.getShadowMap();
  35362. serializationObject.lightId = this._light.id;
  35363. serializationObject.mapSize = shadowMap.getRenderSize();
  35364. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  35365. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  35366. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  35367. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  35368. serializationObject.usePoissonSampling = this.usePoissonSampling;
  35369. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  35370. serializationObject.depthScale = this.depthScale;
  35371. serializationObject.darkness = this.getDarkness();
  35372. serializationObject.blurBoxOffset = this.blurBoxOffset;
  35373. serializationObject.blurKernel = this.blurKernel;
  35374. serializationObject.blurScale = this.blurScale;
  35375. serializationObject.useKernelBlur = this.useKernelBlur;
  35376. serializationObject.transparencyShadow = this._transparencyShadow;
  35377. serializationObject.renderList = [];
  35378. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  35379. var mesh = shadowMap.renderList[meshIndex];
  35380. serializationObject.renderList.push(mesh.id);
  35381. }
  35382. return serializationObject;
  35383. };
  35384. /**
  35385. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  35386. */
  35387. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  35388. //casting to point light, as light is missing the position attr and typescript complains.
  35389. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  35390. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  35391. var shadowMap = shadowGenerator.getShadowMap();
  35392. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  35393. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  35394. meshes.forEach(function (mesh) {
  35395. shadowMap.renderList.push(mesh);
  35396. });
  35397. }
  35398. if (parsedShadowGenerator.usePoissonSampling) {
  35399. shadowGenerator.usePoissonSampling = true;
  35400. }
  35401. else if (parsedShadowGenerator.useExponentialShadowMap) {
  35402. shadowGenerator.useExponentialShadowMap = true;
  35403. }
  35404. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  35405. shadowGenerator.useBlurExponentialShadowMap = true;
  35406. }
  35407. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  35408. shadowGenerator.useCloseExponentialShadowMap = true;
  35409. }
  35410. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  35411. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  35412. }
  35413. else if (parsedShadowGenerator.useVarianceShadowMap) {
  35414. shadowGenerator.useExponentialShadowMap = true;
  35415. }
  35416. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  35417. shadowGenerator.useBlurExponentialShadowMap = true;
  35418. }
  35419. if (parsedShadowGenerator.depthScale) {
  35420. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  35421. }
  35422. if (parsedShadowGenerator.blurScale) {
  35423. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  35424. }
  35425. if (parsedShadowGenerator.blurBoxOffset) {
  35426. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  35427. }
  35428. if (parsedShadowGenerator.useKernelBlur) {
  35429. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  35430. }
  35431. if (parsedShadowGenerator.blurKernel) {
  35432. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  35433. }
  35434. if (parsedShadowGenerator.bias !== undefined) {
  35435. shadowGenerator.bias = parsedShadowGenerator.bias;
  35436. }
  35437. if (parsedShadowGenerator.darkness) {
  35438. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  35439. }
  35440. if (parsedShadowGenerator.transparencyShadow) {
  35441. shadowGenerator.setTransparencyShadow(true);
  35442. }
  35443. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  35444. return shadowGenerator;
  35445. };
  35446. ShadowGenerator._FILTER_NONE = 0;
  35447. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  35448. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  35449. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  35450. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  35451. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  35452. return ShadowGenerator;
  35453. }());
  35454. BABYLON.ShadowGenerator = ShadowGenerator;
  35455. })(BABYLON || (BABYLON = {}));
  35456. //# sourceMappingURL=babylon.shadowGenerator.js.map
  35457. var BABYLON;
  35458. (function (BABYLON) {
  35459. var ShadowLight = (function (_super) {
  35460. __extends(ShadowLight, _super);
  35461. function ShadowLight() {
  35462. var _this = _super !== null && _super.apply(this, arguments) || this;
  35463. _this._needProjectionMatrixCompute = true;
  35464. return _this;
  35465. }
  35466. Object.defineProperty(ShadowLight.prototype, "direction", {
  35467. get: function () {
  35468. return this._direction;
  35469. },
  35470. set: function (value) {
  35471. this._direction = value;
  35472. },
  35473. enumerable: true,
  35474. configurable: true
  35475. });
  35476. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  35477. get: function () {
  35478. return this._shadowMinZ;
  35479. },
  35480. set: function (value) {
  35481. this._shadowMinZ = value;
  35482. this.forceProjectionMatrixCompute();
  35483. },
  35484. enumerable: true,
  35485. configurable: true
  35486. });
  35487. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  35488. get: function () {
  35489. return this._shadowMaxZ;
  35490. },
  35491. set: function (value) {
  35492. this._shadowMaxZ = value;
  35493. this.forceProjectionMatrixCompute();
  35494. },
  35495. enumerable: true,
  35496. configurable: true
  35497. });
  35498. /**
  35499. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  35500. */
  35501. ShadowLight.prototype.computeTransformedInformation = function () {
  35502. if (this.parent && this.parent.getWorldMatrix) {
  35503. if (!this.transformedPosition) {
  35504. this.transformedPosition = BABYLON.Vector3.Zero();
  35505. }
  35506. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  35507. // In case the direction is present.
  35508. if (this.direction) {
  35509. if (!this.transformedDirection) {
  35510. this.transformedDirection = BABYLON.Vector3.Zero();
  35511. }
  35512. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  35513. }
  35514. return true;
  35515. }
  35516. return false;
  35517. };
  35518. /**
  35519. * Return the depth scale used for the shadow map.
  35520. */
  35521. ShadowLight.prototype.getDepthScale = function () {
  35522. return 50.0;
  35523. };
  35524. /**
  35525. * Returns the light direction (Vector3) for any passed face index.
  35526. */
  35527. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  35528. return this.transformedDirection ? this.transformedDirection : this.direction;
  35529. };
  35530. /**
  35531. * Returns the DirectionalLight absolute position in the World.
  35532. */
  35533. ShadowLight.prototype.getAbsolutePosition = function () {
  35534. return this.transformedPosition ? this.transformedPosition : this.position;
  35535. };
  35536. /**
  35537. * Sets the DirectionalLight direction toward the passed target (Vector3).
  35538. * Returns the updated DirectionalLight direction (Vector3).
  35539. */
  35540. ShadowLight.prototype.setDirectionToTarget = function (target) {
  35541. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  35542. return this.direction;
  35543. };
  35544. /**
  35545. * Returns the light rotation (Vector3).
  35546. */
  35547. ShadowLight.prototype.getRotation = function () {
  35548. this.direction.normalize();
  35549. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  35550. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  35551. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  35552. };
  35553. /**
  35554. * Boolean : false by default.
  35555. */
  35556. ShadowLight.prototype.needCube = function () {
  35557. return false;
  35558. };
  35559. /**
  35560. * Specifies wether or not the projection matrix should be recomputed this frame.
  35561. */
  35562. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  35563. return this._needProjectionMatrixCompute;
  35564. };
  35565. /**
  35566. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  35567. */
  35568. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  35569. this._needProjectionMatrixCompute = true;
  35570. };
  35571. /**
  35572. * Get the world matrix of the sahdow lights.
  35573. */
  35574. ShadowLight.prototype._getWorldMatrix = function () {
  35575. if (!this._worldMatrix) {
  35576. this._worldMatrix = BABYLON.Matrix.Identity();
  35577. }
  35578. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  35579. return this._worldMatrix;
  35580. };
  35581. /**
  35582. * Gets the minZ used for shadow according to both the scene and the light.
  35583. * @param activeCamera
  35584. */
  35585. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  35586. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  35587. };
  35588. /**
  35589. * Gets the maxZ used for shadow according to both the scene and the light.
  35590. * @param activeCamera
  35591. */
  35592. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  35593. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  35594. };
  35595. /**
  35596. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  35597. * Returns the light.
  35598. */
  35599. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35600. if (this.customProjectionMatrixBuilder) {
  35601. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  35602. }
  35603. else {
  35604. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  35605. }
  35606. return this;
  35607. };
  35608. __decorate([
  35609. BABYLON.serializeAsVector3()
  35610. ], ShadowLight.prototype, "position", void 0);
  35611. __decorate([
  35612. BABYLON.serializeAsVector3()
  35613. ], ShadowLight.prototype, "direction", null);
  35614. __decorate([
  35615. BABYLON.serialize()
  35616. ], ShadowLight.prototype, "shadowMinZ", null);
  35617. __decorate([
  35618. BABYLON.serialize()
  35619. ], ShadowLight.prototype, "shadowMaxZ", null);
  35620. return ShadowLight;
  35621. }(BABYLON.Light));
  35622. BABYLON.ShadowLight = ShadowLight;
  35623. })(BABYLON || (BABYLON = {}));
  35624. //# sourceMappingURL=babylon.shadowLight.js.map
  35625. var BABYLON;
  35626. (function (BABYLON) {
  35627. var PointLight = (function (_super) {
  35628. __extends(PointLight, _super);
  35629. /**
  35630. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  35631. * A PointLight emits the light in every direction.
  35632. * It can cast shadows.
  35633. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  35634. * ```javascript
  35635. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  35636. * ```
  35637. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35638. */
  35639. function PointLight(name, position, scene) {
  35640. var _this = _super.call(this, name, scene) || this;
  35641. _this._shadowAngle = Math.PI / 2;
  35642. _this.position = position;
  35643. return _this;
  35644. }
  35645. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  35646. /**
  35647. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35648. * This specifies what angle the shadow will use to be created.
  35649. *
  35650. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  35651. */
  35652. get: function () {
  35653. return this._shadowAngle;
  35654. },
  35655. /**
  35656. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35657. * This specifies what angle the shadow will use to be created.
  35658. *
  35659. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  35660. */
  35661. set: function (value) {
  35662. this._shadowAngle = value;
  35663. this.forceProjectionMatrixCompute();
  35664. },
  35665. enumerable: true,
  35666. configurable: true
  35667. });
  35668. Object.defineProperty(PointLight.prototype, "direction", {
  35669. get: function () {
  35670. return this._direction;
  35671. },
  35672. /**
  35673. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35674. */
  35675. set: function (value) {
  35676. var previousNeedCube = this.needCube();
  35677. this._direction = value;
  35678. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  35679. this._shadowGenerator.recreateShadowMap();
  35680. }
  35681. },
  35682. enumerable: true,
  35683. configurable: true
  35684. });
  35685. /**
  35686. * Returns the string "PointLight"
  35687. */
  35688. PointLight.prototype.getClassName = function () {
  35689. return "PointLight";
  35690. };
  35691. /**
  35692. * Returns the integer 0.
  35693. */
  35694. PointLight.prototype.getTypeID = function () {
  35695. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  35696. };
  35697. /**
  35698. * Specifies wether or not the shadowmap should be a cube texture.
  35699. */
  35700. PointLight.prototype.needCube = function () {
  35701. return !this.direction;
  35702. };
  35703. /**
  35704. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  35705. */
  35706. PointLight.prototype.getShadowDirection = function (faceIndex) {
  35707. if (this.direction) {
  35708. return _super.prototype.getShadowDirection.call(this, faceIndex);
  35709. }
  35710. else {
  35711. switch (faceIndex) {
  35712. case 0:
  35713. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  35714. case 1:
  35715. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  35716. case 2:
  35717. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  35718. case 3:
  35719. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  35720. case 4:
  35721. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  35722. case 5:
  35723. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  35724. }
  35725. }
  35726. return BABYLON.Vector3.Zero();
  35727. };
  35728. /**
  35729. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  35730. * - fov = PI / 2
  35731. * - aspect ratio : 1.0
  35732. * - z-near and far equal to the active camera minZ and maxZ.
  35733. * Returns the PointLight.
  35734. */
  35735. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35736. var activeCamera = this.getScene().activeCamera;
  35737. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  35738. };
  35739. PointLight.prototype._buildUniformLayout = function () {
  35740. this._uniformBuffer.addUniform("vLightData", 4);
  35741. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35742. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35743. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35744. this._uniformBuffer.addUniform("depthValues", 2);
  35745. this._uniformBuffer.create();
  35746. };
  35747. /**
  35748. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  35749. * Returns the PointLight.
  35750. */
  35751. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  35752. if (this.computeTransformedInformation()) {
  35753. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  35754. return this;
  35755. }
  35756. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  35757. return this;
  35758. };
  35759. __decorate([
  35760. BABYLON.serialize()
  35761. ], PointLight.prototype, "shadowAngle", null);
  35762. return PointLight;
  35763. }(BABYLON.ShadowLight));
  35764. BABYLON.PointLight = PointLight;
  35765. })(BABYLON || (BABYLON = {}));
  35766. //# sourceMappingURL=babylon.pointLight.js.map
  35767. /// <reference path="babylon.light.ts" />
  35768. var BABYLON;
  35769. (function (BABYLON) {
  35770. var DirectionalLight = (function (_super) {
  35771. __extends(DirectionalLight, _super);
  35772. /**
  35773. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  35774. * The directional light is emitted from everywhere in the given direction.
  35775. * It can cast shawdows.
  35776. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35777. */
  35778. function DirectionalLight(name, direction, scene) {
  35779. var _this = _super.call(this, name, scene) || this;
  35780. _this._shadowFrustumSize = 0;
  35781. _this._shadowOrthoScale = 0.5;
  35782. _this.autoUpdateExtends = true;
  35783. // Cache
  35784. _this._orthoLeft = Number.MAX_VALUE;
  35785. _this._orthoRight = Number.MIN_VALUE;
  35786. _this._orthoTop = Number.MIN_VALUE;
  35787. _this._orthoBottom = Number.MAX_VALUE;
  35788. _this.position = direction.scale(-1.0);
  35789. _this.direction = direction;
  35790. return _this;
  35791. }
  35792. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  35793. /**
  35794. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  35795. */
  35796. get: function () {
  35797. return this._shadowFrustumSize;
  35798. },
  35799. /**
  35800. * Specifies a fix frustum size for the shadow generation.
  35801. */
  35802. set: function (value) {
  35803. this._shadowFrustumSize = value;
  35804. this.forceProjectionMatrixCompute();
  35805. },
  35806. enumerable: true,
  35807. configurable: true
  35808. });
  35809. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  35810. get: function () {
  35811. return this._shadowOrthoScale;
  35812. },
  35813. set: function (value) {
  35814. this._shadowOrthoScale = value;
  35815. this.forceProjectionMatrixCompute();
  35816. },
  35817. enumerable: true,
  35818. configurable: true
  35819. });
  35820. /**
  35821. * Returns the string "DirectionalLight".
  35822. */
  35823. DirectionalLight.prototype.getClassName = function () {
  35824. return "DirectionalLight";
  35825. };
  35826. /**
  35827. * Returns the integer 1.
  35828. */
  35829. DirectionalLight.prototype.getTypeID = function () {
  35830. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  35831. };
  35832. /**
  35833. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  35834. * Returns the DirectionalLight Shadow projection matrix.
  35835. */
  35836. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35837. if (this.shadowFrustumSize > 0) {
  35838. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  35839. }
  35840. else {
  35841. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  35842. }
  35843. };
  35844. /**
  35845. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  35846. * Returns the DirectionalLight Shadow projection matrix.
  35847. */
  35848. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  35849. var activeCamera = this.getScene().activeCamera;
  35850. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  35851. };
  35852. /**
  35853. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  35854. * Returns the DirectionalLight Shadow projection matrix.
  35855. */
  35856. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35857. var activeCamera = this.getScene().activeCamera;
  35858. // Check extends
  35859. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  35860. var tempVector3 = BABYLON.Vector3.Zero();
  35861. this._orthoLeft = Number.MAX_VALUE;
  35862. this._orthoRight = Number.MIN_VALUE;
  35863. this._orthoTop = Number.MIN_VALUE;
  35864. this._orthoBottom = Number.MAX_VALUE;
  35865. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  35866. var mesh = renderList[meshIndex];
  35867. if (!mesh) {
  35868. continue;
  35869. }
  35870. var boundingInfo = mesh.getBoundingInfo();
  35871. if (!boundingInfo) {
  35872. continue;
  35873. }
  35874. var boundingBox = boundingInfo.boundingBox;
  35875. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  35876. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  35877. if (tempVector3.x < this._orthoLeft)
  35878. this._orthoLeft = tempVector3.x;
  35879. if (tempVector3.y < this._orthoBottom)
  35880. this._orthoBottom = tempVector3.y;
  35881. if (tempVector3.x > this._orthoRight)
  35882. this._orthoRight = tempVector3.x;
  35883. if (tempVector3.y > this._orthoTop)
  35884. this._orthoTop = tempVector3.y;
  35885. }
  35886. }
  35887. }
  35888. var xOffset = this._orthoRight - this._orthoLeft;
  35889. var yOffset = this._orthoTop - this._orthoBottom;
  35890. 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);
  35891. };
  35892. DirectionalLight.prototype._buildUniformLayout = function () {
  35893. this._uniformBuffer.addUniform("vLightData", 4);
  35894. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35895. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35896. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35897. this._uniformBuffer.addUniform("depthValues", 2);
  35898. this._uniformBuffer.create();
  35899. };
  35900. /**
  35901. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  35902. * Returns the DirectionalLight.
  35903. */
  35904. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  35905. if (this.computeTransformedInformation()) {
  35906. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  35907. return this;
  35908. }
  35909. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  35910. return this;
  35911. };
  35912. /**
  35913. * Gets the minZ used for shadow according to both the scene and the light.
  35914. *
  35915. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  35916. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  35917. * @param activeCamera
  35918. */
  35919. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  35920. return 1;
  35921. };
  35922. /**
  35923. * Gets the maxZ used for shadow according to both the scene and the light.
  35924. *
  35925. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  35926. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  35927. * @param activeCamera
  35928. */
  35929. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  35930. return 1;
  35931. };
  35932. __decorate([
  35933. BABYLON.serialize()
  35934. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  35935. __decorate([
  35936. BABYLON.serialize()
  35937. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  35938. __decorate([
  35939. BABYLON.serialize()
  35940. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  35941. return DirectionalLight;
  35942. }(BABYLON.ShadowLight));
  35943. BABYLON.DirectionalLight = DirectionalLight;
  35944. })(BABYLON || (BABYLON = {}));
  35945. //# sourceMappingURL=babylon.directionalLight.js.map
  35946. var BABYLON;
  35947. (function (BABYLON) {
  35948. var SpotLight = (function (_super) {
  35949. __extends(SpotLight, _super);
  35950. /**
  35951. * Creates a SpotLight object in the scene with the passed parameters :
  35952. * - `position` (Vector3) is the initial SpotLight position,
  35953. * - `direction` (Vector3) is the initial SpotLight direction,
  35954. * - `angle` (float, in radians) is the spot light cone angle,
  35955. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  35956. * A spot light is a simply light oriented cone.
  35957. * It can cast shadows.
  35958. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35959. */
  35960. function SpotLight(name, position, direction, angle, exponent, scene) {
  35961. var _this = _super.call(this, name, scene) || this;
  35962. _this.position = position;
  35963. _this.direction = direction;
  35964. _this.angle = angle;
  35965. _this.exponent = exponent;
  35966. return _this;
  35967. }
  35968. Object.defineProperty(SpotLight.prototype, "angle", {
  35969. get: function () {
  35970. return this._angle;
  35971. },
  35972. set: function (value) {
  35973. this._angle = value;
  35974. this.forceProjectionMatrixCompute();
  35975. },
  35976. enumerable: true,
  35977. configurable: true
  35978. });
  35979. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  35980. get: function () {
  35981. return this._shadowAngleScale;
  35982. },
  35983. /**
  35984. * Allows scaling the angle of the light for shadow generation only.
  35985. */
  35986. set: function (value) {
  35987. this._shadowAngleScale = value;
  35988. this.forceProjectionMatrixCompute();
  35989. },
  35990. enumerable: true,
  35991. configurable: true
  35992. });
  35993. /**
  35994. * Returns the string "SpotLight".
  35995. */
  35996. SpotLight.prototype.getClassName = function () {
  35997. return "SpotLight";
  35998. };
  35999. /**
  36000. * Returns the integer 2.
  36001. */
  36002. SpotLight.prototype.getTypeID = function () {
  36003. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36004. };
  36005. /**
  36006. * 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.
  36007. * Returns the SpotLight.
  36008. */
  36009. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36010. var activeCamera = this.getScene().activeCamera;
  36011. this._shadowAngleScale = this._shadowAngleScale || 1;
  36012. var angle = this._shadowAngleScale * this._angle;
  36013. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36014. };
  36015. SpotLight.prototype._buildUniformLayout = function () {
  36016. this._uniformBuffer.addUniform("vLightData", 4);
  36017. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36018. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36019. this._uniformBuffer.addUniform("vLightDirection", 3);
  36020. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36021. this._uniformBuffer.addUniform("depthValues", 2);
  36022. this._uniformBuffer.create();
  36023. };
  36024. /**
  36025. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36026. * Return the SpotLight.
  36027. */
  36028. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36029. var normalizeDirection;
  36030. if (this.computeTransformedInformation()) {
  36031. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36032. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36033. }
  36034. else {
  36035. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36036. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36037. }
  36038. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36039. return this;
  36040. };
  36041. __decorate([
  36042. BABYLON.serialize()
  36043. ], SpotLight.prototype, "angle", null);
  36044. __decorate([
  36045. BABYLON.serialize()
  36046. /**
  36047. * Allows scaling the angle of the light for shadow generation only.
  36048. */
  36049. ], SpotLight.prototype, "shadowAngleScale", null);
  36050. __decorate([
  36051. BABYLON.serialize()
  36052. ], SpotLight.prototype, "exponent", void 0);
  36053. return SpotLight;
  36054. }(BABYLON.ShadowLight));
  36055. BABYLON.SpotLight = SpotLight;
  36056. })(BABYLON || (BABYLON = {}));
  36057. //# sourceMappingURL=babylon.spotLight.js.map
  36058. var BABYLON;
  36059. (function (BABYLON) {
  36060. var MultiMaterial = (function (_super) {
  36061. __extends(MultiMaterial, _super);
  36062. function MultiMaterial(name, scene) {
  36063. var _this = _super.call(this, name, scene, true) || this;
  36064. scene.multiMaterials.push(_this);
  36065. _this.subMaterials = new Array();
  36066. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  36067. return _this;
  36068. }
  36069. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  36070. get: function () {
  36071. return this._subMaterials;
  36072. },
  36073. set: function (value) {
  36074. this._subMaterials = value;
  36075. this._hookArray(value);
  36076. },
  36077. enumerable: true,
  36078. configurable: true
  36079. });
  36080. MultiMaterial.prototype._hookArray = function (array) {
  36081. var _this = this;
  36082. var oldPush = array.push;
  36083. array.push = function () {
  36084. var items = [];
  36085. for (var _i = 0; _i < arguments.length; _i++) {
  36086. items[_i] = arguments[_i];
  36087. }
  36088. var result = oldPush.apply(array, items);
  36089. _this._markAllSubMeshesAsTexturesDirty();
  36090. return result;
  36091. };
  36092. var oldSplice = array.splice;
  36093. array.splice = function (index, deleteCount) {
  36094. var deleted = oldSplice.apply(array, [index, deleteCount]);
  36095. _this._markAllSubMeshesAsTexturesDirty();
  36096. return deleted;
  36097. };
  36098. };
  36099. // Properties
  36100. MultiMaterial.prototype.getSubMaterial = function (index) {
  36101. if (index < 0 || index >= this.subMaterials.length) {
  36102. return this.getScene().defaultMaterial;
  36103. }
  36104. return this.subMaterials[index];
  36105. };
  36106. MultiMaterial.prototype.getActiveTextures = function () {
  36107. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  36108. var _a;
  36109. };
  36110. // Methods
  36111. MultiMaterial.prototype.getClassName = function () {
  36112. return "MultiMaterial";
  36113. };
  36114. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36115. for (var index = 0; index < this.subMaterials.length; index++) {
  36116. var subMaterial = this.subMaterials[index];
  36117. if (subMaterial) {
  36118. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  36119. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  36120. return false;
  36121. }
  36122. continue;
  36123. }
  36124. if (!this.subMaterials[index].isReady(mesh)) {
  36125. return false;
  36126. }
  36127. }
  36128. }
  36129. return true;
  36130. };
  36131. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  36132. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  36133. for (var index = 0; index < this.subMaterials.length; index++) {
  36134. var subMaterial = null;
  36135. if (cloneChildren) {
  36136. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  36137. }
  36138. else {
  36139. subMaterial = this.subMaterials[index];
  36140. }
  36141. newMultiMaterial.subMaterials.push(subMaterial);
  36142. }
  36143. return newMultiMaterial;
  36144. };
  36145. MultiMaterial.prototype.serialize = function () {
  36146. var serializationObject = {};
  36147. serializationObject.name = this.name;
  36148. serializationObject.id = this.id;
  36149. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36150. serializationObject.materials = [];
  36151. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  36152. var subMat = this.subMaterials[matIndex];
  36153. if (subMat) {
  36154. serializationObject.materials.push(subMat.id);
  36155. }
  36156. else {
  36157. serializationObject.materials.push(null);
  36158. }
  36159. }
  36160. return serializationObject;
  36161. };
  36162. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36163. var scene = this.getScene();
  36164. if (!scene) {
  36165. return;
  36166. }
  36167. var index = scene.multiMaterials.indexOf(this);
  36168. if (index >= 0) {
  36169. scene.multiMaterials.splice(index, 1);
  36170. }
  36171. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36172. };
  36173. return MultiMaterial;
  36174. }(BABYLON.Material));
  36175. BABYLON.MultiMaterial = MultiMaterial;
  36176. })(BABYLON || (BABYLON = {}));
  36177. //# sourceMappingURL=babylon.multiMaterial.js.map
  36178. var BABYLON;
  36179. (function (BABYLON) {
  36180. var PBRMaterialDefines = (function (_super) {
  36181. __extends(PBRMaterialDefines, _super);
  36182. function PBRMaterialDefines() {
  36183. var _this = _super.call(this) || this;
  36184. _this.PBR = true;
  36185. _this.MAINUV1 = false;
  36186. _this.MAINUV2 = false;
  36187. _this.UV1 = false;
  36188. _this.UV2 = false;
  36189. _this.ALBEDO = false;
  36190. _this.ALBEDODIRECTUV = 0;
  36191. _this.VERTEXCOLOR = false;
  36192. _this.AMBIENT = false;
  36193. _this.AMBIENTDIRECTUV = 0;
  36194. _this.AMBIENTINGRAYSCALE = false;
  36195. _this.OPACITY = false;
  36196. _this.VERTEXALPHA = false;
  36197. _this.OPACITYDIRECTUV = 0;
  36198. _this.OPACITYRGB = false;
  36199. _this.ALPHATEST = false;
  36200. _this.ALPHABLEND = false;
  36201. _this.ALPHAFROMALBEDO = false;
  36202. _this.ALPHATESTVALUE = 0.5;
  36203. _this.SPECULAROVERALPHA = false;
  36204. _this.RADIANCEOVERALPHA = false;
  36205. _this.ALPHAFRESNEL = false;
  36206. _this.PREMULTIPLYALPHA = false;
  36207. _this.EMISSIVE = false;
  36208. _this.EMISSIVEDIRECTUV = 0;
  36209. _this.REFLECTIVITY = false;
  36210. _this.REFLECTIVITYDIRECTUV = 0;
  36211. _this.SPECULARTERM = false;
  36212. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36213. _this.MICROSURFACEAUTOMATIC = false;
  36214. _this.LODBASEDMICROSFURACE = false;
  36215. _this.MICROSURFACEMAP = false;
  36216. _this.MICROSURFACEMAPDIRECTUV = 0;
  36217. _this.METALLICWORKFLOW = false;
  36218. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36219. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36220. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36221. _this.AOSTOREINMETALMAPRED = false;
  36222. _this.ENVIRONMENTBRDF = false;
  36223. _this.NORMAL = false;
  36224. _this.TANGENT = false;
  36225. _this.BUMP = false;
  36226. _this.BUMPDIRECTUV = 0;
  36227. _this.PARALLAX = false;
  36228. _this.PARALLAXOCCLUSION = false;
  36229. _this.NORMALXYSCALE = true;
  36230. _this.LIGHTMAP = false;
  36231. _this.LIGHTMAPDIRECTUV = 0;
  36232. _this.USELIGHTMAPASSHADOWMAP = false;
  36233. _this.REFLECTION = false;
  36234. _this.REFLECTIONMAP_3D = false;
  36235. _this.REFLECTIONMAP_SPHERICAL = false;
  36236. _this.REFLECTIONMAP_PLANAR = false;
  36237. _this.REFLECTIONMAP_CUBIC = false;
  36238. _this.REFLECTIONMAP_PROJECTION = false;
  36239. _this.REFLECTIONMAP_SKYBOX = false;
  36240. _this.REFLECTIONMAP_EXPLICIT = false;
  36241. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36242. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36243. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36244. _this.INVERTCUBICMAP = false;
  36245. _this.USESPHERICALFROMREFLECTIONMAP = false;
  36246. _this.USESPHERICALINFRAGMENT = false;
  36247. _this.REFLECTIONMAP_OPPOSITEZ = false;
  36248. _this.LODINREFLECTIONALPHA = false;
  36249. _this.GAMMAREFLECTION = false;
  36250. _this.REFRACTION = false;
  36251. _this.REFRACTIONMAP_3D = false;
  36252. _this.REFRACTIONMAP_OPPOSITEZ = false;
  36253. _this.LODINREFRACTIONALPHA = false;
  36254. _this.GAMMAREFRACTION = false;
  36255. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  36256. _this.INSTANCES = false;
  36257. _this.NUM_BONE_INFLUENCERS = 0;
  36258. _this.BonesPerMesh = 0;
  36259. _this.MORPHTARGETS = false;
  36260. _this.MORPHTARGETS_NORMAL = false;
  36261. _this.MORPHTARGETS_TANGENT = false;
  36262. _this.NUM_MORPH_INFLUENCERS = 0;
  36263. _this.IMAGEPROCESSING = false;
  36264. _this.VIGNETTE = false;
  36265. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36266. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36267. _this.TONEMAPPING = false;
  36268. _this.CONTRAST = false;
  36269. _this.COLORCURVES = false;
  36270. _this.COLORGRADING = false;
  36271. _this.SAMPLER3DGREENDEPTH = false;
  36272. _this.SAMPLER3DBGRMAP = false;
  36273. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36274. _this.EXPOSURE = false;
  36275. _this.USEPHYSICALLIGHTFALLOFF = false;
  36276. _this.TWOSIDEDLIGHTING = false;
  36277. _this.SHADOWFLOAT = false;
  36278. _this.USERIGHTHANDEDSYSTEM = false;
  36279. _this.CLIPPLANE = false;
  36280. _this.POINTSIZE = false;
  36281. _this.FOG = false;
  36282. _this.LOGARITHMICDEPTH = false;
  36283. _this.FORCENORMALFORWARD = false;
  36284. _this.rebuild();
  36285. return _this;
  36286. }
  36287. PBRMaterialDefines.prototype.reset = function () {
  36288. _super.prototype.reset.call(this);
  36289. this.ALPHATESTVALUE = 0.5;
  36290. this.PBR = true;
  36291. };
  36292. return PBRMaterialDefines;
  36293. }(BABYLON.MaterialDefines));
  36294. /**
  36295. * The Physically based material base class of BJS.
  36296. *
  36297. * This offers the main features of a standard PBR material.
  36298. * For more information, please refer to the documentation :
  36299. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36300. */
  36301. var PBRBaseMaterial = (function (_super) {
  36302. __extends(PBRBaseMaterial, _super);
  36303. /**
  36304. * Instantiates a new PBRMaterial instance.
  36305. *
  36306. * @param name The material name
  36307. * @param scene The scene the material will be use in.
  36308. */
  36309. function PBRBaseMaterial(name, scene) {
  36310. var _this = _super.call(this, name, scene) || this;
  36311. /**
  36312. * Intensity of the direct lights e.g. the four lights available in your scene.
  36313. * This impacts both the direct diffuse and specular highlights.
  36314. */
  36315. _this._directIntensity = 1.0;
  36316. /**
  36317. * Intensity of the emissive part of the material.
  36318. * This helps controlling the emissive effect without modifying the emissive color.
  36319. */
  36320. _this._emissiveIntensity = 1.0;
  36321. /**
  36322. * Intensity of the environment e.g. how much the environment will light the object
  36323. * either through harmonics for rough material or through the refelction for shiny ones.
  36324. */
  36325. _this._environmentIntensity = 1.0;
  36326. /**
  36327. * This is a special control allowing the reduction of the specular highlights coming from the
  36328. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36329. */
  36330. _this._specularIntensity = 1.0;
  36331. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  36332. /**
  36333. * Debug Control allowing disabling the bump map on this material.
  36334. */
  36335. _this._disableBumpMap = false;
  36336. /**
  36337. * AKA Occlusion Texture Intensity in other nomenclature.
  36338. */
  36339. _this._ambientTextureStrength = 1.0;
  36340. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  36341. /**
  36342. * AKA Diffuse Color in other nomenclature.
  36343. */
  36344. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  36345. /**
  36346. * AKA Specular Color in other nomenclature.
  36347. */
  36348. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36349. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  36350. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  36351. /**
  36352. * AKA Glossiness in other nomenclature.
  36353. */
  36354. _this._microSurface = 0.9;
  36355. /**
  36356. * source material index of refraction (IOR)' / 'destination material IOR.
  36357. */
  36358. _this._indexOfRefraction = 0.66;
  36359. /**
  36360. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36361. */
  36362. _this._invertRefractionY = false;
  36363. /**
  36364. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36365. * Materials half opaque for instance using refraction could benefit from this control.
  36366. */
  36367. _this._linkRefractionWithTransparency = false;
  36368. _this._useLightmapAsShadowmap = false;
  36369. /**
  36370. * Specifies that the alpha is coming form the albedo channel alpha channel.
  36371. */
  36372. _this._useAlphaFromAlbedoTexture = false;
  36373. /**
  36374. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36375. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36376. */
  36377. _this._useSpecularOverAlpha = true;
  36378. /**
  36379. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36380. */
  36381. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  36382. /**
  36383. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36384. */
  36385. _this._useRoughnessFromMetallicTextureAlpha = true;
  36386. /**
  36387. * Specifies if the metallic texture contains the roughness information in its green channel.
  36388. */
  36389. _this._useRoughnessFromMetallicTextureGreen = false;
  36390. /**
  36391. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36392. */
  36393. _this._useMetallnessFromMetallicTextureBlue = false;
  36394. /**
  36395. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36396. */
  36397. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  36398. /**
  36399. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36400. */
  36401. _this._useAmbientInGrayScale = false;
  36402. /**
  36403. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36404. * The material will try to infer what glossiness each pixel should be.
  36405. */
  36406. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  36407. /**
  36408. * BJS is using an harcoded light falloff based on a manually sets up range.
  36409. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36410. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36411. */
  36412. _this._usePhysicalLightFalloff = true;
  36413. /**
  36414. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36415. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36416. */
  36417. _this._useRadianceOverAlpha = true;
  36418. /**
  36419. * Allows using the bump map in parallax mode.
  36420. */
  36421. _this._useParallax = false;
  36422. /**
  36423. * Allows using the bump map in parallax occlusion mode.
  36424. */
  36425. _this._useParallaxOcclusion = false;
  36426. /**
  36427. * Controls the scale bias of the parallax mode.
  36428. */
  36429. _this._parallaxScaleBias = 0.05;
  36430. /**
  36431. * If sets to true, disables all the lights affecting the material.
  36432. */
  36433. _this._disableLighting = false;
  36434. /**
  36435. * Number of Simultaneous lights allowed on the material.
  36436. */
  36437. _this._maxSimultaneousLights = 4;
  36438. /**
  36439. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  36440. */
  36441. _this._invertNormalMapX = false;
  36442. /**
  36443. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  36444. */
  36445. _this._invertNormalMapY = false;
  36446. /**
  36447. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36448. */
  36449. _this._twoSidedLighting = false;
  36450. /**
  36451. * Defines the alpha limits in alpha test mode.
  36452. */
  36453. _this._alphaCutOff = 0.4;
  36454. /**
  36455. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36456. */
  36457. _this._forceAlphaTest = false;
  36458. /**
  36459. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  36460. * in your scene composition.
  36461. */
  36462. _this._preMultiplyAlpha = false;
  36463. /**
  36464. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36465. * And/Or occlude the blended part.
  36466. */
  36467. _this._useAlphaFresnel = false;
  36468. /**
  36469. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36470. * from cos thetav and roughness:
  36471. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36472. */
  36473. _this._environmentBRDFTexture = null;
  36474. /**
  36475. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36476. */
  36477. _this._forceIrradianceInFragment = false;
  36478. /**
  36479. * Force normal to face away from face.
  36480. * (Temporary internal fix to remove before 3.1)
  36481. */
  36482. _this._forceNormalForward = false;
  36483. _this._renderTargets = new BABYLON.SmartArray(16);
  36484. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  36485. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36486. _this._tempColor = new BABYLON.Color3();
  36487. // Setup the default processing configuration to the scene.
  36488. _this._attachImageProcessingConfiguration(null);
  36489. _this.getRenderTargetTextures = function () {
  36490. _this._renderTargets.reset();
  36491. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36492. _this._renderTargets.push(_this._reflectionTexture);
  36493. }
  36494. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36495. _this._renderTargets.push(_this._refractionTexture);
  36496. }
  36497. return _this._renderTargets;
  36498. };
  36499. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36500. return _this;
  36501. }
  36502. /**
  36503. * Attaches a new image processing configuration to the PBR Material.
  36504. * @param configuration
  36505. */
  36506. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36507. var _this = this;
  36508. if (configuration === this._imageProcessingConfiguration) {
  36509. return;
  36510. }
  36511. // Detaches observer.
  36512. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36513. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36514. }
  36515. // Pick the scene configuration if needed.
  36516. if (!configuration) {
  36517. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36518. }
  36519. else {
  36520. this._imageProcessingConfiguration = configuration;
  36521. }
  36522. // Attaches observer.
  36523. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36524. _this._markAllSubMeshesAsImageProcessingDirty();
  36525. });
  36526. };
  36527. PBRBaseMaterial.prototype.getClassName = function () {
  36528. return "PBRBaseMaterial";
  36529. };
  36530. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36531. get: function () {
  36532. return this._useLogarithmicDepth;
  36533. },
  36534. set: function (value) {
  36535. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36536. },
  36537. enumerable: true,
  36538. configurable: true
  36539. });
  36540. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  36541. if (this._linkRefractionWithTransparency) {
  36542. return false;
  36543. }
  36544. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  36545. };
  36546. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  36547. if (this._forceAlphaTest) {
  36548. return true;
  36549. }
  36550. if (this._linkRefractionWithTransparency) {
  36551. return false;
  36552. }
  36553. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  36554. };
  36555. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36556. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  36557. };
  36558. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  36559. return this._albedoTexture;
  36560. };
  36561. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36562. if (this.isFrozen) {
  36563. if (this._wasPreviouslyReady) {
  36564. return true;
  36565. }
  36566. }
  36567. if (!subMesh._materialDefines) {
  36568. subMesh._materialDefines = new PBRMaterialDefines();
  36569. }
  36570. var scene = this.getScene();
  36571. var defines = subMesh._materialDefines;
  36572. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36573. if (defines._renderId === scene.getRenderId()) {
  36574. return true;
  36575. }
  36576. }
  36577. var engine = scene.getEngine();
  36578. // Lights
  36579. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36580. defines._needNormals = true;
  36581. // Textures
  36582. if (defines._areTexturesDirty) {
  36583. defines._needUVs = false;
  36584. if (scene.texturesEnabled) {
  36585. if (scene.getEngine().getCaps().textureLOD) {
  36586. defines.LODBASEDMICROSFURACE = true;
  36587. }
  36588. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36589. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  36590. return false;
  36591. }
  36592. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  36593. }
  36594. else {
  36595. defines.ALBEDO = false;
  36596. }
  36597. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36598. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36599. return false;
  36600. }
  36601. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36602. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  36603. }
  36604. else {
  36605. defines.AMBIENT = false;
  36606. }
  36607. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36608. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36609. return false;
  36610. }
  36611. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36612. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36613. }
  36614. else {
  36615. defines.OPACITY = false;
  36616. }
  36617. var reflectionTexture = this._getReflectionTexture();
  36618. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36619. if (!reflectionTexture.isReadyOrNotBlocking()) {
  36620. return false;
  36621. }
  36622. defines.REFLECTION = true;
  36623. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  36624. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  36625. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36626. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  36627. defines.INVERTCUBICMAP = true;
  36628. }
  36629. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  36630. switch (reflectionTexture.coordinatesMode) {
  36631. case BABYLON.Texture.CUBIC_MODE:
  36632. case BABYLON.Texture.INVCUBIC_MODE:
  36633. defines.REFLECTIONMAP_CUBIC = true;
  36634. break;
  36635. case BABYLON.Texture.EXPLICIT_MODE:
  36636. defines.REFLECTIONMAP_EXPLICIT = true;
  36637. break;
  36638. case BABYLON.Texture.PLANAR_MODE:
  36639. defines.REFLECTIONMAP_PLANAR = true;
  36640. break;
  36641. case BABYLON.Texture.PROJECTION_MODE:
  36642. defines.REFLECTIONMAP_PROJECTION = true;
  36643. break;
  36644. case BABYLON.Texture.SKYBOX_MODE:
  36645. defines.REFLECTIONMAP_SKYBOX = true;
  36646. break;
  36647. case BABYLON.Texture.SPHERICAL_MODE:
  36648. defines.REFLECTIONMAP_SPHERICAL = true;
  36649. break;
  36650. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36651. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  36652. break;
  36653. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36654. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  36655. break;
  36656. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36657. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  36658. break;
  36659. }
  36660. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  36661. if (reflectionTexture.sphericalPolynomial) {
  36662. defines.USESPHERICALFROMREFLECTIONMAP = true;
  36663. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  36664. defines.USESPHERICALINFRAGMENT = true;
  36665. }
  36666. }
  36667. }
  36668. }
  36669. else {
  36670. defines.REFLECTION = false;
  36671. defines.REFLECTIONMAP_3D = false;
  36672. defines.REFLECTIONMAP_SPHERICAL = false;
  36673. defines.REFLECTIONMAP_PLANAR = false;
  36674. defines.REFLECTIONMAP_CUBIC = false;
  36675. defines.REFLECTIONMAP_PROJECTION = false;
  36676. defines.REFLECTIONMAP_SKYBOX = false;
  36677. defines.REFLECTIONMAP_EXPLICIT = false;
  36678. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36679. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36680. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36681. defines.INVERTCUBICMAP = false;
  36682. defines.USESPHERICALFROMREFLECTIONMAP = false;
  36683. defines.USESPHERICALINFRAGMENT = false;
  36684. defines.REFLECTIONMAP_OPPOSITEZ = false;
  36685. defines.LODINREFLECTIONALPHA = false;
  36686. defines.GAMMAREFLECTION = false;
  36687. }
  36688. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36689. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36690. return false;
  36691. }
  36692. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36693. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36694. }
  36695. else {
  36696. defines.LIGHTMAP = false;
  36697. }
  36698. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36699. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36700. return false;
  36701. }
  36702. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36703. }
  36704. else {
  36705. defines.EMISSIVE = false;
  36706. }
  36707. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36708. if (this._metallicTexture) {
  36709. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  36710. return false;
  36711. }
  36712. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  36713. defines.METALLICWORKFLOW = true;
  36714. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  36715. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  36716. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  36717. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  36718. }
  36719. else if (this._reflectivityTexture) {
  36720. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  36721. return false;
  36722. }
  36723. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  36724. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  36725. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  36726. }
  36727. else {
  36728. defines.REFLECTIVITY = false;
  36729. }
  36730. if (this._microSurfaceTexture) {
  36731. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  36732. return false;
  36733. }
  36734. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  36735. }
  36736. else {
  36737. defines.MICROSURFACEMAP = false;
  36738. }
  36739. }
  36740. else {
  36741. defines.REFLECTIVITY = false;
  36742. defines.MICROSURFACEMAP = false;
  36743. }
  36744. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36745. // Bump texure can not be none blocking.
  36746. if (!this._bumpTexture.isReady()) {
  36747. return false;
  36748. }
  36749. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36750. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36751. defines.PARALLAX = true;
  36752. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  36753. }
  36754. else {
  36755. defines.PARALLAX = false;
  36756. }
  36757. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  36758. }
  36759. else {
  36760. defines.BUMP = false;
  36761. }
  36762. var refractionTexture = this._getRefractionTexture();
  36763. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36764. if (!refractionTexture.isReadyOrNotBlocking()) {
  36765. return false;
  36766. }
  36767. defines.REFRACTION = true;
  36768. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  36769. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  36770. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  36771. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36772. if (this._linkRefractionWithTransparency) {
  36773. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  36774. }
  36775. }
  36776. else {
  36777. defines.REFRACTION = false;
  36778. }
  36779. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36780. // This is blocking.
  36781. if (!this._environmentBRDFTexture.isReady()) {
  36782. return false;
  36783. }
  36784. defines.ENVIRONMENTBRDF = true;
  36785. }
  36786. if (this._shouldUseAlphaFromAlbedoTexture()) {
  36787. defines.ALPHAFROMALBEDO = true;
  36788. }
  36789. }
  36790. if (this._useSpecularOverAlpha) {
  36791. defines.SPECULAROVERALPHA = true;
  36792. }
  36793. if (this._usePhysicalLightFalloff) {
  36794. defines.USEPHYSICALLIGHTFALLOFF = true;
  36795. }
  36796. if (this._useRadianceOverAlpha) {
  36797. defines.RADIANCEOVERALPHA = true;
  36798. }
  36799. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  36800. defines.METALLICWORKFLOW = true;
  36801. }
  36802. if (!this.backFaceCulling && this._twoSidedLighting) {
  36803. defines.TWOSIDEDLIGHTING = true;
  36804. }
  36805. defines.ALPHATESTVALUE = this._alphaCutOff;
  36806. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  36807. defines.ALPHABLEND = this.needAlphaBlending();
  36808. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  36809. }
  36810. if (defines._areImageProcessingDirty) {
  36811. if (!this._imageProcessingConfiguration.isReady()) {
  36812. return false;
  36813. }
  36814. this._imageProcessingConfiguration.prepareDefines(defines);
  36815. }
  36816. defines.FORCENORMALFORWARD = this._forceNormalForward;
  36817. // Misc.
  36818. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36819. // Values that need to be evaluated on every frame
  36820. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  36821. // Attribs
  36822. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  36823. if (mesh) {
  36824. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36825. mesh.createNormals(true);
  36826. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  36827. }
  36828. }
  36829. }
  36830. // Get correct effect
  36831. if (defines.isDirty) {
  36832. defines.markAsProcessed();
  36833. scene.resetCachedMaterial();
  36834. // Fallbacks
  36835. var fallbacks = new BABYLON.EffectFallbacks();
  36836. if (defines.ENVIRONMENTBRDF) {
  36837. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  36838. }
  36839. if (defines.REFLECTION) {
  36840. fallbacks.addFallback(0, "REFLECTION");
  36841. }
  36842. if (defines.REFRACTION) {
  36843. fallbacks.addFallback(0, "REFRACTION");
  36844. }
  36845. if (defines.REFLECTIVITY) {
  36846. fallbacks.addFallback(0, "REFLECTIVITY");
  36847. }
  36848. if (defines.BUMP) {
  36849. fallbacks.addFallback(0, "BUMP");
  36850. }
  36851. if (defines.PARALLAX) {
  36852. fallbacks.addFallback(1, "PARALLAX");
  36853. }
  36854. if (defines.PARALLAXOCCLUSION) {
  36855. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  36856. }
  36857. if (defines.SPECULAROVERALPHA) {
  36858. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  36859. }
  36860. if (defines.FOG) {
  36861. fallbacks.addFallback(1, "FOG");
  36862. }
  36863. if (defines.POINTSIZE) {
  36864. fallbacks.addFallback(0, "POINTSIZE");
  36865. }
  36866. if (defines.LOGARITHMICDEPTH) {
  36867. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  36868. }
  36869. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  36870. if (defines.SPECULARTERM) {
  36871. fallbacks.addFallback(0, "SPECULARTERM");
  36872. }
  36873. if (defines.NUM_BONE_INFLUENCERS > 0) {
  36874. fallbacks.addCPUSkinningFallback(0, mesh);
  36875. }
  36876. //Attributes
  36877. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36878. if (defines.NORMAL) {
  36879. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36880. }
  36881. if (defines.TANGENT) {
  36882. attribs.push(BABYLON.VertexBuffer.TangentKind);
  36883. }
  36884. if (defines.UV1) {
  36885. attribs.push(BABYLON.VertexBuffer.UVKind);
  36886. }
  36887. if (defines.UV2) {
  36888. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36889. }
  36890. if (defines.VERTEXCOLOR) {
  36891. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36892. }
  36893. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36894. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36895. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36896. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  36897. "vFogInfos", "vFogColor", "pointSize",
  36898. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36899. "mBones",
  36900. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36901. "vLightingIntensity",
  36902. "logarithmicDepthConstant",
  36903. "vSphericalX", "vSphericalY", "vSphericalZ",
  36904. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  36905. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  36906. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  36907. "vNormalReoderParams"
  36908. ];
  36909. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  36910. "bumpSampler", "lightmapSampler", "opacitySampler",
  36911. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  36912. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  36913. "microSurfaceSampler", "environmentBrdfSampler"];
  36914. var uniformBuffers = ["Material", "Scene"];
  36915. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36916. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36917. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36918. uniformsNames: uniforms,
  36919. uniformBuffersNames: uniformBuffers,
  36920. samplers: samplers,
  36921. defines: defines,
  36922. maxSimultaneousLights: this._maxSimultaneousLights
  36923. });
  36924. var onCompiled = function (effect) {
  36925. if (this.onCompiled) {
  36926. this.onCompiled(effect);
  36927. }
  36928. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  36929. }.bind(this);
  36930. var join = defines.toString();
  36931. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  36932. attributes: attribs,
  36933. uniformsNames: uniforms,
  36934. uniformBuffersNames: uniformBuffers,
  36935. samplers: samplers,
  36936. defines: join,
  36937. fallbacks: fallbacks,
  36938. onCompiled: onCompiled,
  36939. onError: this.onError,
  36940. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36941. }, engine), defines);
  36942. this.buildUniformLayout();
  36943. }
  36944. if (!subMesh.effect.isReady()) {
  36945. return false;
  36946. }
  36947. defines._renderId = scene.getRenderId();
  36948. this._wasPreviouslyReady = true;
  36949. return true;
  36950. };
  36951. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  36952. // Order is important !
  36953. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  36954. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  36955. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36956. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36957. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36958. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  36959. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  36960. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36961. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36962. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36963. this._uniformBuffer.addUniform("albedoMatrix", 16);
  36964. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36965. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36966. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36967. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36968. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  36969. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  36970. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36971. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  36972. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36973. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36974. this._uniformBuffer.addUniform("vReflectionColor", 3);
  36975. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  36976. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  36977. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  36978. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  36979. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  36980. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36981. this._uniformBuffer.addUniform("pointSize", 1);
  36982. this._uniformBuffer.create();
  36983. };
  36984. PBRBaseMaterial.prototype.unbind = function () {
  36985. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36986. this._uniformBuffer.setTexture("reflectionSampler", null);
  36987. }
  36988. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36989. this._uniformBuffer.setTexture("refractionSampler", null);
  36990. }
  36991. _super.prototype.unbind.call(this);
  36992. };
  36993. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36994. this._activeEffect.setMatrix("world", world);
  36995. };
  36996. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36997. var scene = this.getScene();
  36998. var defines = subMesh._materialDefines;
  36999. if (!defines) {
  37000. return;
  37001. }
  37002. var effect = subMesh.effect;
  37003. this._activeEffect = effect;
  37004. // Matrices
  37005. this.bindOnlyWorldMatrix(world);
  37006. // Bones
  37007. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37008. if (this._mustRebind(scene, effect, mesh.visibility)) {
  37009. this._uniformBuffer.bindToEffect(effect, "Material");
  37010. this.bindViewProjection(effect);
  37011. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37012. // Texture uniforms
  37013. if (scene.texturesEnabled) {
  37014. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37015. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37016. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37017. }
  37018. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37019. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37020. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37021. }
  37022. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37023. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37024. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37025. }
  37026. var reflectionTexture = this._getReflectionTexture();
  37027. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37028. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37029. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37030. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37031. var polynomials = reflectionTexture.sphericalPolynomial;
  37032. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37033. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37034. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37035. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37036. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37037. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37038. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37039. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37040. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37041. }
  37042. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37043. }
  37044. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37045. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37046. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37047. }
  37048. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37049. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37050. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37051. }
  37052. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37053. if (this._metallicTexture) {
  37054. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37055. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37056. }
  37057. else if (this._reflectivityTexture) {
  37058. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37059. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37060. }
  37061. if (this._microSurfaceTexture) {
  37062. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37063. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37064. }
  37065. }
  37066. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37067. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37068. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37069. if (scene._mirroredCameraPosition) {
  37070. this._uniformBuffer.updateFloat4("vNormalReoderParams", this._invertNormalMapX ? 0 : 1.0, this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 0 : 1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37071. }
  37072. else {
  37073. this._uniformBuffer.updateFloat4("vNormalReoderParams", this._invertNormalMapX ? 1.0 : 0, this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? 1.0 : 0, this._invertNormalMapY ? -1.0 : 1.0);
  37074. }
  37075. }
  37076. var refractionTexture = this._getRefractionTexture();
  37077. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37078. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37079. var depth = 1.0;
  37080. if (!refractionTexture.isCube) {
  37081. if (refractionTexture.depth) {
  37082. depth = refractionTexture.depth;
  37083. }
  37084. }
  37085. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37086. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37087. }
  37088. }
  37089. // Point size
  37090. if (this.pointsCloud) {
  37091. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37092. }
  37093. // Colors
  37094. if (defines.METALLICWORKFLOW) {
  37095. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37096. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37097. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37098. }
  37099. else {
  37100. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37101. }
  37102. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37103. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37104. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37105. // Misc
  37106. this._lightingInfos.x = this._directIntensity;
  37107. this._lightingInfos.y = this._emissiveIntensity;
  37108. this._lightingInfos.z = this._environmentIntensity;
  37109. this._lightingInfos.w = this._specularIntensity;
  37110. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37111. }
  37112. // Textures
  37113. if (scene.texturesEnabled) {
  37114. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37115. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37116. }
  37117. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37118. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37119. }
  37120. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37121. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37122. }
  37123. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37124. if (defines.LODBASEDMICROSFURACE) {
  37125. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37126. }
  37127. else {
  37128. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37129. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37130. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37131. }
  37132. }
  37133. if (defines.ENVIRONMENTBRDF) {
  37134. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37135. }
  37136. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37137. if (defines.LODBASEDMICROSFURACE) {
  37138. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37139. }
  37140. else {
  37141. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37142. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37143. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37144. }
  37145. }
  37146. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37147. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37148. }
  37149. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37150. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37151. }
  37152. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37153. if (this._metallicTexture) {
  37154. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37155. }
  37156. else if (this._reflectivityTexture) {
  37157. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37158. }
  37159. if (this._microSurfaceTexture) {
  37160. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37161. }
  37162. }
  37163. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37164. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37165. }
  37166. }
  37167. // Clip plane
  37168. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37169. // Colors
  37170. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37171. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  37172. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  37173. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37174. }
  37175. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  37176. // Lights
  37177. if (scene.lightsEnabled && !this._disableLighting) {
  37178. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37179. }
  37180. // View
  37181. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37182. this.bindView(effect);
  37183. }
  37184. // Fog
  37185. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37186. // Morph targets
  37187. if (defines.NUM_MORPH_INFLUENCERS) {
  37188. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37189. }
  37190. // image processing
  37191. this._imageProcessingConfiguration.bind(this._activeEffect);
  37192. // Log. depth
  37193. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37194. }
  37195. this._uniformBuffer.update();
  37196. this._afterBind(mesh);
  37197. scene = null;
  37198. };
  37199. PBRBaseMaterial.prototype.getAnimatables = function () {
  37200. var results = [];
  37201. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37202. results.push(this._albedoTexture);
  37203. }
  37204. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37205. results.push(this._ambientTexture);
  37206. }
  37207. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37208. results.push(this._opacityTexture);
  37209. }
  37210. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37211. results.push(this._reflectionTexture);
  37212. }
  37213. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37214. results.push(this._emissiveTexture);
  37215. }
  37216. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37217. results.push(this._metallicTexture);
  37218. }
  37219. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37220. results.push(this._reflectivityTexture);
  37221. }
  37222. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37223. results.push(this._bumpTexture);
  37224. }
  37225. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37226. results.push(this._lightmapTexture);
  37227. }
  37228. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37229. results.push(this._refractionTexture);
  37230. }
  37231. return results;
  37232. };
  37233. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  37234. if (this._reflectionTexture) {
  37235. return this._reflectionTexture;
  37236. }
  37237. return this.getScene().environmentTexture;
  37238. };
  37239. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  37240. if (this._refractionTexture) {
  37241. return this._refractionTexture;
  37242. }
  37243. if (this._linkRefractionWithTransparency) {
  37244. return this.getScene().environmentTexture;
  37245. }
  37246. return null;
  37247. };
  37248. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37249. if (forceDisposeTextures) {
  37250. if (this._albedoTexture) {
  37251. this._albedoTexture.dispose();
  37252. }
  37253. if (this._ambientTexture) {
  37254. this._ambientTexture.dispose();
  37255. }
  37256. if (this._opacityTexture) {
  37257. this._opacityTexture.dispose();
  37258. }
  37259. if (this._reflectionTexture) {
  37260. this._reflectionTexture.dispose();
  37261. }
  37262. if (this._environmentBRDFTexture) {
  37263. this._environmentBRDFTexture.dispose();
  37264. }
  37265. if (this._emissiveTexture) {
  37266. this._emissiveTexture.dispose();
  37267. }
  37268. if (this._metallicTexture) {
  37269. this._metallicTexture.dispose();
  37270. }
  37271. if (this._reflectivityTexture) {
  37272. this._reflectivityTexture.dispose();
  37273. }
  37274. if (this._bumpTexture) {
  37275. this._bumpTexture.dispose();
  37276. }
  37277. if (this._lightmapTexture) {
  37278. this._lightmapTexture.dispose();
  37279. }
  37280. if (this._refractionTexture) {
  37281. this._refractionTexture.dispose();
  37282. }
  37283. }
  37284. this._renderTargets.dispose();
  37285. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37286. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37287. }
  37288. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37289. };
  37290. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37291. __decorate([
  37292. BABYLON.serializeAsImageProcessingConfiguration()
  37293. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37294. __decorate([
  37295. BABYLON.serialize()
  37296. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37297. return PBRBaseMaterial;
  37298. }(BABYLON.PushMaterial));
  37299. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37300. })(BABYLON || (BABYLON = {}));
  37301. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37302. var BABYLON;
  37303. (function (BABYLON) {
  37304. var Internals;
  37305. (function (Internals) {
  37306. /**
  37307. * The Physically based simple base material of BJS.
  37308. *
  37309. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37310. * It is used as the base class for both the specGloss and metalRough conventions.
  37311. */
  37312. var PBRBaseSimpleMaterial = (function (_super) {
  37313. __extends(PBRBaseSimpleMaterial, _super);
  37314. /**
  37315. * Instantiates a new PBRMaterial instance.
  37316. *
  37317. * @param name The material name
  37318. * @param scene The scene the material will be use in.
  37319. */
  37320. function PBRBaseSimpleMaterial(name, scene) {
  37321. var _this = _super.call(this, name, scene) || this;
  37322. /**
  37323. * Number of Simultaneous lights allowed on the material.
  37324. */
  37325. _this.maxSimultaneousLights = 4;
  37326. /**
  37327. * If sets to true, disables all the lights affecting the material.
  37328. */
  37329. _this.disableLighting = false;
  37330. /**
  37331. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37332. */
  37333. _this.invertNormalMapX = false;
  37334. /**
  37335. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37336. */
  37337. _this.invertNormalMapY = false;
  37338. /**
  37339. * Emissivie color used to self-illuminate the model.
  37340. */
  37341. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37342. /**
  37343. * Occlusion Channel Strenght.
  37344. */
  37345. _this.occlusionStrength = 1.0;
  37346. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  37347. _this._useAmbientInGrayScale = true;
  37348. return _this;
  37349. }
  37350. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  37351. /**
  37352. * Gets the current transparency mode.
  37353. */
  37354. get: function () {
  37355. return this._transparencyMode;
  37356. },
  37357. /**
  37358. * Sets the transparency mode of the material.
  37359. */
  37360. set: function (value) {
  37361. if (this._transparencyMode === value) {
  37362. return;
  37363. }
  37364. this._transparencyMode = value;
  37365. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  37366. this._forceAlphaTest = true;
  37367. }
  37368. else {
  37369. this._forceAlphaTest = false;
  37370. }
  37371. this._markAllSubMeshesAsTexturesDirty();
  37372. },
  37373. enumerable: true,
  37374. configurable: true
  37375. });
  37376. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37377. /**
  37378. * Gets the current double sided mode.
  37379. */
  37380. get: function () {
  37381. return this._twoSidedLighting;
  37382. },
  37383. /**
  37384. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37385. */
  37386. set: function (value) {
  37387. if (this._twoSidedLighting === value) {
  37388. return;
  37389. }
  37390. this._twoSidedLighting = value;
  37391. this.backFaceCulling = !value;
  37392. this._markAllSubMeshesAsTexturesDirty();
  37393. },
  37394. enumerable: true,
  37395. configurable: true
  37396. });
  37397. /**
  37398. * Specifies wether or not the alpha value of the albedo texture should be used.
  37399. */
  37400. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  37401. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  37402. };
  37403. /**
  37404. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  37405. */
  37406. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  37407. if (this._linkRefractionWithTransparency) {
  37408. return false;
  37409. }
  37410. return (this.alpha < 1.0) ||
  37411. (this._shouldUseAlphaFromAlbedoTexture() &&
  37412. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  37413. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  37414. };
  37415. /**
  37416. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  37417. */
  37418. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  37419. if (this._linkRefractionWithTransparency) {
  37420. return false;
  37421. }
  37422. return this._shouldUseAlphaFromAlbedoTexture() &&
  37423. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  37424. };
  37425. /**
  37426. * Return the active textures of the material.
  37427. */
  37428. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37429. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37430. if (this.environmentTexture) {
  37431. activeTextures.push(this.environmentTexture);
  37432. }
  37433. if (this.normalTexture) {
  37434. activeTextures.push(this.normalTexture);
  37435. }
  37436. if (this.emissiveTexture) {
  37437. activeTextures.push(this.emissiveTexture);
  37438. }
  37439. if (this.occlusionTexture) {
  37440. activeTextures.push(this.occlusionTexture);
  37441. }
  37442. return activeTextures;
  37443. };
  37444. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37445. return "PBRBaseSimpleMaterial";
  37446. };
  37447. __decorate([
  37448. BABYLON.serialize(),
  37449. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37450. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37451. __decorate([
  37452. BABYLON.serialize(),
  37453. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37454. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37455. __decorate([
  37456. BABYLON.serializeAsTexture(),
  37457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37458. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37459. __decorate([
  37460. BABYLON.serialize(),
  37461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37462. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37463. __decorate([
  37464. BABYLON.serialize(),
  37465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37466. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37467. __decorate([
  37468. BABYLON.serializeAsTexture(),
  37469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37470. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37471. __decorate([
  37472. BABYLON.serializeAsColor3("emissive"),
  37473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37474. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37475. __decorate([
  37476. BABYLON.serializeAsTexture(),
  37477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37478. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37479. __decorate([
  37480. BABYLON.serialize(),
  37481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37482. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37483. __decorate([
  37484. BABYLON.serializeAsTexture(),
  37485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37486. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37487. __decorate([
  37488. BABYLON.serialize(),
  37489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37490. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37491. __decorate([
  37492. BABYLON.serialize()
  37493. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  37494. __decorate([
  37495. BABYLON.serialize()
  37496. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37497. return PBRBaseSimpleMaterial;
  37498. }(BABYLON.PBRBaseMaterial));
  37499. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  37500. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37501. })(BABYLON || (BABYLON = {}));
  37502. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  37503. var BABYLON;
  37504. (function (BABYLON) {
  37505. /**
  37506. * The Physically based material of BJS.
  37507. *
  37508. * This offers the main features of a standard PBR material.
  37509. * For more information, please refer to the documentation :
  37510. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37511. */
  37512. var PBRMaterial = (function (_super) {
  37513. __extends(PBRMaterial, _super);
  37514. /**
  37515. * Instantiates a new PBRMaterial instance.
  37516. *
  37517. * @param name The material name
  37518. * @param scene The scene the material will be use in.
  37519. */
  37520. function PBRMaterial(name, scene) {
  37521. var _this = _super.call(this, name, scene) || this;
  37522. /**
  37523. * Intensity of the direct lights e.g. the four lights available in your scene.
  37524. * This impacts both the direct diffuse and specular highlights.
  37525. */
  37526. _this.directIntensity = 1.0;
  37527. /**
  37528. * Intensity of the emissive part of the material.
  37529. * This helps controlling the emissive effect without modifying the emissive color.
  37530. */
  37531. _this.emissiveIntensity = 1.0;
  37532. /**
  37533. * Intensity of the environment e.g. how much the environment will light the object
  37534. * either through harmonics for rough material or through the refelction for shiny ones.
  37535. */
  37536. _this.environmentIntensity = 1.0;
  37537. /**
  37538. * This is a special control allowing the reduction of the specular highlights coming from the
  37539. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37540. */
  37541. _this.specularIntensity = 1.0;
  37542. /**
  37543. * Debug Control allowing disabling the bump map on this material.
  37544. */
  37545. _this.disableBumpMap = false;
  37546. /**
  37547. * AKA Occlusion Texture Intensity in other nomenclature.
  37548. */
  37549. _this.ambientTextureStrength = 1.0;
  37550. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37551. /**
  37552. * AKA Diffuse Color in other nomenclature.
  37553. */
  37554. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  37555. /**
  37556. * AKA Specular Color in other nomenclature.
  37557. */
  37558. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37559. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  37560. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37561. /**
  37562. * AKA Glossiness in other nomenclature.
  37563. */
  37564. _this.microSurface = 1.0;
  37565. /**
  37566. * source material index of refraction (IOR)' / 'destination material IOR.
  37567. */
  37568. _this.indexOfRefraction = 0.66;
  37569. /**
  37570. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37571. */
  37572. _this.invertRefractionY = false;
  37573. /**
  37574. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37575. * Materials half opaque for instance using refraction could benefit from this control.
  37576. */
  37577. _this.linkRefractionWithTransparency = false;
  37578. _this.useLightmapAsShadowmap = false;
  37579. /**
  37580. * Specifies that the alpha is coming form the albedo channel alpha channel.
  37581. */
  37582. _this.useAlphaFromAlbedoTexture = false;
  37583. /**
  37584. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37585. */
  37586. _this.forceAlphaTest = false;
  37587. /**
  37588. * Defines the alpha limits in alpha test mode.
  37589. */
  37590. _this.alphaCutOff = 0.4;
  37591. /**
  37592. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37593. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37594. */
  37595. _this.useSpecularOverAlpha = true;
  37596. /**
  37597. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37598. */
  37599. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  37600. /**
  37601. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37602. */
  37603. _this.useRoughnessFromMetallicTextureAlpha = true;
  37604. /**
  37605. * Specifies if the metallic texture contains the roughness information in its green channel.
  37606. */
  37607. _this.useRoughnessFromMetallicTextureGreen = false;
  37608. /**
  37609. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37610. */
  37611. _this.useMetallnessFromMetallicTextureBlue = false;
  37612. /**
  37613. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37614. */
  37615. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  37616. /**
  37617. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37618. */
  37619. _this.useAmbientInGrayScale = false;
  37620. /**
  37621. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37622. * The material will try to infer what glossiness each pixel should be.
  37623. */
  37624. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  37625. /**
  37626. * BJS is using an harcoded light falloff based on a manually sets up range.
  37627. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37628. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37629. */
  37630. _this.usePhysicalLightFalloff = true;
  37631. /**
  37632. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37633. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37634. */
  37635. _this.useRadianceOverAlpha = true;
  37636. /**
  37637. * Allows using the bump map in parallax mode.
  37638. */
  37639. _this.useParallax = false;
  37640. /**
  37641. * Allows using the bump map in parallax occlusion mode.
  37642. */
  37643. _this.useParallaxOcclusion = false;
  37644. /**
  37645. * Controls the scale bias of the parallax mode.
  37646. */
  37647. _this.parallaxScaleBias = 0.05;
  37648. /**
  37649. * If sets to true, disables all the lights affecting the material.
  37650. */
  37651. _this.disableLighting = false;
  37652. /**
  37653. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37654. */
  37655. _this.forceIrradianceInFragment = false;
  37656. /**
  37657. * Number of Simultaneous lights allowed on the material.
  37658. */
  37659. _this.maxSimultaneousLights = 4;
  37660. /**
  37661. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37662. */
  37663. _this.invertNormalMapX = false;
  37664. /**
  37665. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37666. */
  37667. _this.invertNormalMapY = false;
  37668. /**
  37669. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37670. */
  37671. _this.twoSidedLighting = false;
  37672. /**
  37673. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  37674. * in your scene composition.
  37675. */
  37676. _this.preMultiplyAlpha = false;
  37677. /**
  37678. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37679. * And/Or occlude the blended part.
  37680. */
  37681. _this.useAlphaFresnel = false;
  37682. /**
  37683. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37684. * And/Or occlude the blended part.
  37685. */
  37686. _this.environmentBRDFTexture = null;
  37687. /**
  37688. * Force normal to face away from face.
  37689. * (Temporary internal fix to remove before 3.1)
  37690. */
  37691. _this.forceNormalForward = false;
  37692. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37693. return _this;
  37694. }
  37695. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  37696. /**
  37697. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  37698. */
  37699. get: function () {
  37700. return this._PBRMATERIAL_OPAQUE;
  37701. },
  37702. enumerable: true,
  37703. configurable: true
  37704. });
  37705. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  37706. /**
  37707. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  37708. */
  37709. get: function () {
  37710. return this._PBRMATERIAL_ALPHATEST;
  37711. },
  37712. enumerable: true,
  37713. configurable: true
  37714. });
  37715. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  37716. /**
  37717. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37718. */
  37719. get: function () {
  37720. return this._PBRMATERIAL_ALPHABLEND;
  37721. },
  37722. enumerable: true,
  37723. configurable: true
  37724. });
  37725. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  37726. /**
  37727. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37728. * They are also discarded below the alpha cutoff threshold to improve performances.
  37729. */
  37730. get: function () {
  37731. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  37732. },
  37733. enumerable: true,
  37734. configurable: true
  37735. });
  37736. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  37737. /**
  37738. * Gets the image processing configuration used either in this material.
  37739. */
  37740. get: function () {
  37741. return this._imageProcessingConfiguration;
  37742. },
  37743. /**
  37744. * Sets the Default image processing configuration used either in the this material.
  37745. *
  37746. * If sets to null, the scene one is in use.
  37747. */
  37748. set: function (value) {
  37749. this._attachImageProcessingConfiguration(value);
  37750. // Ensure the effect will be rebuilt.
  37751. this._markAllSubMeshesAsTexturesDirty();
  37752. },
  37753. enumerable: true,
  37754. configurable: true
  37755. });
  37756. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  37757. /**
  37758. * Gets wether the color curves effect is enabled.
  37759. */
  37760. get: function () {
  37761. return this.imageProcessingConfiguration.colorCurvesEnabled;
  37762. },
  37763. /**
  37764. * Sets wether the color curves effect is enabled.
  37765. */
  37766. set: function (value) {
  37767. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  37768. },
  37769. enumerable: true,
  37770. configurable: true
  37771. });
  37772. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  37773. /**
  37774. * Gets wether the color grading effect is enabled.
  37775. */
  37776. get: function () {
  37777. return this.imageProcessingConfiguration.colorGradingEnabled;
  37778. },
  37779. /**
  37780. * Gets wether the color grading effect is enabled.
  37781. */
  37782. set: function (value) {
  37783. this.imageProcessingConfiguration.colorGradingEnabled = value;
  37784. },
  37785. enumerable: true,
  37786. configurable: true
  37787. });
  37788. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  37789. /**
  37790. * Gets wether tonemapping is enabled or not.
  37791. */
  37792. get: function () {
  37793. return this._imageProcessingConfiguration.toneMappingEnabled;
  37794. },
  37795. /**
  37796. * Sets wether tonemapping is enabled or not
  37797. */
  37798. set: function (value) {
  37799. this._imageProcessingConfiguration.toneMappingEnabled = value;
  37800. },
  37801. enumerable: true,
  37802. configurable: true
  37803. });
  37804. ;
  37805. ;
  37806. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  37807. /**
  37808. * The camera exposure used on this material.
  37809. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37810. * This corresponds to a photographic exposure.
  37811. */
  37812. get: function () {
  37813. return this._imageProcessingConfiguration.exposure;
  37814. },
  37815. /**
  37816. * The camera exposure used on this material.
  37817. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37818. * This corresponds to a photographic exposure.
  37819. */
  37820. set: function (value) {
  37821. this._imageProcessingConfiguration.exposure = value;
  37822. },
  37823. enumerable: true,
  37824. configurable: true
  37825. });
  37826. ;
  37827. ;
  37828. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  37829. /**
  37830. * Gets The camera contrast used on this material.
  37831. */
  37832. get: function () {
  37833. return this._imageProcessingConfiguration.contrast;
  37834. },
  37835. /**
  37836. * Sets The camera contrast used on this material.
  37837. */
  37838. set: function (value) {
  37839. this._imageProcessingConfiguration.contrast = value;
  37840. },
  37841. enumerable: true,
  37842. configurable: true
  37843. });
  37844. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  37845. /**
  37846. * Gets the Color Grading 2D Lookup Texture.
  37847. */
  37848. get: function () {
  37849. return this._imageProcessingConfiguration.colorGradingTexture;
  37850. },
  37851. /**
  37852. * Sets the Color Grading 2D Lookup Texture.
  37853. */
  37854. set: function (value) {
  37855. this._imageProcessingConfiguration.colorGradingTexture = value;
  37856. },
  37857. enumerable: true,
  37858. configurable: true
  37859. });
  37860. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  37861. /**
  37862. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37863. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37864. * 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;
  37865. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37866. */
  37867. get: function () {
  37868. return this._imageProcessingConfiguration.colorCurves;
  37869. },
  37870. /**
  37871. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37872. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37873. * 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;
  37874. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37875. */
  37876. set: function (value) {
  37877. this._imageProcessingConfiguration.colorCurves = value;
  37878. },
  37879. enumerable: true,
  37880. configurable: true
  37881. });
  37882. PBRMaterial.prototype.getClassName = function () {
  37883. return "PBRMaterial";
  37884. };
  37885. PBRMaterial.prototype.getActiveTextures = function () {
  37886. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37887. if (this._albedoTexture) {
  37888. activeTextures.push(this._albedoTexture);
  37889. }
  37890. if (this._ambientTexture) {
  37891. activeTextures.push(this._ambientTexture);
  37892. }
  37893. if (this._opacityTexture) {
  37894. activeTextures.push(this._opacityTexture);
  37895. }
  37896. if (this._reflectionTexture) {
  37897. activeTextures.push(this._reflectionTexture);
  37898. }
  37899. if (this._emissiveTexture) {
  37900. activeTextures.push(this._emissiveTexture);
  37901. }
  37902. if (this._reflectivityTexture) {
  37903. activeTextures.push(this._reflectivityTexture);
  37904. }
  37905. if (this._metallicTexture) {
  37906. activeTextures.push(this._metallicTexture);
  37907. }
  37908. if (this._microSurfaceTexture) {
  37909. activeTextures.push(this._microSurfaceTexture);
  37910. }
  37911. if (this._bumpTexture) {
  37912. activeTextures.push(this._bumpTexture);
  37913. }
  37914. if (this._lightmapTexture) {
  37915. activeTextures.push(this._lightmapTexture);
  37916. }
  37917. if (this._refractionTexture) {
  37918. activeTextures.push(this._refractionTexture);
  37919. }
  37920. return activeTextures;
  37921. };
  37922. PBRMaterial.prototype.hasTexture = function (texture) {
  37923. if (_super.prototype.hasTexture.call(this, texture)) {
  37924. return true;
  37925. }
  37926. if (this._albedoTexture === texture) {
  37927. return true;
  37928. }
  37929. if (this._ambientTexture === texture) {
  37930. return true;
  37931. }
  37932. if (this._opacityTexture === texture) {
  37933. return true;
  37934. }
  37935. if (this._reflectionTexture === texture) {
  37936. return true;
  37937. }
  37938. if (this._reflectivityTexture === texture) {
  37939. return true;
  37940. }
  37941. if (this._metallicTexture === texture) {
  37942. return true;
  37943. }
  37944. if (this._microSurfaceTexture === texture) {
  37945. return true;
  37946. }
  37947. if (this._bumpTexture === texture) {
  37948. return true;
  37949. }
  37950. if (this._lightmapTexture === texture) {
  37951. return true;
  37952. }
  37953. if (this._refractionTexture === texture) {
  37954. return true;
  37955. }
  37956. return false;
  37957. };
  37958. PBRMaterial.prototype.clone = function (name) {
  37959. var _this = this;
  37960. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  37961. };
  37962. PBRMaterial.prototype.serialize = function () {
  37963. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37964. serializationObject.customType = "BABYLON.PBRMaterial";
  37965. return serializationObject;
  37966. };
  37967. // Statics
  37968. PBRMaterial.Parse = function (source, scene, rootUrl) {
  37969. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  37970. };
  37971. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  37972. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  37973. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  37974. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  37975. __decorate([
  37976. BABYLON.serialize(),
  37977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37978. ], PBRMaterial.prototype, "directIntensity", void 0);
  37979. __decorate([
  37980. BABYLON.serialize(),
  37981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37982. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  37983. __decorate([
  37984. BABYLON.serialize(),
  37985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37986. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  37987. __decorate([
  37988. BABYLON.serialize(),
  37989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37990. ], PBRMaterial.prototype, "specularIntensity", void 0);
  37991. __decorate([
  37992. BABYLON.serialize(),
  37993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37994. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  37995. __decorate([
  37996. BABYLON.serializeAsTexture(),
  37997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37998. ], PBRMaterial.prototype, "albedoTexture", void 0);
  37999. __decorate([
  38000. BABYLON.serializeAsTexture(),
  38001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38002. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38003. __decorate([
  38004. BABYLON.serialize(),
  38005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38006. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38007. __decorate([
  38008. BABYLON.serializeAsTexture(),
  38009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38010. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38011. __decorate([
  38012. BABYLON.serializeAsTexture(),
  38013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38014. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38015. __decorate([
  38016. BABYLON.serializeAsTexture(),
  38017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38018. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38019. __decorate([
  38020. BABYLON.serializeAsTexture(),
  38021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38022. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38023. __decorate([
  38024. BABYLON.serializeAsTexture(),
  38025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38026. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38027. __decorate([
  38028. BABYLON.serialize(),
  38029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38030. ], PBRMaterial.prototype, "metallic", void 0);
  38031. __decorate([
  38032. BABYLON.serialize(),
  38033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38034. ], PBRMaterial.prototype, "roughness", void 0);
  38035. __decorate([
  38036. BABYLON.serializeAsTexture(),
  38037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38038. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38039. __decorate([
  38040. BABYLON.serializeAsTexture(),
  38041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38042. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38043. __decorate([
  38044. BABYLON.serializeAsTexture(),
  38045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38046. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38047. __decorate([
  38048. BABYLON.serializeAsTexture(),
  38049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38050. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38051. __decorate([
  38052. BABYLON.serializeAsColor3("ambient"),
  38053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38054. ], PBRMaterial.prototype, "ambientColor", void 0);
  38055. __decorate([
  38056. BABYLON.serializeAsColor3("albedo"),
  38057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38058. ], PBRMaterial.prototype, "albedoColor", void 0);
  38059. __decorate([
  38060. BABYLON.serializeAsColor3("reflectivity"),
  38061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38062. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38063. __decorate([
  38064. BABYLON.serializeAsColor3("reflection"),
  38065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38066. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38067. __decorate([
  38068. BABYLON.serializeAsColor3("emissive"),
  38069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38070. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38071. __decorate([
  38072. BABYLON.serialize(),
  38073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38074. ], PBRMaterial.prototype, "microSurface", void 0);
  38075. __decorate([
  38076. BABYLON.serialize(),
  38077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38078. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38079. __decorate([
  38080. BABYLON.serialize(),
  38081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38082. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38083. __decorate([
  38084. BABYLON.serialize(),
  38085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38086. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38087. __decorate([
  38088. BABYLON.serialize(),
  38089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38090. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38091. __decorate([
  38092. BABYLON.serialize(),
  38093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38094. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38095. __decorate([
  38096. BABYLON.serialize(),
  38097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38098. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38099. __decorate([
  38100. BABYLON.serialize(),
  38101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38102. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38103. __decorate([
  38104. BABYLON.serialize(),
  38105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38106. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38107. __decorate([
  38108. BABYLON.serialize(),
  38109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38110. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38111. __decorate([
  38112. BABYLON.serialize(),
  38113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38114. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38115. __decorate([
  38116. BABYLON.serialize(),
  38117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38118. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38119. __decorate([
  38120. BABYLON.serialize(),
  38121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38122. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38123. __decorate([
  38124. BABYLON.serialize(),
  38125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38126. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38127. __decorate([
  38128. BABYLON.serialize(),
  38129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38130. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38131. __decorate([
  38132. BABYLON.serialize(),
  38133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38134. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38135. __decorate([
  38136. BABYLON.serialize(),
  38137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38138. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38139. __decorate([
  38140. BABYLON.serialize(),
  38141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38142. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38143. __decorate([
  38144. BABYLON.serialize(),
  38145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38146. ], PBRMaterial.prototype, "useParallax", void 0);
  38147. __decorate([
  38148. BABYLON.serialize(),
  38149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38150. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38151. __decorate([
  38152. BABYLON.serialize(),
  38153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38154. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38155. __decorate([
  38156. BABYLON.serialize(),
  38157. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38158. ], PBRMaterial.prototype, "disableLighting", void 0);
  38159. __decorate([
  38160. BABYLON.serialize(),
  38161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38162. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38163. __decorate([
  38164. BABYLON.serialize(),
  38165. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38166. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38167. __decorate([
  38168. BABYLON.serialize(),
  38169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38170. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38171. __decorate([
  38172. BABYLON.serialize(),
  38173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38174. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38175. __decorate([
  38176. BABYLON.serialize(),
  38177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38178. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38179. __decorate([
  38180. BABYLON.serialize(),
  38181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38182. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  38183. __decorate([
  38184. BABYLON.serialize(),
  38185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38186. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38187. __decorate([
  38188. BABYLON.serializeAsTexture(),
  38189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38190. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38191. __decorate([
  38192. BABYLON.serialize(),
  38193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38194. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38195. return PBRMaterial;
  38196. }(BABYLON.PBRBaseMaterial));
  38197. BABYLON.PBRMaterial = PBRMaterial;
  38198. })(BABYLON || (BABYLON = {}));
  38199. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38200. var BABYLON;
  38201. (function (BABYLON) {
  38202. /**
  38203. * The PBR material of BJS following the metal roughness convention.
  38204. *
  38205. * This fits to the PBR convention in the GLTF definition:
  38206. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38207. */
  38208. var PBRMetallicRoughnessMaterial = (function (_super) {
  38209. __extends(PBRMetallicRoughnessMaterial, _super);
  38210. /**
  38211. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38212. *
  38213. * @param name The material name
  38214. * @param scene The scene the material will be use in.
  38215. */
  38216. function PBRMetallicRoughnessMaterial(name, scene) {
  38217. var _this = _super.call(this, name, scene) || this;
  38218. _this._useRoughnessFromMetallicTextureAlpha = false;
  38219. _this._useRoughnessFromMetallicTextureGreen = true;
  38220. _this._useMetallnessFromMetallicTextureBlue = true;
  38221. return _this;
  38222. }
  38223. /**
  38224. * Return the currrent class name of the material.
  38225. */
  38226. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38227. return "PBRMetallicRoughnessMaterial";
  38228. };
  38229. /**
  38230. * Return the active textures of the material.
  38231. */
  38232. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  38233. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38234. if (this.baseTexture) {
  38235. activeTextures.push(this.baseTexture);
  38236. }
  38237. if (this.metallicRoughnessTexture) {
  38238. activeTextures.push(this.metallicRoughnessTexture);
  38239. }
  38240. return activeTextures;
  38241. };
  38242. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  38243. if (_super.prototype.hasTexture.call(this, texture)) {
  38244. return true;
  38245. }
  38246. if (this.baseTexture === texture) {
  38247. return true;
  38248. }
  38249. if (this.metallicRoughnessTexture === texture) {
  38250. return true;
  38251. }
  38252. return false;
  38253. };
  38254. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  38255. var _this = this;
  38256. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  38257. };
  38258. /**
  38259. * Serialize the material to a parsable JSON object.
  38260. */
  38261. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  38262. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38263. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  38264. return serializationObject;
  38265. };
  38266. /**
  38267. * Parses a JSON object correponding to the serialize function.
  38268. */
  38269. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38270. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38271. };
  38272. __decorate([
  38273. BABYLON.serializeAsColor3(),
  38274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38275. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38276. __decorate([
  38277. BABYLON.serializeAsTexture(),
  38278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38279. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38280. __decorate([
  38281. BABYLON.serialize(),
  38282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38283. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38284. __decorate([
  38285. BABYLON.serialize(),
  38286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38287. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38288. __decorate([
  38289. BABYLON.serializeAsTexture(),
  38290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38291. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38292. return PBRMetallicRoughnessMaterial;
  38293. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38294. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38295. })(BABYLON || (BABYLON = {}));
  38296. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38297. var BABYLON;
  38298. (function (BABYLON) {
  38299. /**
  38300. * The PBR material of BJS following the specular glossiness convention.
  38301. *
  38302. * This fits to the PBR convention in the GLTF definition:
  38303. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38304. */
  38305. var PBRSpecularGlossinessMaterial = (function (_super) {
  38306. __extends(PBRSpecularGlossinessMaterial, _super);
  38307. /**
  38308. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38309. *
  38310. * @param name The material name
  38311. * @param scene The scene the material will be use in.
  38312. */
  38313. function PBRSpecularGlossinessMaterial(name, scene) {
  38314. var _this = _super.call(this, name, scene) || this;
  38315. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38316. return _this;
  38317. }
  38318. /**
  38319. * Return the currrent class name of the material.
  38320. */
  38321. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38322. return "PBRSpecularGlossinessMaterial";
  38323. };
  38324. /**
  38325. * Return the active textures of the material.
  38326. */
  38327. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38328. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38329. if (this.diffuseTexture) {
  38330. activeTextures.push(this.diffuseTexture);
  38331. }
  38332. if (this.specularGlossinessTexture) {
  38333. activeTextures.push(this.specularGlossinessTexture);
  38334. }
  38335. return activeTextures;
  38336. };
  38337. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38338. if (_super.prototype.hasTexture.call(this, texture)) {
  38339. return true;
  38340. }
  38341. if (this.diffuseTexture === texture) {
  38342. return true;
  38343. }
  38344. if (this.specularGlossinessTexture === texture) {
  38345. return true;
  38346. }
  38347. return false;
  38348. };
  38349. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  38350. var _this = this;
  38351. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  38352. };
  38353. /**
  38354. * Serialize the material to a parsable JSON object.
  38355. */
  38356. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  38357. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38358. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  38359. return serializationObject;
  38360. };
  38361. /**
  38362. * Parses a JSON object correponding to the serialize function.
  38363. */
  38364. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38365. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38366. };
  38367. __decorate([
  38368. BABYLON.serializeAsColor3("diffuse"),
  38369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38370. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38371. __decorate([
  38372. BABYLON.serializeAsTexture(),
  38373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38374. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38375. __decorate([
  38376. BABYLON.serializeAsColor3("specular"),
  38377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38378. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38379. __decorate([
  38380. BABYLON.serialize(),
  38381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38382. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38383. __decorate([
  38384. BABYLON.serializeAsTexture(),
  38385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38386. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38387. return PBRSpecularGlossinessMaterial;
  38388. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38389. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38390. })(BABYLON || (BABYLON = {}));
  38391. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38392. var BABYLON;
  38393. (function (BABYLON) {
  38394. var ShaderMaterial = (function (_super) {
  38395. __extends(ShaderMaterial, _super);
  38396. function ShaderMaterial(name, scene, shaderPath, options) {
  38397. var _this = _super.call(this, name, scene) || this;
  38398. _this._textures = {};
  38399. _this._textureArrays = {};
  38400. _this._floats = {};
  38401. _this._floatsArrays = {};
  38402. _this._colors3 = {};
  38403. _this._colors3Arrays = {};
  38404. _this._colors4 = {};
  38405. _this._vectors2 = {};
  38406. _this._vectors3 = {};
  38407. _this._vectors4 = {};
  38408. _this._matrices = {};
  38409. _this._matrices3x3 = {};
  38410. _this._matrices2x2 = {};
  38411. _this._vectors3Arrays = {};
  38412. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  38413. _this._shaderPath = shaderPath;
  38414. options.needAlphaBlending = options.needAlphaBlending || false;
  38415. options.needAlphaTesting = options.needAlphaTesting || false;
  38416. options.attributes = options.attributes || ["position", "normal", "uv"];
  38417. options.uniforms = options.uniforms || ["worldViewProjection"];
  38418. options.uniformBuffers = options.uniformBuffers || [];
  38419. options.samplers = options.samplers || [];
  38420. options.defines = options.defines || [];
  38421. _this._options = options;
  38422. return _this;
  38423. }
  38424. ShaderMaterial.prototype.getClassName = function () {
  38425. return "ShaderMaterial";
  38426. };
  38427. ShaderMaterial.prototype.needAlphaBlending = function () {
  38428. return this._options.needAlphaBlending;
  38429. };
  38430. ShaderMaterial.prototype.needAlphaTesting = function () {
  38431. return this._options.needAlphaTesting;
  38432. };
  38433. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  38434. if (this._options.uniforms.indexOf(uniformName) === -1) {
  38435. this._options.uniforms.push(uniformName);
  38436. }
  38437. };
  38438. ShaderMaterial.prototype.setTexture = function (name, texture) {
  38439. if (this._options.samplers.indexOf(name) === -1) {
  38440. this._options.samplers.push(name);
  38441. }
  38442. this._textures[name] = texture;
  38443. return this;
  38444. };
  38445. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  38446. if (this._options.samplers.indexOf(name) === -1) {
  38447. this._options.samplers.push(name);
  38448. }
  38449. this._checkUniform(name);
  38450. this._textureArrays[name] = textures;
  38451. return this;
  38452. };
  38453. ShaderMaterial.prototype.setFloat = function (name, value) {
  38454. this._checkUniform(name);
  38455. this._floats[name] = value;
  38456. return this;
  38457. };
  38458. ShaderMaterial.prototype.setFloats = function (name, value) {
  38459. this._checkUniform(name);
  38460. this._floatsArrays[name] = value;
  38461. return this;
  38462. };
  38463. ShaderMaterial.prototype.setColor3 = function (name, value) {
  38464. this._checkUniform(name);
  38465. this._colors3[name] = value;
  38466. return this;
  38467. };
  38468. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  38469. this._checkUniform(name);
  38470. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  38471. color.toArray(arr, arr.length);
  38472. return arr;
  38473. }, []);
  38474. return this;
  38475. };
  38476. ShaderMaterial.prototype.setColor4 = function (name, value) {
  38477. this._checkUniform(name);
  38478. this._colors4[name] = value;
  38479. return this;
  38480. };
  38481. ShaderMaterial.prototype.setVector2 = function (name, value) {
  38482. this._checkUniform(name);
  38483. this._vectors2[name] = value;
  38484. return this;
  38485. };
  38486. ShaderMaterial.prototype.setVector3 = function (name, value) {
  38487. this._checkUniform(name);
  38488. this._vectors3[name] = value;
  38489. return this;
  38490. };
  38491. ShaderMaterial.prototype.setVector4 = function (name, value) {
  38492. this._checkUniform(name);
  38493. this._vectors4[name] = value;
  38494. return this;
  38495. };
  38496. ShaderMaterial.prototype.setMatrix = function (name, value) {
  38497. this._checkUniform(name);
  38498. this._matrices[name] = value;
  38499. return this;
  38500. };
  38501. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  38502. this._checkUniform(name);
  38503. this._matrices3x3[name] = value;
  38504. return this;
  38505. };
  38506. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  38507. this._checkUniform(name);
  38508. this._matrices2x2[name] = value;
  38509. return this;
  38510. };
  38511. ShaderMaterial.prototype.setArray3 = function (name, value) {
  38512. this._checkUniform(name);
  38513. this._vectors3Arrays[name] = value;
  38514. return this;
  38515. };
  38516. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  38517. if (!mesh) {
  38518. return true;
  38519. }
  38520. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  38521. return false;
  38522. }
  38523. return false;
  38524. };
  38525. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  38526. var scene = this.getScene();
  38527. var engine = scene.getEngine();
  38528. if (!this.checkReadyOnEveryCall) {
  38529. if (this._renderId === scene.getRenderId()) {
  38530. if (this._checkCache(scene, mesh, useInstances)) {
  38531. return true;
  38532. }
  38533. }
  38534. }
  38535. // Instances
  38536. var defines = [];
  38537. var attribs = [];
  38538. var fallbacks = new BABYLON.EffectFallbacks();
  38539. if (useInstances) {
  38540. defines.push("#define INSTANCES");
  38541. }
  38542. for (var index = 0; index < this._options.defines.length; index++) {
  38543. defines.push(this._options.defines[index]);
  38544. }
  38545. for (var index = 0; index < this._options.attributes.length; index++) {
  38546. attribs.push(this._options.attributes[index]);
  38547. }
  38548. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38549. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38550. defines.push("#define VERTEXCOLOR");
  38551. }
  38552. // Bones
  38553. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  38554. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38555. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38556. if (mesh.numBoneInfluencers > 4) {
  38557. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38558. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38559. }
  38560. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38561. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38562. fallbacks.addCPUSkinningFallback(0, mesh);
  38563. if (this._options.uniforms.indexOf("mBones") === -1) {
  38564. this._options.uniforms.push("mBones");
  38565. }
  38566. }
  38567. else {
  38568. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38569. }
  38570. // Textures
  38571. for (var name in this._textures) {
  38572. if (!this._textures[name].isReady()) {
  38573. return false;
  38574. }
  38575. }
  38576. // Alpha test
  38577. if (engine.getAlphaTesting()) {
  38578. defines.push("#define ALPHATEST");
  38579. }
  38580. var previousEffect = this._effect;
  38581. var join = defines.join("\n");
  38582. this._effect = engine.createEffect(this._shaderPath, {
  38583. attributes: attribs,
  38584. uniformsNames: this._options.uniforms,
  38585. uniformBuffersNames: this._options.uniformBuffers,
  38586. samplers: this._options.samplers,
  38587. defines: join,
  38588. fallbacks: fallbacks,
  38589. onCompiled: this.onCompiled,
  38590. onError: this.onError
  38591. }, engine);
  38592. if (!this._effect.isReady()) {
  38593. return false;
  38594. }
  38595. if (previousEffect !== this._effect) {
  38596. scene.resetCachedMaterial();
  38597. }
  38598. this._renderId = scene.getRenderId();
  38599. return true;
  38600. };
  38601. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38602. var scene = this.getScene();
  38603. if (this._options.uniforms.indexOf("world") !== -1) {
  38604. this._effect.setMatrix("world", world);
  38605. }
  38606. if (this._options.uniforms.indexOf("worldView") !== -1) {
  38607. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  38608. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  38609. }
  38610. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  38611. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  38612. }
  38613. };
  38614. ShaderMaterial.prototype.bind = function (world, mesh) {
  38615. // Std values
  38616. this.bindOnlyWorldMatrix(world);
  38617. if (this.getScene().getCachedMaterial() !== this) {
  38618. if (this._options.uniforms.indexOf("view") !== -1) {
  38619. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  38620. }
  38621. if (this._options.uniforms.indexOf("projection") !== -1) {
  38622. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  38623. }
  38624. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  38625. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  38626. }
  38627. // Bones
  38628. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  38629. var name;
  38630. // Texture
  38631. for (name in this._textures) {
  38632. this._effect.setTexture(name, this._textures[name]);
  38633. }
  38634. // Texture arrays
  38635. for (name in this._textureArrays) {
  38636. this._effect.setTextureArray(name, this._textureArrays[name]);
  38637. }
  38638. // Float
  38639. for (name in this._floats) {
  38640. this._effect.setFloat(name, this._floats[name]);
  38641. }
  38642. // Float s
  38643. for (name in this._floatsArrays) {
  38644. this._effect.setArray(name, this._floatsArrays[name]);
  38645. }
  38646. // Color3
  38647. for (name in this._colors3) {
  38648. this._effect.setColor3(name, this._colors3[name]);
  38649. }
  38650. for (name in this._colors3Arrays) {
  38651. this._effect.setArray3(name, this._colors3Arrays[name]);
  38652. }
  38653. // Color4
  38654. for (name in this._colors4) {
  38655. var color = this._colors4[name];
  38656. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  38657. }
  38658. // Vector2
  38659. for (name in this._vectors2) {
  38660. this._effect.setVector2(name, this._vectors2[name]);
  38661. }
  38662. // Vector3
  38663. for (name in this._vectors3) {
  38664. this._effect.setVector3(name, this._vectors3[name]);
  38665. }
  38666. // Vector4
  38667. for (name in this._vectors4) {
  38668. this._effect.setVector4(name, this._vectors4[name]);
  38669. }
  38670. // Matrix
  38671. for (name in this._matrices) {
  38672. this._effect.setMatrix(name, this._matrices[name]);
  38673. }
  38674. // Matrix 3x3
  38675. for (name in this._matrices3x3) {
  38676. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  38677. }
  38678. // Matrix 2x2
  38679. for (name in this._matrices2x2) {
  38680. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  38681. }
  38682. // Vector3Array
  38683. for (name in this._vectors3Arrays) {
  38684. this._effect.setArray3(name, this._vectors3Arrays[name]);
  38685. }
  38686. }
  38687. this._afterBind(mesh);
  38688. };
  38689. ShaderMaterial.prototype.getActiveTextures = function () {
  38690. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38691. for (var name in this._textures) {
  38692. activeTextures.push(this._textures[name]);
  38693. }
  38694. for (var name in this._textureArrays) {
  38695. var array = this._textureArrays[name];
  38696. for (var index = 0; index < array.length; index++) {
  38697. activeTextures.push(array[index]);
  38698. }
  38699. }
  38700. return activeTextures;
  38701. };
  38702. ShaderMaterial.prototype.hasTexture = function (texture) {
  38703. if (_super.prototype.hasTexture.call(this, texture)) {
  38704. return true;
  38705. }
  38706. for (var name in this._textures) {
  38707. if (this._textures[name] === texture) {
  38708. return true;
  38709. }
  38710. }
  38711. for (var name in this._textureArrays) {
  38712. var array = this._textureArrays[name];
  38713. for (var index = 0; index < array.length; index++) {
  38714. if (array[index] === texture) {
  38715. return true;
  38716. }
  38717. }
  38718. }
  38719. return false;
  38720. };
  38721. ShaderMaterial.prototype.clone = function (name) {
  38722. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  38723. return newShaderMaterial;
  38724. };
  38725. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38726. if (forceDisposeTextures) {
  38727. var name;
  38728. for (name in this._textures) {
  38729. this._textures[name].dispose();
  38730. }
  38731. for (name in this._textureArrays) {
  38732. var array = this._textureArrays[name];
  38733. for (var index = 0; index < array.length; index++) {
  38734. array[index].dispose();
  38735. }
  38736. }
  38737. }
  38738. this._textures = {};
  38739. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38740. };
  38741. ShaderMaterial.prototype.serialize = function () {
  38742. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38743. serializationObject.customType = "BABYLON.ShaderMaterial";
  38744. serializationObject.options = this._options;
  38745. serializationObject.shaderPath = this._shaderPath;
  38746. var name;
  38747. // Texture
  38748. serializationObject.textures = {};
  38749. for (name in this._textures) {
  38750. serializationObject.textures[name] = this._textures[name].serialize();
  38751. }
  38752. // Texture arrays
  38753. serializationObject.textureArrays = {};
  38754. for (name in this._textureArrays) {
  38755. serializationObject.textureArrays[name] = [];
  38756. var array = this._textureArrays[name];
  38757. for (var index = 0; index < array.length; index++) {
  38758. serializationObject.textureArrays[name].push(array[index].serialize());
  38759. }
  38760. }
  38761. // Float
  38762. serializationObject.floats = {};
  38763. for (name in this._floats) {
  38764. serializationObject.floats[name] = this._floats[name];
  38765. }
  38766. // Float s
  38767. serializationObject.floatArrays = {};
  38768. for (name in this._floatsArrays) {
  38769. serializationObject.floatArrays[name] = this._floatsArrays[name];
  38770. }
  38771. // Color3
  38772. serializationObject.colors3 = {};
  38773. for (name in this._colors3) {
  38774. serializationObject.colors3[name] = this._colors3[name].asArray();
  38775. }
  38776. // Color3 array
  38777. serializationObject.colors3Arrays = {};
  38778. for (name in this._colors3Arrays) {
  38779. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  38780. }
  38781. // Color4
  38782. serializationObject.colors4 = {};
  38783. for (name in this._colors4) {
  38784. serializationObject.colors4[name] = this._colors4[name].asArray();
  38785. }
  38786. // Vector2
  38787. serializationObject.vectors2 = {};
  38788. for (name in this._vectors2) {
  38789. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  38790. }
  38791. // Vector3
  38792. serializationObject.vectors3 = {};
  38793. for (name in this._vectors3) {
  38794. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  38795. }
  38796. // Vector4
  38797. serializationObject.vectors4 = {};
  38798. for (name in this._vectors4) {
  38799. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  38800. }
  38801. // Matrix
  38802. serializationObject.matrices = {};
  38803. for (name in this._matrices) {
  38804. serializationObject.matrices[name] = this._matrices[name].asArray();
  38805. }
  38806. // Matrix 3x3
  38807. serializationObject.matrices3x3 = {};
  38808. for (name in this._matrices3x3) {
  38809. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  38810. }
  38811. // Matrix 2x2
  38812. serializationObject.matrices2x2 = {};
  38813. for (name in this._matrices2x2) {
  38814. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  38815. }
  38816. // Vector3Array
  38817. serializationObject.vectors3Arrays = {};
  38818. for (name in this._vectors3Arrays) {
  38819. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  38820. }
  38821. return serializationObject;
  38822. };
  38823. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  38824. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  38825. var name;
  38826. // Texture
  38827. for (name in source.textures) {
  38828. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  38829. }
  38830. // Texture arrays
  38831. for (name in source.textureArrays) {
  38832. var array = source.textureArrays[name];
  38833. var textureArray = new Array();
  38834. for (var index = 0; index < array.length; index++) {
  38835. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  38836. }
  38837. material.setTextureArray(name, textureArray);
  38838. }
  38839. // Float
  38840. for (name in source.floats) {
  38841. material.setFloat(name, source.floats[name]);
  38842. }
  38843. // Float s
  38844. for (name in source.floatsArrays) {
  38845. material.setFloats(name, source.floatsArrays[name]);
  38846. }
  38847. // Color3
  38848. for (name in source.colors3) {
  38849. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  38850. }
  38851. // Color3 arrays
  38852. for (name in source.colors3Arrays) {
  38853. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  38854. if (i % 3 === 0) {
  38855. arr.push([num]);
  38856. }
  38857. else {
  38858. arr[arr.length - 1].push(num);
  38859. }
  38860. return arr;
  38861. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  38862. material.setColor3Array(name, colors);
  38863. }
  38864. // Color4
  38865. for (name in source.colors4) {
  38866. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  38867. }
  38868. // Vector2
  38869. for (name in source.vectors2) {
  38870. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  38871. }
  38872. // Vector3
  38873. for (name in source.vectors3) {
  38874. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  38875. }
  38876. // Vector4
  38877. for (name in source.vectors4) {
  38878. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  38879. }
  38880. // Matrix
  38881. for (name in source.matrices) {
  38882. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  38883. }
  38884. // Matrix 3x3
  38885. for (name in source.matrices3x3) {
  38886. material.setMatrix3x3(name, source.matrices3x3[name]);
  38887. }
  38888. // Matrix 2x2
  38889. for (name in source.matrices2x2) {
  38890. material.setMatrix2x2(name, source.matrices2x2[name]);
  38891. }
  38892. // Vector3Array
  38893. for (name in source.vectors3Arrays) {
  38894. material.setArray3(name, source.vectors3Arrays[name]);
  38895. }
  38896. return material;
  38897. };
  38898. return ShaderMaterial;
  38899. }(BABYLON.Material));
  38900. BABYLON.ShaderMaterial = ShaderMaterial;
  38901. })(BABYLON || (BABYLON = {}));
  38902. //# sourceMappingURL=babylon.shaderMaterial.js.map
  38903. var BABYLON;
  38904. (function (BABYLON) {
  38905. var MeshBuilder = (function () {
  38906. function MeshBuilder() {
  38907. }
  38908. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  38909. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  38910. return BABYLON.Mesh.DOUBLESIDE;
  38911. }
  38912. if (orientation === undefined || orientation === null) {
  38913. return BABYLON.Mesh.FRONTSIDE;
  38914. }
  38915. return orientation;
  38916. };
  38917. /**
  38918. * Creates a box mesh.
  38919. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  38920. * The parameter `size` sets the size (float) of each box side (default 1).
  38921. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  38922. * 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).
  38923. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  38924. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38925. * 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).
  38926. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38927. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38928. */
  38929. MeshBuilder.CreateBox = function (name, options, scene) {
  38930. var box = new BABYLON.Mesh(name, scene);
  38931. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38932. box.sideOrientation = options.sideOrientation;
  38933. var vertexData = BABYLON.VertexData.CreateBox(options);
  38934. vertexData.applyToMesh(box, options.updatable);
  38935. return box;
  38936. };
  38937. /**
  38938. * Creates a sphere mesh.
  38939. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  38940. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  38941. * 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`).
  38942. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  38943. * 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
  38944. * 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).
  38945. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38946. * 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).
  38947. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38948. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38949. */
  38950. MeshBuilder.CreateSphere = function (name, options, scene) {
  38951. var sphere = new BABYLON.Mesh(name, scene);
  38952. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38953. sphere.sideOrientation = options.sideOrientation;
  38954. var vertexData = BABYLON.VertexData.CreateSphere(options);
  38955. vertexData.applyToMesh(sphere, options.updatable);
  38956. return sphere;
  38957. };
  38958. /**
  38959. * Creates a plane polygonal mesh. By default, this is a disc.
  38960. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  38961. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  38962. * 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.
  38963. * 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
  38964. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38965. * 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).
  38966. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38967. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38968. */
  38969. MeshBuilder.CreateDisc = function (name, options, scene) {
  38970. var disc = new BABYLON.Mesh(name, scene);
  38971. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38972. disc.sideOrientation = options.sideOrientation;
  38973. var vertexData = BABYLON.VertexData.CreateDisc(options);
  38974. vertexData.applyToMesh(disc, options.updatable);
  38975. return disc;
  38976. };
  38977. /**
  38978. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  38979. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  38980. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  38981. * 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`).
  38982. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  38983. * 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.
  38984. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38985. * 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).
  38986. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38987. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38988. */
  38989. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  38990. var sphere = new BABYLON.Mesh(name, scene);
  38991. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38992. sphere.sideOrientation = options.sideOrientation;
  38993. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  38994. vertexData.applyToMesh(sphere, options.updatable);
  38995. return sphere;
  38996. };
  38997. ;
  38998. /**
  38999. * Creates a ribbon mesh.
  39000. * 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.
  39001. *
  39002. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  39003. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  39004. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  39005. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  39006. * 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.
  39007. * 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.
  39008. * 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
  39009. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39010. * 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).
  39011. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39012. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39013. * 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.
  39014. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  39015. * 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
  39016. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  39017. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  39018. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39019. */
  39020. MeshBuilder.CreateRibbon = function (name, options, scene) {
  39021. var pathArray = options.pathArray;
  39022. var closeArray = options.closeArray;
  39023. var closePath = options.closePath;
  39024. var offset = options.offset;
  39025. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39026. var instance = options.instance;
  39027. var updatable = options.updatable;
  39028. if (instance) {
  39029. // positionFunction : ribbon case
  39030. // only pathArray and sideOrientation parameters are taken into account for positions update
  39031. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  39032. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  39033. var positionFunction = function (positions) {
  39034. var minlg = pathArray[0].length;
  39035. var i = 0;
  39036. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  39037. for (var si = 1; si <= ns; si++) {
  39038. for (var p = 0; p < pathArray.length; p++) {
  39039. var path = pathArray[p];
  39040. var l = path.length;
  39041. minlg = (minlg < l) ? minlg : l;
  39042. var j = 0;
  39043. while (j < minlg) {
  39044. positions[i] = path[j].x;
  39045. positions[i + 1] = path[j].y;
  39046. positions[i + 2] = path[j].z;
  39047. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  39048. BABYLON.Tmp.Vector3[0].x = path[j].x;
  39049. }
  39050. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  39051. BABYLON.Tmp.Vector3[1].x = path[j].x;
  39052. }
  39053. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  39054. BABYLON.Tmp.Vector3[0].y = path[j].y;
  39055. }
  39056. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  39057. BABYLON.Tmp.Vector3[1].y = path[j].y;
  39058. }
  39059. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  39060. BABYLON.Tmp.Vector3[0].z = path[j].z;
  39061. }
  39062. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  39063. BABYLON.Tmp.Vector3[1].z = path[j].z;
  39064. }
  39065. j++;
  39066. i += 3;
  39067. }
  39068. if (instance._closePath) {
  39069. positions[i] = path[0].x;
  39070. positions[i + 1] = path[0].y;
  39071. positions[i + 2] = path[0].z;
  39072. i += 3;
  39073. }
  39074. }
  39075. }
  39076. };
  39077. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39078. positionFunction(positions);
  39079. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  39080. instance._boundingInfo.update(instance._worldMatrix);
  39081. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  39082. if (options.colors) {
  39083. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39084. for (var c = 0; c < options.colors.length; c++) {
  39085. colors[c * 4] = options.colors[c].r;
  39086. colors[c * 4 + 1] = options.colors[c].g;
  39087. colors[c * 4 + 2] = options.colors[c].b;
  39088. colors[c * 4 + 3] = options.colors[c].a;
  39089. }
  39090. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  39091. }
  39092. if (options.uvs) {
  39093. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39094. for (var i = 0; i < options.uvs.length; i++) {
  39095. uvs[i * 2] = options.uvs[i].x;
  39096. uvs[i * 2 + 1] = options.uvs[i].y;
  39097. }
  39098. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  39099. }
  39100. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  39101. var indices = instance.getIndices();
  39102. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39103. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  39104. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  39105. if (instance._closePath) {
  39106. var indexFirst = 0;
  39107. var indexLast = 0;
  39108. for (var p = 0; p < pathArray.length; p++) {
  39109. indexFirst = instance._idx[p] * 3;
  39110. if (p + 1 < pathArray.length) {
  39111. indexLast = (instance._idx[p + 1] - 1) * 3;
  39112. }
  39113. else {
  39114. indexLast = normals.length - 3;
  39115. }
  39116. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  39117. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  39118. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  39119. normals[indexLast] = normals[indexFirst];
  39120. normals[indexLast + 1] = normals[indexFirst + 1];
  39121. normals[indexLast + 2] = normals[indexFirst + 2];
  39122. }
  39123. }
  39124. if (!(instance.areNormalsFrozen)) {
  39125. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  39126. }
  39127. }
  39128. return instance;
  39129. }
  39130. else {
  39131. var ribbon = new BABYLON.Mesh(name, scene);
  39132. ribbon.sideOrientation = sideOrientation;
  39133. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  39134. if (closePath) {
  39135. ribbon._idx = vertexData._idx;
  39136. }
  39137. ribbon._closePath = closePath;
  39138. ribbon._closeArray = closeArray;
  39139. vertexData.applyToMesh(ribbon, updatable);
  39140. return ribbon;
  39141. }
  39142. };
  39143. /**
  39144. * Creates a cylinder or a cone mesh.
  39145. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  39146. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  39147. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  39148. * 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.
  39149. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  39150. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  39151. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  39152. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  39153. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  39154. * 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).
  39155. * 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
  39156. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  39157. * 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
  39158. * 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.
  39159. * If `enclose` is false, a ring surface is one element.
  39160. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  39161. * 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
  39162. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39163. * 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).
  39164. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39165. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39166. */
  39167. MeshBuilder.CreateCylinder = function (name, options, scene) {
  39168. var cylinder = new BABYLON.Mesh(name, scene);
  39169. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39170. cylinder.sideOrientation = options.sideOrientation;
  39171. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  39172. vertexData.applyToMesh(cylinder, options.updatable);
  39173. return cylinder;
  39174. };
  39175. /**
  39176. * Creates a torus mesh.
  39177. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  39178. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  39179. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  39180. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  39181. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39182. * 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).
  39183. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39184. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39185. */
  39186. MeshBuilder.CreateTorus = function (name, options, scene) {
  39187. var torus = new BABYLON.Mesh(name, scene);
  39188. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39189. torus.sideOrientation = options.sideOrientation;
  39190. var vertexData = BABYLON.VertexData.CreateTorus(options);
  39191. vertexData.applyToMesh(torus, options.updatable);
  39192. return torus;
  39193. };
  39194. /**
  39195. * Creates a torus knot mesh.
  39196. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  39197. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  39198. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  39199. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  39200. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  39201. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39202. * 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).
  39203. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39204. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39205. */
  39206. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  39207. var torusKnot = new BABYLON.Mesh(name, scene);
  39208. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39209. torusKnot.sideOrientation = options.sideOrientation;
  39210. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  39211. vertexData.applyToMesh(torusKnot, options.updatable);
  39212. return torusKnot;
  39213. };
  39214. /**
  39215. * Creates a line system mesh.
  39216. * A line system is a pool of many lines gathered in a single mesh.
  39217. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  39218. * 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.
  39219. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  39220. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  39221. * 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
  39222. * 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
  39223. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  39224. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39225. */
  39226. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  39227. var instance = options.instance;
  39228. var lines = options.lines;
  39229. if (instance) {
  39230. var positionFunction = function (positions) {
  39231. var i = 0;
  39232. for (var l = 0; l < lines.length; l++) {
  39233. var points = lines[l];
  39234. for (var p = 0; p < points.length; p++) {
  39235. positions[i] = points[p].x;
  39236. positions[i + 1] = points[p].y;
  39237. positions[i + 2] = points[p].z;
  39238. i += 3;
  39239. }
  39240. }
  39241. };
  39242. instance.updateMeshPositions(positionFunction, false);
  39243. return instance;
  39244. }
  39245. // line system creation
  39246. var lineSystem = new BABYLON.LinesMesh(name, scene);
  39247. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  39248. vertexData.applyToMesh(lineSystem, options.updatable);
  39249. return lineSystem;
  39250. };
  39251. /**
  39252. * Creates a line mesh.
  39253. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  39254. * 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.
  39255. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39256. * The parameter `points` is an array successive Vector3.
  39257. * 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
  39258. * When updating an instance, remember that only point positions can change, not the number of points.
  39259. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39260. */
  39261. MeshBuilder.CreateLines = function (name, options, scene) {
  39262. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  39263. return lines;
  39264. };
  39265. /**
  39266. * Creates a dashed line mesh.
  39267. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  39268. * 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.
  39269. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39270. * The parameter `points` is an array successive Vector3.
  39271. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  39272. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  39273. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  39274. * 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
  39275. * When updating an instance, remember that only point positions can change, not the number of points.
  39276. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39277. */
  39278. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  39279. var points = options.points;
  39280. var instance = options.instance;
  39281. var gapSize = options.gapSize;
  39282. var dashNb = options.dashNb;
  39283. var dashSize = options.dashSize;
  39284. if (instance) {
  39285. var positionFunction = function (positions) {
  39286. var curvect = BABYLON.Vector3.Zero();
  39287. var nbSeg = positions.length / 6;
  39288. var lg = 0;
  39289. var nb = 0;
  39290. var shft = 0;
  39291. var dashshft = 0;
  39292. var curshft = 0;
  39293. var p = 0;
  39294. var i = 0;
  39295. var j = 0;
  39296. for (i = 0; i < points.length - 1; i++) {
  39297. points[i + 1].subtractToRef(points[i], curvect);
  39298. lg += curvect.length();
  39299. }
  39300. shft = lg / nbSeg;
  39301. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  39302. for (i = 0; i < points.length - 1; i++) {
  39303. points[i + 1].subtractToRef(points[i], curvect);
  39304. nb = Math.floor(curvect.length() / shft);
  39305. curvect.normalize();
  39306. j = 0;
  39307. while (j < nb && p < positions.length) {
  39308. curshft = shft * j;
  39309. positions[p] = points[i].x + curshft * curvect.x;
  39310. positions[p + 1] = points[i].y + curshft * curvect.y;
  39311. positions[p + 2] = points[i].z + curshft * curvect.z;
  39312. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  39313. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  39314. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  39315. p += 6;
  39316. j++;
  39317. }
  39318. }
  39319. while (p < positions.length) {
  39320. positions[p] = points[i].x;
  39321. positions[p + 1] = points[i].y;
  39322. positions[p + 2] = points[i].z;
  39323. p += 3;
  39324. }
  39325. };
  39326. instance.updateMeshPositions(positionFunction, false);
  39327. return instance;
  39328. }
  39329. // dashed lines creation
  39330. var dashedLines = new BABYLON.LinesMesh(name, scene);
  39331. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  39332. vertexData.applyToMesh(dashedLines, options.updatable);
  39333. dashedLines.dashSize = dashSize;
  39334. dashedLines.gapSize = gapSize;
  39335. return dashedLines;
  39336. };
  39337. /**
  39338. * Creates an extruded shape mesh.
  39339. * 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.
  39340. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  39341. *
  39342. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39343. * 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
  39344. * extruded along the Z axis.
  39345. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39346. * 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.
  39347. * The parameter `scale` (float, default 1) is the value to scale the shape.
  39348. * 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
  39349. * 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
  39350. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  39351. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39352. * 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).
  39353. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39354. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39355. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39356. */
  39357. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  39358. var path = options.path;
  39359. var shape = options.shape;
  39360. var scale = options.scale || 1;
  39361. var rotation = options.rotation || 0;
  39362. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39363. var updatable = options.updatable;
  39364. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39365. var instance = options.instance;
  39366. var invertUV = options.invertUV || false;
  39367. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  39368. };
  39369. /**
  39370. * Creates an custom extruded shape mesh.
  39371. * 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.
  39372. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  39373. *
  39374. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39375. * 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
  39376. * extruded along the Z axis.
  39377. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39378. * 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
  39379. * and the distance of this point from the begining of the path :
  39380. * ```javascript
  39381. * var rotationFunction = function(i, distance) {
  39382. * // do things
  39383. * return rotationValue; }
  39384. * ```
  39385. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  39386. * 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
  39387. * and the distance of this point from the begining of the path :
  39388. * ```javascript
  39389. * var scaleFunction = function(i, distance) {
  39390. * // do things
  39391. * return scaleValue;}
  39392. * ```
  39393. * It must returns a float value that will be the scale value applied to the shape on each path point.
  39394. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  39395. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  39396. * 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
  39397. * 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
  39398. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  39399. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39400. * 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).
  39401. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39402. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39404. */
  39405. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  39406. var path = options.path;
  39407. var shape = options.shape;
  39408. var scaleFunction = options.scaleFunction || (function () { return 1; });
  39409. var rotationFunction = options.rotationFunction || (function () { return 0; });
  39410. var ribbonCloseArray = options.ribbonCloseArray || false;
  39411. var ribbonClosePath = options.ribbonClosePath || false;
  39412. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39413. var updatable = options.updatable;
  39414. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39415. var instance = options.instance;
  39416. var invertUV = options.invertUV || false;
  39417. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  39418. };
  39419. /**
  39420. * Creates lathe mesh.
  39421. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  39422. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  39423. *
  39424. * 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
  39425. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  39426. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  39427. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  39428. * 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.
  39429. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  39430. * 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
  39431. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39432. * 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).
  39433. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39434. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39435. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39436. */
  39437. MeshBuilder.CreateLathe = function (name, options, scene) {
  39438. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  39439. var closed = (options.closed === undefined) ? true : options.closed;
  39440. var shape = options.shape;
  39441. var radius = options.radius || 1;
  39442. var tessellation = options.tessellation || 64;
  39443. var updatable = options.updatable;
  39444. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39445. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  39446. var pi2 = Math.PI * 2;
  39447. var paths = new Array();
  39448. var invertUV = options.invertUV || false;
  39449. var i = 0;
  39450. var p = 0;
  39451. var step = pi2 / tessellation * arc;
  39452. var rotated;
  39453. var path = new Array();
  39454. ;
  39455. for (i = 0; i <= tessellation; i++) {
  39456. var path = [];
  39457. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  39458. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  39459. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  39460. }
  39461. for (p = 0; p < shape.length; p++) {
  39462. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  39463. path.push(rotated);
  39464. }
  39465. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  39466. 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));
  39467. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  39468. }
  39469. paths.push(path);
  39470. }
  39471. // lathe ribbon
  39472. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  39473. return lathe;
  39474. };
  39475. /**
  39476. * Creates a plane mesh.
  39477. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  39478. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  39479. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  39480. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  39481. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39482. * 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).
  39483. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39484. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39485. */
  39486. MeshBuilder.CreatePlane = function (name, options, scene) {
  39487. var plane = new BABYLON.Mesh(name, scene);
  39488. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39489. plane.sideOrientation = options.sideOrientation;
  39490. var vertexData = BABYLON.VertexData.CreatePlane(options);
  39491. vertexData.applyToMesh(plane, options.updatable);
  39492. if (options.sourcePlane) {
  39493. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  39494. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  39495. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  39496. plane.rotate(vectorProduct, product);
  39497. }
  39498. return plane;
  39499. };
  39500. /**
  39501. * Creates a ground mesh.
  39502. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  39503. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  39504. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  39505. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39506. */
  39507. MeshBuilder.CreateGround = function (name, options, scene) {
  39508. var ground = new BABYLON.GroundMesh(name, scene);
  39509. ground._setReady(false);
  39510. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39511. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39512. ground._width = options.width || 1;
  39513. ground._height = options.height || 1;
  39514. ground._maxX = ground._width / 2;
  39515. ground._maxZ = ground._height / 2;
  39516. ground._minX = -ground._maxX;
  39517. ground._minZ = -ground._maxZ;
  39518. var vertexData = BABYLON.VertexData.CreateGround(options);
  39519. vertexData.applyToMesh(ground, options.updatable);
  39520. ground._setReady(true);
  39521. return ground;
  39522. };
  39523. /**
  39524. * Creates a tiled ground mesh.
  39525. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  39526. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  39527. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  39528. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  39529. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  39530. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  39531. * numbers of subdivisions on the ground width and height of each tile.
  39532. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39533. */
  39534. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  39535. var tiledGround = new BABYLON.Mesh(name, scene);
  39536. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  39537. vertexData.applyToMesh(tiledGround, options.updatable);
  39538. return tiledGround;
  39539. };
  39540. /**
  39541. * Creates a ground mesh from a height map.
  39542. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  39543. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  39544. * The parameter `url` sets the URL of the height map image resource.
  39545. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  39546. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  39547. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  39548. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  39549. * 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.
  39550. * 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).
  39551. * This function is passed the newly built mesh :
  39552. * ```javascript
  39553. * function(mesh) { // do things
  39554. * return; }
  39555. * ```
  39556. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39557. */
  39558. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  39559. var width = options.width || 10.0;
  39560. var height = options.height || 10.0;
  39561. var subdivisions = options.subdivisions || 1 | 0;
  39562. var minHeight = options.minHeight || 0.0;
  39563. var maxHeight = options.maxHeight || 10.0;
  39564. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39565. var updatable = options.updatable;
  39566. var onReady = options.onReady;
  39567. var ground = new BABYLON.GroundMesh(name, scene);
  39568. ground._subdivisionsX = subdivisions;
  39569. ground._subdivisionsY = subdivisions;
  39570. ground._width = width;
  39571. ground._height = height;
  39572. ground._maxX = ground._width / 2.0;
  39573. ground._maxZ = ground._height / 2.0;
  39574. ground._minX = -ground._maxX;
  39575. ground._minZ = -ground._maxZ;
  39576. ground._setReady(false);
  39577. var onload = function (img) {
  39578. // Getting height map data
  39579. var canvas = document.createElement("canvas");
  39580. var context = canvas.getContext("2d");
  39581. var bufferWidth = img.width;
  39582. var bufferHeight = img.height;
  39583. canvas.width = bufferWidth;
  39584. canvas.height = bufferHeight;
  39585. context.drawImage(img, 0, 0);
  39586. // Create VertexData from map data
  39587. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  39588. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  39589. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  39590. width: width, height: height,
  39591. subdivisions: subdivisions,
  39592. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  39593. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  39594. });
  39595. vertexData.applyToMesh(ground, updatable);
  39596. ground._setReady(true);
  39597. //execute ready callback, if set
  39598. if (onReady) {
  39599. onReady(ground);
  39600. }
  39601. };
  39602. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  39603. return ground;
  39604. };
  39605. /**
  39606. * Creates a polygon mesh.
  39607. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  39608. * 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.
  39609. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39610. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39611. * 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).
  39612. * Remember you can only change the shape positions, not their number when updating a polygon.
  39613. */
  39614. MeshBuilder.CreatePolygon = function (name, options, scene) {
  39615. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39616. var shape = options.shape;
  39617. var holes = options.holes || [];
  39618. var depth = options.depth || 0;
  39619. var contours = [];
  39620. var hole = [];
  39621. for (var i = 0; i < shape.length; i++) {
  39622. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  39623. }
  39624. var epsilon = 0.00000001;
  39625. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  39626. contours.pop();
  39627. }
  39628. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  39629. for (var hNb = 0; hNb < holes.length; hNb++) {
  39630. hole = [];
  39631. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  39632. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  39633. }
  39634. polygonTriangulation.addHole(hole);
  39635. }
  39636. var polygon = polygonTriangulation.build(options.updatable, depth);
  39637. polygon.sideOrientation = options.sideOrientation;
  39638. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  39639. vertexData.applyToMesh(polygon, options.updatable);
  39640. return polygon;
  39641. };
  39642. ;
  39643. /**
  39644. * Creates an extruded polygon mesh, with depth in the Y direction.
  39645. * 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).
  39646. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  39647. */
  39648. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  39649. return MeshBuilder.CreatePolygon(name, options, scene);
  39650. };
  39651. ;
  39652. /**
  39653. * Creates a tube mesh.
  39654. * 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.
  39655. *
  39656. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  39657. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  39658. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  39659. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  39660. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  39661. * 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.
  39662. * It must return a radius value (positive float) :
  39663. * ```javascript
  39664. * var radiusFunction = function(i, distance) {
  39665. * // do things
  39666. * return radius; }
  39667. * ```
  39668. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  39669. * 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
  39670. * 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
  39671. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39672. * 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).
  39673. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39674. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39675. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39676. */
  39677. MeshBuilder.CreateTube = function (name, options, scene) {
  39678. var path = options.path;
  39679. var radius = options.radius || 1.0;
  39680. var tessellation = options.tessellation || 64 | 0;
  39681. var radiusFunction = options.radiusFunction;
  39682. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  39683. var invertUV = options.invertUV || false;
  39684. var updatable = options.updatable;
  39685. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39686. var instance = options.instance;
  39687. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  39688. // tube geometry
  39689. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  39690. var tangents = path3D.getTangents();
  39691. var normals = path3D.getNormals();
  39692. var distances = path3D.getDistances();
  39693. var pi2 = Math.PI * 2;
  39694. var step = pi2 / tessellation * arc;
  39695. var returnRadius = function () { return radius; };
  39696. var radiusFunctionFinal = radiusFunction || returnRadius;
  39697. var circlePath;
  39698. var rad;
  39699. var normal;
  39700. var rotated;
  39701. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  39702. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  39703. for (var i = 0; i < path.length; i++) {
  39704. rad = radiusFunctionFinal(i, distances[i]); // current radius
  39705. circlePath = Array(); // current circle array
  39706. normal = normals[i]; // current normal
  39707. for (var t = 0; t < tessellation; t++) {
  39708. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  39709. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  39710. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  39711. rotated.scaleInPlace(rad).addInPlace(path[i]);
  39712. circlePath[t] = rotated;
  39713. }
  39714. circlePaths[index] = circlePath;
  39715. index++;
  39716. }
  39717. // cap
  39718. var capPath = function (nbPoints, pathIndex) {
  39719. var pointCap = Array();
  39720. for (var i = 0; i < nbPoints; i++) {
  39721. pointCap.push(path[pathIndex]);
  39722. }
  39723. return pointCap;
  39724. };
  39725. switch (cap) {
  39726. case BABYLON.Mesh.NO_CAP:
  39727. break;
  39728. case BABYLON.Mesh.CAP_START:
  39729. circlePaths[0] = capPath(tessellation, 0);
  39730. circlePaths[1] = circlePaths[2].slice(0);
  39731. break;
  39732. case BABYLON.Mesh.CAP_END:
  39733. circlePaths[index] = circlePaths[index - 1].slice(0);
  39734. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  39735. break;
  39736. case BABYLON.Mesh.CAP_ALL:
  39737. circlePaths[0] = capPath(tessellation, 0);
  39738. circlePaths[1] = circlePaths[2].slice(0);
  39739. circlePaths[index] = circlePaths[index - 1].slice(0);
  39740. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  39741. break;
  39742. default:
  39743. break;
  39744. }
  39745. return circlePaths;
  39746. };
  39747. var path3D;
  39748. var pathArray;
  39749. if (instance) {
  39750. var arc = options.arc || instance.arc;
  39751. path3D = (instance.path3D).update(path);
  39752. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  39753. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  39754. instance.path3D = path3D;
  39755. instance.pathArray = pathArray;
  39756. instance.arc = arc;
  39757. return instance;
  39758. }
  39759. // tube creation
  39760. path3D = new BABYLON.Path3D(path);
  39761. var newPathArray = new Array();
  39762. cap = (cap < 0 || cap > 3) ? 0 : cap;
  39763. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  39764. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  39765. tube.pathArray = pathArray;
  39766. tube.path3D = path3D;
  39767. tube.tessellation = tessellation;
  39768. tube.cap = cap;
  39769. tube.arc = options.arc;
  39770. return tube;
  39771. };
  39772. /**
  39773. * Creates a polyhedron mesh.
  39774. *
  39775. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  39776. * 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
  39777. * to choose the wanted type.
  39778. * The parameter `size` (positive float, default 1) sets the polygon size.
  39779. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  39780. * 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`.
  39781. * 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
  39782. * 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)`).
  39783. * 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
  39784. * 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.
  39785. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39786. * 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).
  39787. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39789. */
  39790. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  39791. var polyhedron = new BABYLON.Mesh(name, scene);
  39792. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39793. polyhedron.sideOrientation = options.sideOrientation;
  39794. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  39795. vertexData.applyToMesh(polyhedron, options.updatable);
  39796. return polyhedron;
  39797. };
  39798. /**
  39799. * Creates a decal mesh.
  39800. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  39801. * 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.
  39802. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  39803. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  39804. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  39805. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  39806. */
  39807. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  39808. var indices = sourceMesh.getIndices();
  39809. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39810. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39811. var position = options.position || BABYLON.Vector3.Zero();
  39812. var normal = options.normal || BABYLON.Vector3.Up();
  39813. var size = options.size || BABYLON.Vector3.One();
  39814. var angle = options.angle || 0;
  39815. // Getting correct rotation
  39816. if (!normal) {
  39817. var target = new BABYLON.Vector3(0, 0, 1);
  39818. var camera = sourceMesh.getScene().activeCamera;
  39819. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  39820. normal = camera.globalPosition.subtract(cameraWorldTarget);
  39821. }
  39822. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  39823. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  39824. var pitch = Math.atan2(normal.y, len);
  39825. // Matrix
  39826. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  39827. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  39828. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  39829. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  39830. var vertexData = new BABYLON.VertexData();
  39831. vertexData.indices = [];
  39832. vertexData.positions = [];
  39833. vertexData.normals = [];
  39834. vertexData.uvs = [];
  39835. var currentVertexDataIndex = 0;
  39836. var extractDecalVector3 = function (indexId) {
  39837. var vertexId = indices[indexId];
  39838. var result = new BABYLON.PositionNormalVertex();
  39839. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  39840. // Send vector to decal local world
  39841. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  39842. // Get normal
  39843. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  39844. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  39845. return result;
  39846. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  39847. var clip = function (vertices, axis) {
  39848. if (vertices.length === 0) {
  39849. return vertices;
  39850. }
  39851. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  39852. var clipVertices = function (v0, v1) {
  39853. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  39854. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  39855. };
  39856. var result = new Array();
  39857. for (var index = 0; index < vertices.length; index += 3) {
  39858. var v1Out;
  39859. var v2Out;
  39860. var v3Out;
  39861. var total = 0;
  39862. var nV1, nV2, nV3, nV4;
  39863. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  39864. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  39865. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  39866. v1Out = d1 > 0;
  39867. v2Out = d2 > 0;
  39868. v3Out = d3 > 0;
  39869. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  39870. switch (total) {
  39871. case 0:
  39872. result.push(vertices[index]);
  39873. result.push(vertices[index + 1]);
  39874. result.push(vertices[index + 2]);
  39875. break;
  39876. case 1:
  39877. if (v1Out) {
  39878. nV1 = vertices[index + 1];
  39879. nV2 = vertices[index + 2];
  39880. nV3 = clipVertices(vertices[index], nV1);
  39881. nV4 = clipVertices(vertices[index], nV2);
  39882. }
  39883. if (v2Out) {
  39884. nV1 = vertices[index];
  39885. nV2 = vertices[index + 2];
  39886. nV3 = clipVertices(vertices[index + 1], nV1);
  39887. nV4 = clipVertices(vertices[index + 1], nV2);
  39888. result.push(nV3);
  39889. result.push(nV2.clone());
  39890. result.push(nV1.clone());
  39891. result.push(nV2.clone());
  39892. result.push(nV3.clone());
  39893. result.push(nV4);
  39894. break;
  39895. }
  39896. if (v3Out) {
  39897. nV1 = vertices[index];
  39898. nV2 = vertices[index + 1];
  39899. nV3 = clipVertices(vertices[index + 2], nV1);
  39900. nV4 = clipVertices(vertices[index + 2], nV2);
  39901. }
  39902. result.push(nV1.clone());
  39903. result.push(nV2.clone());
  39904. result.push(nV3);
  39905. result.push(nV4);
  39906. result.push(nV3.clone());
  39907. result.push(nV2.clone());
  39908. break;
  39909. case 2:
  39910. if (!v1Out) {
  39911. nV1 = vertices[index].clone();
  39912. nV2 = clipVertices(nV1, vertices[index + 1]);
  39913. nV3 = clipVertices(nV1, vertices[index + 2]);
  39914. result.push(nV1);
  39915. result.push(nV2);
  39916. result.push(nV3);
  39917. }
  39918. if (!v2Out) {
  39919. nV1 = vertices[index + 1].clone();
  39920. nV2 = clipVertices(nV1, vertices[index + 2]);
  39921. nV3 = clipVertices(nV1, vertices[index]);
  39922. result.push(nV1);
  39923. result.push(nV2);
  39924. result.push(nV3);
  39925. }
  39926. if (!v3Out) {
  39927. nV1 = vertices[index + 2].clone();
  39928. nV2 = clipVertices(nV1, vertices[index]);
  39929. nV3 = clipVertices(nV1, vertices[index + 1]);
  39930. result.push(nV1);
  39931. result.push(nV2);
  39932. result.push(nV3);
  39933. }
  39934. break;
  39935. case 3:
  39936. break;
  39937. }
  39938. }
  39939. return result;
  39940. };
  39941. for (var index = 0; index < indices.length; index += 3) {
  39942. var faceVertices = new Array();
  39943. faceVertices.push(extractDecalVector3(index));
  39944. faceVertices.push(extractDecalVector3(index + 1));
  39945. faceVertices.push(extractDecalVector3(index + 2));
  39946. // Clip
  39947. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  39948. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  39949. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  39950. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  39951. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  39952. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  39953. if (faceVertices.length === 0) {
  39954. continue;
  39955. }
  39956. // Add UVs and get back to world
  39957. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  39958. var vertex = faceVertices[vIndex];
  39959. //TODO check for Int32Array | Uint32Array | Uint16Array
  39960. vertexData.indices.push(currentVertexDataIndex);
  39961. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  39962. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  39963. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  39964. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  39965. currentVertexDataIndex++;
  39966. }
  39967. }
  39968. // Return mesh
  39969. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  39970. vertexData.applyToMesh(decal);
  39971. decal.position = position.clone();
  39972. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  39973. return decal;
  39974. };
  39975. // Privates
  39976. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  39977. // extrusion geometry
  39978. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  39979. var tangents = path3D.getTangents();
  39980. var normals = path3D.getNormals();
  39981. var binormals = path3D.getBinormals();
  39982. var distances = path3D.getDistances();
  39983. var angle = 0;
  39984. var returnScale = function () { return scale; };
  39985. var returnRotation = function () { return rotation; };
  39986. var rotate = custom ? rotateFunction : returnRotation;
  39987. var scl = custom ? scaleFunction : returnScale;
  39988. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  39989. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  39990. for (var i = 0; i < curve.length; i++) {
  39991. var shapePath = new Array();
  39992. var angleStep = rotate(i, distances[i]);
  39993. var scaleRatio = scl(i, distances[i]);
  39994. for (var p = 0; p < shape.length; p++) {
  39995. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  39996. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  39997. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  39998. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  39999. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  40000. shapePath[p] = rotated;
  40001. }
  40002. shapePaths[index] = shapePath;
  40003. angle += angleStep;
  40004. index++;
  40005. }
  40006. // cap
  40007. var capPath = function (shapePath) {
  40008. var pointCap = Array();
  40009. var barycenter = BABYLON.Vector3.Zero();
  40010. var i;
  40011. for (i = 0; i < shapePath.length; i++) {
  40012. barycenter.addInPlace(shapePath[i]);
  40013. }
  40014. barycenter.scaleInPlace(1.0 / shapePath.length);
  40015. for (i = 0; i < shapePath.length; i++) {
  40016. pointCap.push(barycenter);
  40017. }
  40018. return pointCap;
  40019. };
  40020. switch (cap) {
  40021. case BABYLON.Mesh.NO_CAP:
  40022. break;
  40023. case BABYLON.Mesh.CAP_START:
  40024. shapePaths[0] = capPath(shapePaths[2]);
  40025. shapePaths[1] = shapePaths[2];
  40026. break;
  40027. case BABYLON.Mesh.CAP_END:
  40028. shapePaths[index] = shapePaths[index - 1];
  40029. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40030. break;
  40031. case BABYLON.Mesh.CAP_ALL:
  40032. shapePaths[0] = capPath(shapePaths[2]);
  40033. shapePaths[1] = shapePaths[2];
  40034. shapePaths[index] = shapePaths[index - 1];
  40035. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40036. break;
  40037. default:
  40038. break;
  40039. }
  40040. return shapePaths;
  40041. };
  40042. var path3D;
  40043. var pathArray;
  40044. if (instance) {
  40045. path3D = (instance.path3D).update(curve);
  40046. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  40047. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  40048. return instance;
  40049. }
  40050. // extruded shape creation
  40051. path3D = new BABYLON.Path3D(curve);
  40052. var newShapePaths = new Array();
  40053. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40054. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  40055. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  40056. extrudedGeneric.pathArray = pathArray;
  40057. extrudedGeneric.path3D = path3D;
  40058. extrudedGeneric.cap = cap;
  40059. return extrudedGeneric;
  40060. };
  40061. return MeshBuilder;
  40062. }());
  40063. BABYLON.MeshBuilder = MeshBuilder;
  40064. })(BABYLON || (BABYLON = {}));
  40065. //# sourceMappingURL=babylon.meshBuilder.js.map
  40066. var BABYLON;
  40067. (function (BABYLON) {
  40068. var Layer = (function () {
  40069. function Layer(name, imgUrl, scene, isBackground, color) {
  40070. this.name = name;
  40071. this.scale = new BABYLON.Vector2(1, 1);
  40072. this.offset = new BABYLON.Vector2(0, 0);
  40073. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  40074. this.layerMask = 0x0FFFFFFF;
  40075. this._vertexBuffers = {};
  40076. // Events
  40077. /**
  40078. * An event triggered when the layer is disposed.
  40079. * @type {BABYLON.Observable}
  40080. */
  40081. this.onDisposeObservable = new BABYLON.Observable();
  40082. /**
  40083. * An event triggered before rendering the scene
  40084. * @type {BABYLON.Observable}
  40085. */
  40086. this.onBeforeRenderObservable = new BABYLON.Observable();
  40087. /**
  40088. * An event triggered after rendering the scene
  40089. * @type {BABYLON.Observable}
  40090. */
  40091. this.onAfterRenderObservable = new BABYLON.Observable();
  40092. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  40093. this.isBackground = isBackground === undefined ? true : isBackground;
  40094. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  40095. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40096. this._scene.layers.push(this);
  40097. var engine = this._scene.getEngine();
  40098. // VBO
  40099. var vertices = [];
  40100. vertices.push(1, 1);
  40101. vertices.push(-1, 1);
  40102. vertices.push(-1, -1);
  40103. vertices.push(1, -1);
  40104. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40105. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  40106. // Indices
  40107. var indices = [];
  40108. indices.push(0);
  40109. indices.push(1);
  40110. indices.push(2);
  40111. indices.push(0);
  40112. indices.push(2);
  40113. indices.push(3);
  40114. this._indexBuffer = engine.createIndexBuffer(indices);
  40115. // Effects
  40116. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  40117. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  40118. }
  40119. Object.defineProperty(Layer.prototype, "onDispose", {
  40120. set: function (callback) {
  40121. if (this._onDisposeObserver) {
  40122. this.onDisposeObservable.remove(this._onDisposeObserver);
  40123. }
  40124. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  40125. },
  40126. enumerable: true,
  40127. configurable: true
  40128. });
  40129. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  40130. set: function (callback) {
  40131. if (this._onBeforeRenderObserver) {
  40132. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40133. }
  40134. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40135. },
  40136. enumerable: true,
  40137. configurable: true
  40138. });
  40139. Object.defineProperty(Layer.prototype, "onAfterRender", {
  40140. set: function (callback) {
  40141. if (this._onAfterRenderObserver) {
  40142. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40143. }
  40144. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40145. },
  40146. enumerable: true,
  40147. configurable: true
  40148. });
  40149. Layer.prototype.render = function () {
  40150. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  40151. // Check
  40152. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  40153. return;
  40154. var engine = this._scene.getEngine();
  40155. this.onBeforeRenderObservable.notifyObservers(this);
  40156. // Render
  40157. engine.enableEffect(currentEffect);
  40158. engine.setState(false);
  40159. // Texture
  40160. currentEffect.setTexture("textureSampler", this.texture);
  40161. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  40162. // Color
  40163. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  40164. // Scale / offset
  40165. currentEffect.setVector2("offset", this.offset);
  40166. currentEffect.setVector2("scale", this.scale);
  40167. // VBOs
  40168. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  40169. // Draw order
  40170. if (!this.alphaTest) {
  40171. engine.setAlphaMode(this.alphaBlendingMode);
  40172. engine.draw(true, 0, 6);
  40173. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40174. }
  40175. else {
  40176. engine.draw(true, 0, 6);
  40177. }
  40178. this.onAfterRenderObservable.notifyObservers(this);
  40179. };
  40180. Layer.prototype.dispose = function () {
  40181. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40182. if (vertexBuffer) {
  40183. vertexBuffer.dispose();
  40184. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40185. }
  40186. if (this._indexBuffer) {
  40187. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40188. this._indexBuffer = null;
  40189. }
  40190. if (this.texture) {
  40191. this.texture.dispose();
  40192. this.texture = null;
  40193. }
  40194. // Remove from scene
  40195. var index = this._scene.layers.indexOf(this);
  40196. this._scene.layers.splice(index, 1);
  40197. // Callback
  40198. this.onDisposeObservable.notifyObservers(this);
  40199. this.onDisposeObservable.clear();
  40200. this.onAfterRenderObservable.clear();
  40201. this.onBeforeRenderObservable.clear();
  40202. };
  40203. return Layer;
  40204. }());
  40205. BABYLON.Layer = Layer;
  40206. })(BABYLON || (BABYLON = {}));
  40207. //# sourceMappingURL=babylon.layer.js.map
  40208. var BABYLON;
  40209. (function (BABYLON) {
  40210. var BlurPostProcess = (function (_super) {
  40211. __extends(BlurPostProcess, _super);
  40212. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  40213. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40214. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40215. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  40216. _this.direction = direction;
  40217. _this._packedFloat = false;
  40218. _this.onApplyObservable.add(function (effect) {
  40219. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  40220. });
  40221. _this.kernel = kernel;
  40222. return _this;
  40223. }
  40224. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  40225. /**
  40226. * Gets the length in pixels of the blur sample region
  40227. */
  40228. get: function () {
  40229. return this._idealKernel;
  40230. },
  40231. /**
  40232. * Sets the length in pixels of the blur sample region
  40233. */
  40234. set: function (v) {
  40235. if (this._idealKernel === v) {
  40236. return;
  40237. }
  40238. v = Math.max(v, 1);
  40239. this._idealKernel = v;
  40240. this._kernel = this._nearestBestKernel(v);
  40241. this._updateParameters();
  40242. },
  40243. enumerable: true,
  40244. configurable: true
  40245. });
  40246. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  40247. /**
  40248. * Gets wether or not the blur is unpacking/repacking floats
  40249. */
  40250. get: function () {
  40251. return this._packedFloat;
  40252. },
  40253. /**
  40254. * Sets wether or not the blur needs to unpack/repack floats
  40255. */
  40256. set: function (v) {
  40257. if (this._packedFloat === v) {
  40258. return;
  40259. }
  40260. this._packedFloat = v;
  40261. this._updateParameters();
  40262. },
  40263. enumerable: true,
  40264. configurable: true
  40265. });
  40266. BlurPostProcess.prototype._updateParameters = function () {
  40267. // Generate sampling offsets and weights
  40268. var N = this._kernel;
  40269. var centerIndex = (N - 1) / 2;
  40270. // Generate Gaussian sampling weights over kernel
  40271. var offsets = [];
  40272. var weights = [];
  40273. var totalWeight = 0;
  40274. for (var i = 0; i < N; i++) {
  40275. var u = i / (N - 1);
  40276. var w = this._gaussianWeight(u * 2.0 - 1);
  40277. offsets[i] = (i - centerIndex);
  40278. weights[i] = w;
  40279. totalWeight += w;
  40280. }
  40281. // Normalize weights
  40282. for (var i = 0; i < weights.length; i++) {
  40283. weights[i] /= totalWeight;
  40284. }
  40285. // Optimize: combine samples to take advantage of hardware linear sampling
  40286. // Walk from left to center, combining pairs (symmetrically)
  40287. var linearSamplingWeights = [];
  40288. var linearSamplingOffsets = [];
  40289. var linearSamplingMap = [];
  40290. for (var i = 0; i <= centerIndex; i += 2) {
  40291. var j = Math.min(i + 1, Math.floor(centerIndex));
  40292. var singleCenterSample = i === j;
  40293. if (singleCenterSample) {
  40294. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  40295. }
  40296. else {
  40297. var sharedCell = j === centerIndex;
  40298. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  40299. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  40300. if (offsetLinear === 0) {
  40301. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  40302. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  40303. }
  40304. else {
  40305. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  40306. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  40307. }
  40308. }
  40309. }
  40310. for (var i = 0; i < linearSamplingMap.length; i++) {
  40311. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  40312. linearSamplingWeights[i] = linearSamplingMap[i].w;
  40313. }
  40314. // Replace with optimized
  40315. offsets = linearSamplingOffsets;
  40316. weights = linearSamplingWeights;
  40317. // Generate shaders
  40318. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  40319. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  40320. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  40321. var defines = "";
  40322. for (var i = 0; i < varyingCount; i++) {
  40323. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  40324. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  40325. }
  40326. var depCount = 0;
  40327. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  40328. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  40329. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  40330. depCount++;
  40331. }
  40332. if (this.packedFloat) {
  40333. defines += "#define PACKEDFLOAT 1";
  40334. }
  40335. this.updateEffect(defines, null, null, {
  40336. varyingCount: varyingCount,
  40337. depCount: depCount
  40338. });
  40339. };
  40340. /**
  40341. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  40342. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  40343. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  40344. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  40345. * The gaps between physical kernels are compensated for in the weighting of the samples
  40346. * @param idealKernel Ideal blur kernel.
  40347. * @return Nearest best kernel.
  40348. */
  40349. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  40350. var v = Math.round(idealKernel);
  40351. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  40352. var k = _a[_i];
  40353. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  40354. return Math.max(k, 3);
  40355. }
  40356. }
  40357. return Math.max(v, 3);
  40358. };
  40359. /**
  40360. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  40361. * @param x The point on the Gaussian distribution to sample.
  40362. * @return the value of the Gaussian function at x.
  40363. */
  40364. BlurPostProcess.prototype._gaussianWeight = function (x) {
  40365. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  40366. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  40367. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  40368. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  40369. // truncated at around 1.3% of peak strength.
  40370. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  40371. var sigma = (1 / 3);
  40372. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  40373. var exponent = -((x * x) / (2.0 * sigma * sigma));
  40374. var weight = (1.0 / denominator) * Math.exp(exponent);
  40375. return weight;
  40376. };
  40377. /**
  40378. * Generates a string that can be used as a floating point number in GLSL.
  40379. * @param x Value to print.
  40380. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  40381. * @return GLSL float string.
  40382. */
  40383. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  40384. if (decimalFigures === void 0) { decimalFigures = 8; }
  40385. return x.toFixed(decimalFigures).replace(/0+$/, '');
  40386. };
  40387. return BlurPostProcess;
  40388. }(BABYLON.PostProcess));
  40389. BABYLON.BlurPostProcess = BlurPostProcess;
  40390. })(BABYLON || (BABYLON = {}));
  40391. //# sourceMappingURL=babylon.blurPostProcess.js.map
  40392. var BABYLON;
  40393. (function (BABYLON) {
  40394. var FxaaPostProcess = (function (_super) {
  40395. __extends(FxaaPostProcess, _super);
  40396. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  40397. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40398. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  40399. _this.onApplyObservable.add(function (effect) {
  40400. var texelSize = _this.texelSize;
  40401. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  40402. });
  40403. return _this;
  40404. }
  40405. return FxaaPostProcess;
  40406. }(BABYLON.PostProcess));
  40407. BABYLON.FxaaPostProcess = FxaaPostProcess;
  40408. })(BABYLON || (BABYLON = {}));
  40409. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  40410. var BABYLON;
  40411. (function (BABYLON) {
  40412. var HighlightsPostProcess = (function (_super) {
  40413. __extends(HighlightsPostProcess, _super);
  40414. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  40415. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40416. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  40417. }
  40418. return HighlightsPostProcess;
  40419. }(BABYLON.PostProcess));
  40420. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  40421. })(BABYLON || (BABYLON = {}));
  40422. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  40423. var BABYLON;
  40424. (function (BABYLON) {
  40425. var ImageProcessingPostProcess = (function (_super) {
  40426. __extends(ImageProcessingPostProcess, _super);
  40427. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  40428. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40429. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  40430. _this._fromLinearSpace = true;
  40431. /**
  40432. * Defines cache preventing GC.
  40433. */
  40434. _this._defines = {
  40435. IMAGEPROCESSING: false,
  40436. VIGNETTE: false,
  40437. VIGNETTEBLENDMODEMULTIPLY: false,
  40438. VIGNETTEBLENDMODEOPAQUE: false,
  40439. TONEMAPPING: false,
  40440. CONTRAST: false,
  40441. COLORCURVES: false,
  40442. COLORGRADING: false,
  40443. FROMLINEARSPACE: false,
  40444. SAMPLER3DGREENDEPTH: false,
  40445. SAMPLER3DBGRMAP: false,
  40446. IMAGEPROCESSINGPOSTPROCESS: false,
  40447. EXPOSURE: false,
  40448. };
  40449. // Setup the default processing configuration to the scene.
  40450. _this._attachImageProcessingConfiguration(null, true);
  40451. _this.imageProcessingConfiguration.applyByPostProcess = true;
  40452. _this.onApply = function (effect) {
  40453. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  40454. };
  40455. return _this;
  40456. }
  40457. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  40458. /**
  40459. * Gets the image processing configuration used either in this material.
  40460. */
  40461. get: function () {
  40462. return this._imageProcessingConfiguration;
  40463. },
  40464. /**
  40465. * Sets the Default image processing configuration used either in the this material.
  40466. *
  40467. * If sets to null, the scene one is in use.
  40468. */
  40469. set: function (value) {
  40470. this._attachImageProcessingConfiguration(value);
  40471. },
  40472. enumerable: true,
  40473. configurable: true
  40474. });
  40475. /**
  40476. * Attaches a new image processing configuration to the PBR Material.
  40477. * @param configuration
  40478. */
  40479. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  40480. var _this = this;
  40481. if (doNotBuild === void 0) { doNotBuild = false; }
  40482. if (configuration === this._imageProcessingConfiguration) {
  40483. return;
  40484. }
  40485. // Detaches observer.
  40486. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40487. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40488. }
  40489. // Pick the scene configuration if needed.
  40490. if (!configuration) {
  40491. var camera = this.getCamera();
  40492. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  40493. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  40494. }
  40495. else {
  40496. this._imageProcessingConfiguration = configuration;
  40497. }
  40498. // Attaches observer.
  40499. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40500. _this._updateParameters();
  40501. });
  40502. // Ensure the effect will be rebuilt.
  40503. if (!doNotBuild) {
  40504. this._updateParameters();
  40505. }
  40506. };
  40507. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  40508. /**
  40509. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  40510. */
  40511. get: function () {
  40512. return this.imageProcessingConfiguration.colorCurves;
  40513. },
  40514. /**
  40515. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  40516. */
  40517. set: function (value) {
  40518. this.imageProcessingConfiguration.colorCurves = value;
  40519. },
  40520. enumerable: true,
  40521. configurable: true
  40522. });
  40523. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  40524. /**
  40525. * Gets wether the color curves effect is enabled.
  40526. */
  40527. get: function () {
  40528. return this.imageProcessingConfiguration.colorCurvesEnabled;
  40529. },
  40530. /**
  40531. * Sets wether the color curves effect is enabled.
  40532. */
  40533. set: function (value) {
  40534. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  40535. },
  40536. enumerable: true,
  40537. configurable: true
  40538. });
  40539. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  40540. /**
  40541. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  40542. */
  40543. get: function () {
  40544. return this.imageProcessingConfiguration.colorGradingTexture;
  40545. },
  40546. /**
  40547. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  40548. */
  40549. set: function (value) {
  40550. this.imageProcessingConfiguration.colorGradingTexture = value;
  40551. },
  40552. enumerable: true,
  40553. configurable: true
  40554. });
  40555. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  40556. /**
  40557. * Gets wether the color grading effect is enabled.
  40558. */
  40559. get: function () {
  40560. return this.imageProcessingConfiguration.colorGradingEnabled;
  40561. },
  40562. /**
  40563. * Gets wether the color grading effect is enabled.
  40564. */
  40565. set: function (value) {
  40566. this.imageProcessingConfiguration.colorGradingEnabled = value;
  40567. },
  40568. enumerable: true,
  40569. configurable: true
  40570. });
  40571. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  40572. /**
  40573. * Gets exposure used in the effect.
  40574. */
  40575. get: function () {
  40576. return this.imageProcessingConfiguration.exposure;
  40577. },
  40578. /**
  40579. * Sets exposure used in the effect.
  40580. */
  40581. set: function (value) {
  40582. this.imageProcessingConfiguration.exposure = value;
  40583. },
  40584. enumerable: true,
  40585. configurable: true
  40586. });
  40587. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  40588. /**
  40589. * Gets wether tonemapping is enabled or not.
  40590. */
  40591. get: function () {
  40592. return this._imageProcessingConfiguration.toneMappingEnabled;
  40593. },
  40594. /**
  40595. * Sets wether tonemapping is enabled or not
  40596. */
  40597. set: function (value) {
  40598. this._imageProcessingConfiguration.toneMappingEnabled = value;
  40599. },
  40600. enumerable: true,
  40601. configurable: true
  40602. });
  40603. ;
  40604. ;
  40605. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  40606. /**
  40607. * Gets contrast used in the effect.
  40608. */
  40609. get: function () {
  40610. return this.imageProcessingConfiguration.contrast;
  40611. },
  40612. /**
  40613. * Sets contrast used in the effect.
  40614. */
  40615. set: function (value) {
  40616. this.imageProcessingConfiguration.contrast = value;
  40617. },
  40618. enumerable: true,
  40619. configurable: true
  40620. });
  40621. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  40622. /**
  40623. * Gets Vignette stretch size.
  40624. */
  40625. get: function () {
  40626. return this.imageProcessingConfiguration.vignetteStretch;
  40627. },
  40628. /**
  40629. * Sets Vignette stretch size.
  40630. */
  40631. set: function (value) {
  40632. this.imageProcessingConfiguration.vignetteStretch = value;
  40633. },
  40634. enumerable: true,
  40635. configurable: true
  40636. });
  40637. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  40638. /**
  40639. * Gets Vignette centre X Offset.
  40640. */
  40641. get: function () {
  40642. return this.imageProcessingConfiguration.vignetteCentreX;
  40643. },
  40644. /**
  40645. * Sets Vignette centre X Offset.
  40646. */
  40647. set: function (value) {
  40648. this.imageProcessingConfiguration.vignetteCentreX = value;
  40649. },
  40650. enumerable: true,
  40651. configurable: true
  40652. });
  40653. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  40654. /**
  40655. * Gets Vignette centre Y Offset.
  40656. */
  40657. get: function () {
  40658. return this.imageProcessingConfiguration.vignetteCentreY;
  40659. },
  40660. /**
  40661. * Sets Vignette centre Y Offset.
  40662. */
  40663. set: function (value) {
  40664. this.imageProcessingConfiguration.vignetteCentreY = value;
  40665. },
  40666. enumerable: true,
  40667. configurable: true
  40668. });
  40669. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  40670. /**
  40671. * Gets Vignette weight or intensity of the vignette effect.
  40672. */
  40673. get: function () {
  40674. return this.imageProcessingConfiguration.vignetteWeight;
  40675. },
  40676. /**
  40677. * Sets Vignette weight or intensity of the vignette effect.
  40678. */
  40679. set: function (value) {
  40680. this.imageProcessingConfiguration.vignetteWeight = value;
  40681. },
  40682. enumerable: true,
  40683. configurable: true
  40684. });
  40685. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  40686. /**
  40687. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40688. * if vignetteEnabled is set to true.
  40689. */
  40690. get: function () {
  40691. return this.imageProcessingConfiguration.vignetteColor;
  40692. },
  40693. /**
  40694. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40695. * if vignetteEnabled is set to true.
  40696. */
  40697. set: function (value) {
  40698. this.imageProcessingConfiguration.vignetteColor = value;
  40699. },
  40700. enumerable: true,
  40701. configurable: true
  40702. });
  40703. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  40704. /**
  40705. * Gets Camera field of view used by the Vignette effect.
  40706. */
  40707. get: function () {
  40708. return this.imageProcessingConfiguration.vignetteCameraFov;
  40709. },
  40710. /**
  40711. * Sets Camera field of view used by the Vignette effect.
  40712. */
  40713. set: function (value) {
  40714. this.imageProcessingConfiguration.vignetteCameraFov = value;
  40715. },
  40716. enumerable: true,
  40717. configurable: true
  40718. });
  40719. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  40720. /**
  40721. * Gets the vignette blend mode allowing different kind of effect.
  40722. */
  40723. get: function () {
  40724. return this.imageProcessingConfiguration.vignetteBlendMode;
  40725. },
  40726. /**
  40727. * Sets the vignette blend mode allowing different kind of effect.
  40728. */
  40729. set: function (value) {
  40730. this.imageProcessingConfiguration.vignetteBlendMode = value;
  40731. },
  40732. enumerable: true,
  40733. configurable: true
  40734. });
  40735. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  40736. /**
  40737. * Gets wether the vignette effect is enabled.
  40738. */
  40739. get: function () {
  40740. return this.imageProcessingConfiguration.vignetteEnabled;
  40741. },
  40742. /**
  40743. * Sets wether the vignette effect is enabled.
  40744. */
  40745. set: function (value) {
  40746. this.imageProcessingConfiguration.vignetteEnabled = value;
  40747. },
  40748. enumerable: true,
  40749. configurable: true
  40750. });
  40751. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  40752. /**
  40753. * Gets wether the input of the processing is in Gamma or Linear Space.
  40754. */
  40755. get: function () {
  40756. return this._fromLinearSpace;
  40757. },
  40758. /**
  40759. * Sets wether the input of the processing is in Gamma or Linear Space.
  40760. */
  40761. set: function (value) {
  40762. if (this._fromLinearSpace === value) {
  40763. return;
  40764. }
  40765. this._fromLinearSpace = value;
  40766. this._updateParameters();
  40767. },
  40768. enumerable: true,
  40769. configurable: true
  40770. });
  40771. ImageProcessingPostProcess.prototype.getClassName = function () {
  40772. return "ImageProcessingPostProcess";
  40773. };
  40774. ImageProcessingPostProcess.prototype._updateParameters = function () {
  40775. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  40776. this.imageProcessingConfiguration.prepareDefines(this._defines);
  40777. var defines = "";
  40778. for (var define in this._defines) {
  40779. if (this._defines[define]) {
  40780. defines += "#define " + define + ";\r\n";
  40781. }
  40782. }
  40783. var samplers = ["textureSampler"];
  40784. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  40785. var uniforms = ["scale"];
  40786. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  40787. this.updateEffect(defines, uniforms, samplers);
  40788. };
  40789. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  40790. _super.prototype.dispose.call(this, camera);
  40791. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40792. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40793. }
  40794. this.imageProcessingConfiguration.applyByPostProcess = false;
  40795. };
  40796. __decorate([
  40797. BABYLON.serialize()
  40798. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  40799. return ImageProcessingPostProcess;
  40800. }(BABYLON.PostProcess));
  40801. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  40802. })(BABYLON || (BABYLON = {}));
  40803. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  40804. var BABYLON;
  40805. (function (BABYLON) {
  40806. /**
  40807. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  40808. * It can help converting any input color in a desired output one. This can then be used to create effects
  40809. * from sepia, black and white to sixties or futuristic rendering...
  40810. *
  40811. * The only supported format is currently 3dl.
  40812. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  40813. */
  40814. var ColorGradingTexture = (function (_super) {
  40815. __extends(ColorGradingTexture, _super);
  40816. /**
  40817. * Instantiates a ColorGradingTexture from the following parameters.
  40818. *
  40819. * @param url The location of the color gradind data (currently only supporting 3dl)
  40820. * @param scene The scene the texture will be used in
  40821. */
  40822. function ColorGradingTexture(url, scene) {
  40823. var _this = _super.call(this, scene) || this;
  40824. if (!url) {
  40825. return _this;
  40826. }
  40827. _this._textureMatrix = BABYLON.Matrix.Identity();
  40828. _this.name = url;
  40829. _this.url = url;
  40830. _this.hasAlpha = false;
  40831. _this.isCube = false;
  40832. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40833. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40834. _this.anisotropicFilteringLevel = 1;
  40835. _this._texture = _this._getFromCache(url, true);
  40836. if (!_this._texture) {
  40837. if (!scene.useDelayedTextureLoading) {
  40838. _this.loadTexture();
  40839. }
  40840. else {
  40841. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40842. }
  40843. }
  40844. return _this;
  40845. }
  40846. /**
  40847. * Returns the texture matrix used in most of the material.
  40848. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  40849. */
  40850. ColorGradingTexture.prototype.getTextureMatrix = function () {
  40851. return this._textureMatrix;
  40852. };
  40853. /**
  40854. * Occurs when the file being loaded is a .3dl LUT file.
  40855. */
  40856. ColorGradingTexture.prototype.load3dlTexture = function () {
  40857. var _this = this;
  40858. var mipLevels = 0;
  40859. var floatArrayView = null;
  40860. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40861. this._texture = texture;
  40862. var callback = function (text) {
  40863. var data;
  40864. var tempData;
  40865. var line;
  40866. var lines = text.split('\n');
  40867. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  40868. var maxColor = 0;
  40869. for (var i = 0; i < lines.length; i++) {
  40870. line = lines[i];
  40871. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  40872. continue;
  40873. if (line.indexOf('#') === 0)
  40874. continue;
  40875. var words = line.split(" ");
  40876. if (size === 0) {
  40877. // Number of space + one
  40878. size = words.length;
  40879. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  40880. tempData = new Float32Array(size * size * size * 4);
  40881. continue;
  40882. }
  40883. if (size != 0) {
  40884. var r = Math.max(parseInt(words[0]), 0);
  40885. var g = Math.max(parseInt(words[1]), 0);
  40886. var b = Math.max(parseInt(words[2]), 0);
  40887. maxColor = Math.max(r, maxColor);
  40888. maxColor = Math.max(g, maxColor);
  40889. maxColor = Math.max(b, maxColor);
  40890. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  40891. tempData[pixelStorageIndex + 0] = r;
  40892. tempData[pixelStorageIndex + 1] = g;
  40893. tempData[pixelStorageIndex + 2] = b;
  40894. pixelIndexSlice++;
  40895. if (pixelIndexSlice % size == 0) {
  40896. pixelIndexH++;
  40897. pixelIndexSlice = 0;
  40898. if (pixelIndexH % size == 0) {
  40899. pixelIndexW++;
  40900. pixelIndexH = 0;
  40901. }
  40902. }
  40903. }
  40904. }
  40905. for (var i = 0; i < tempData.length; i++) {
  40906. if (i > 0 && (i + 1) % 4 === 0) {
  40907. data[i] = 255;
  40908. }
  40909. else {
  40910. var value = tempData[i];
  40911. data[i] = (value / maxColor * 255);
  40912. }
  40913. }
  40914. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  40915. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40916. };
  40917. BABYLON.Tools.LoadFile(this.url, callback);
  40918. return this._texture;
  40919. };
  40920. /**
  40921. * Starts the loading process of the texture.
  40922. */
  40923. ColorGradingTexture.prototype.loadTexture = function () {
  40924. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  40925. this.load3dlTexture();
  40926. }
  40927. };
  40928. /**
  40929. * Clones the color gradind texture.
  40930. */
  40931. ColorGradingTexture.prototype.clone = function () {
  40932. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  40933. // Base texture
  40934. newTexture.level = this.level;
  40935. return newTexture;
  40936. };
  40937. /**
  40938. * Called during delayed load for textures.
  40939. */
  40940. ColorGradingTexture.prototype.delayLoad = function () {
  40941. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40942. return;
  40943. }
  40944. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40945. this._texture = this._getFromCache(this.url, true);
  40946. if (!this._texture) {
  40947. this.loadTexture();
  40948. }
  40949. };
  40950. /**
  40951. * Parses a color grading texture serialized by Babylon.
  40952. * @param parsedTexture The texture information being parsedTexture
  40953. * @param scene The scene to load the texture in
  40954. * @param rootUrl The root url of the data assets to load
  40955. * @return A color gradind texture
  40956. */
  40957. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40958. var texture = null;
  40959. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  40960. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  40961. texture.name = parsedTexture.name;
  40962. texture.level = parsedTexture.level;
  40963. }
  40964. return texture;
  40965. };
  40966. /**
  40967. * Serializes the LUT texture to json format.
  40968. */
  40969. ColorGradingTexture.prototype.serialize = function () {
  40970. if (!this.name) {
  40971. return null;
  40972. }
  40973. var serializationObject = {};
  40974. serializationObject.name = this.name;
  40975. serializationObject.level = this.level;
  40976. serializationObject.customType = "BABYLON.ColorGradingTexture";
  40977. return serializationObject;
  40978. };
  40979. /**
  40980. * Empty line regex stored for GC.
  40981. */
  40982. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  40983. return ColorGradingTexture;
  40984. }(BABYLON.BaseTexture));
  40985. BABYLON.ColorGradingTexture = ColorGradingTexture;
  40986. })(BABYLON || (BABYLON = {}));
  40987. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  40988. var BABYLON;
  40989. (function (BABYLON) {
  40990. /**
  40991. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40992. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40993. * 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;
  40994. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40995. */
  40996. var ColorCurves = (function () {
  40997. function ColorCurves() {
  40998. this._dirty = true;
  40999. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41000. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41001. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41002. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41003. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41004. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41005. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41006. this._globalHue = 30;
  41007. this._globalDensity = 0;
  41008. this._globalSaturation = 0;
  41009. this._globalExposure = 0;
  41010. this._highlightsHue = 30;
  41011. this._highlightsDensity = 0;
  41012. this._highlightsSaturation = 0;
  41013. this._highlightsExposure = 0;
  41014. this._midtonesHue = 30;
  41015. this._midtonesDensity = 0;
  41016. this._midtonesSaturation = 0;
  41017. this._midtonesExposure = 0;
  41018. this._shadowsHue = 30;
  41019. this._shadowsDensity = 0;
  41020. this._shadowsSaturation = 0;
  41021. this._shadowsExposure = 0;
  41022. }
  41023. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41024. /**
  41025. * Gets the global Hue value.
  41026. * 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).
  41027. */
  41028. get: function () {
  41029. return this._globalHue;
  41030. },
  41031. /**
  41032. * Sets the global Hue value.
  41033. * 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).
  41034. */
  41035. set: function (value) {
  41036. this._globalHue = value;
  41037. this._dirty = true;
  41038. },
  41039. enumerable: true,
  41040. configurable: true
  41041. });
  41042. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41043. /**
  41044. * Gets the global Density value.
  41045. * 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.
  41046. * Values less than zero provide a filter of opposite hue.
  41047. */
  41048. get: function () {
  41049. return this._globalDensity;
  41050. },
  41051. /**
  41052. * Sets the global Density value.
  41053. * 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.
  41054. * Values less than zero provide a filter of opposite hue.
  41055. */
  41056. set: function (value) {
  41057. this._globalDensity = value;
  41058. this._dirty = true;
  41059. },
  41060. enumerable: true,
  41061. configurable: true
  41062. });
  41063. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41064. /**
  41065. * Gets the global Saturation value.
  41066. * 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.
  41067. */
  41068. get: function () {
  41069. return this._globalSaturation;
  41070. },
  41071. /**
  41072. * Sets the global Saturation value.
  41073. * 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.
  41074. */
  41075. set: function (value) {
  41076. this._globalSaturation = value;
  41077. this._dirty = true;
  41078. },
  41079. enumerable: true,
  41080. configurable: true
  41081. });
  41082. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41083. /**
  41084. * Gets the highlights Hue value.
  41085. * 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).
  41086. */
  41087. get: function () {
  41088. return this._highlightsHue;
  41089. },
  41090. /**
  41091. * Sets the highlights Hue value.
  41092. * 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).
  41093. */
  41094. set: function (value) {
  41095. this._highlightsHue = value;
  41096. this._dirty = true;
  41097. },
  41098. enumerable: true,
  41099. configurable: true
  41100. });
  41101. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41102. /**
  41103. * Gets the highlights Density value.
  41104. * 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.
  41105. * Values less than zero provide a filter of opposite hue.
  41106. */
  41107. get: function () {
  41108. return this._highlightsDensity;
  41109. },
  41110. /**
  41111. * Sets the highlights Density value.
  41112. * 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.
  41113. * Values less than zero provide a filter of opposite hue.
  41114. */
  41115. set: function (value) {
  41116. this._highlightsDensity = value;
  41117. this._dirty = true;
  41118. },
  41119. enumerable: true,
  41120. configurable: true
  41121. });
  41122. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41123. /**
  41124. * Gets the highlights Saturation value.
  41125. * 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.
  41126. */
  41127. get: function () {
  41128. return this._highlightsSaturation;
  41129. },
  41130. /**
  41131. * Sets the highlights Saturation value.
  41132. * 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.
  41133. */
  41134. set: function (value) {
  41135. this._highlightsSaturation = value;
  41136. this._dirty = true;
  41137. },
  41138. enumerable: true,
  41139. configurable: true
  41140. });
  41141. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41142. /**
  41143. * Gets the highlights Exposure value.
  41144. * 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.
  41145. */
  41146. get: function () {
  41147. return this._highlightsExposure;
  41148. },
  41149. /**
  41150. * Sets the highlights Exposure value.
  41151. * 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.
  41152. */
  41153. set: function (value) {
  41154. this._highlightsExposure = value;
  41155. this._dirty = true;
  41156. },
  41157. enumerable: true,
  41158. configurable: true
  41159. });
  41160. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41161. /**
  41162. * Gets the midtones Hue value.
  41163. * 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).
  41164. */
  41165. get: function () {
  41166. return this._midtonesHue;
  41167. },
  41168. /**
  41169. * Sets the midtones Hue value.
  41170. * 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).
  41171. */
  41172. set: function (value) {
  41173. this._midtonesHue = value;
  41174. this._dirty = true;
  41175. },
  41176. enumerable: true,
  41177. configurable: true
  41178. });
  41179. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41180. /**
  41181. * Gets the midtones Density value.
  41182. * 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.
  41183. * Values less than zero provide a filter of opposite hue.
  41184. */
  41185. get: function () {
  41186. return this._midtonesDensity;
  41187. },
  41188. /**
  41189. * Sets the midtones Density value.
  41190. * 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.
  41191. * Values less than zero provide a filter of opposite hue.
  41192. */
  41193. set: function (value) {
  41194. this._midtonesDensity = value;
  41195. this._dirty = true;
  41196. },
  41197. enumerable: true,
  41198. configurable: true
  41199. });
  41200. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41201. /**
  41202. * Gets the midtones Saturation value.
  41203. * 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.
  41204. */
  41205. get: function () {
  41206. return this._midtonesSaturation;
  41207. },
  41208. /**
  41209. * Sets the midtones Saturation value.
  41210. * 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.
  41211. */
  41212. set: function (value) {
  41213. this._midtonesSaturation = value;
  41214. this._dirty = true;
  41215. },
  41216. enumerable: true,
  41217. configurable: true
  41218. });
  41219. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41220. /**
  41221. * Gets the midtones Exposure value.
  41222. * 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.
  41223. */
  41224. get: function () {
  41225. return this._midtonesExposure;
  41226. },
  41227. /**
  41228. * Sets the midtones Exposure value.
  41229. * 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.
  41230. */
  41231. set: function (value) {
  41232. this._midtonesExposure = value;
  41233. this._dirty = true;
  41234. },
  41235. enumerable: true,
  41236. configurable: true
  41237. });
  41238. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41239. /**
  41240. * Gets the shadows Hue value.
  41241. * 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).
  41242. */
  41243. get: function () {
  41244. return this._shadowsHue;
  41245. },
  41246. /**
  41247. * Sets the shadows Hue value.
  41248. * 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).
  41249. */
  41250. set: function (value) {
  41251. this._shadowsHue = value;
  41252. this._dirty = true;
  41253. },
  41254. enumerable: true,
  41255. configurable: true
  41256. });
  41257. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41258. /**
  41259. * Gets the shadows Density value.
  41260. * 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.
  41261. * Values less than zero provide a filter of opposite hue.
  41262. */
  41263. get: function () {
  41264. return this._shadowsDensity;
  41265. },
  41266. /**
  41267. * Sets the shadows Density value.
  41268. * 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.
  41269. * Values less than zero provide a filter of opposite hue.
  41270. */
  41271. set: function (value) {
  41272. this._shadowsDensity = value;
  41273. this._dirty = true;
  41274. },
  41275. enumerable: true,
  41276. configurable: true
  41277. });
  41278. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41279. /**
  41280. * Gets the shadows Saturation value.
  41281. * 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.
  41282. */
  41283. get: function () {
  41284. return this._shadowsSaturation;
  41285. },
  41286. /**
  41287. * Sets the shadows Saturation value.
  41288. * 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.
  41289. */
  41290. set: function (value) {
  41291. this._shadowsSaturation = value;
  41292. this._dirty = true;
  41293. },
  41294. enumerable: true,
  41295. configurable: true
  41296. });
  41297. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41298. /**
  41299. * Gets the shadows Exposure value.
  41300. * 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.
  41301. */
  41302. get: function () {
  41303. return this._shadowsExposure;
  41304. },
  41305. /**
  41306. * Sets the shadows Exposure value.
  41307. * 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.
  41308. */
  41309. set: function (value) {
  41310. this._shadowsExposure = value;
  41311. this._dirty = true;
  41312. },
  41313. enumerable: true,
  41314. configurable: true
  41315. });
  41316. ColorCurves.prototype.getClassName = function () {
  41317. return "ColorCurves";
  41318. };
  41319. /**
  41320. * Binds the color curves to the shader.
  41321. * @param colorCurves The color curve to bind
  41322. * @param effect The effect to bind to
  41323. */
  41324. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41325. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41326. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41327. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41328. if (colorCurves._dirty) {
  41329. colorCurves._dirty = false;
  41330. // Fill in global info.
  41331. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41332. // Compute highlights info.
  41333. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41334. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41335. // Compute midtones info.
  41336. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41337. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41338. // Compute shadows info.
  41339. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41340. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41341. // Compute deltas (neutral is midtones).
  41342. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41343. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41344. }
  41345. if (effect) {
  41346. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41347. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41348. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41349. }
  41350. };
  41351. /**
  41352. * Prepare the list of uniforms associated with the ColorCurves effects.
  41353. * @param uniformsList The list of uniforms used in the effect
  41354. */
  41355. ColorCurves.PrepareUniforms = function (uniformsList) {
  41356. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41357. };
  41358. /**
  41359. * Returns color grading data based on a hue, density, saturation and exposure value.
  41360. * @param filterHue The hue of the color filter.
  41361. * @param filterDensity The density of the color filter.
  41362. * @param saturation The saturation.
  41363. * @param exposure The exposure.
  41364. * @param result The result data container.
  41365. */
  41366. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41367. if (hue == null) {
  41368. return;
  41369. }
  41370. hue = ColorCurves.clamp(hue, 0, 360);
  41371. density = ColorCurves.clamp(density, -100, 100);
  41372. saturation = ColorCurves.clamp(saturation, -100, 100);
  41373. exposure = ColorCurves.clamp(exposure, -100, 100);
  41374. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41375. // so that the maximum filter density is only 50% control. This provides fine control
  41376. // for small values and reasonable range.
  41377. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41378. density *= 0.5;
  41379. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41380. if (density < 0) {
  41381. density *= -1;
  41382. hue = (hue + 180) % 360;
  41383. }
  41384. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41385. result.scaleToRef(2, result);
  41386. result.a = 1 + 0.01 * saturation;
  41387. };
  41388. /**
  41389. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41390. * @param value The input slider value in range [-100,100].
  41391. * @returns Adjusted value.
  41392. */
  41393. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41394. value /= 100;
  41395. var x = Math.abs(value);
  41396. x = Math.pow(x, 2);
  41397. if (value < 0) {
  41398. x *= -1;
  41399. }
  41400. x *= 100;
  41401. return x;
  41402. };
  41403. /**
  41404. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41405. * @param hue The hue (H) input.
  41406. * @param saturation The saturation (S) input.
  41407. * @param brightness The brightness (B) input.
  41408. * @result An RGBA color represented as Vector4.
  41409. */
  41410. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41411. var h = ColorCurves.clamp(hue, 0, 360);
  41412. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41413. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41414. if (s === 0) {
  41415. result.r = v;
  41416. result.g = v;
  41417. result.b = v;
  41418. }
  41419. else {
  41420. // sector 0 to 5
  41421. h /= 60;
  41422. var i = Math.floor(h);
  41423. // fractional part of h
  41424. var f = h - i;
  41425. var p = v * (1 - s);
  41426. var q = v * (1 - s * f);
  41427. var t = v * (1 - s * (1 - f));
  41428. switch (i) {
  41429. case 0:
  41430. result.r = v;
  41431. result.g = t;
  41432. result.b = p;
  41433. break;
  41434. case 1:
  41435. result.r = q;
  41436. result.g = v;
  41437. result.b = p;
  41438. break;
  41439. case 2:
  41440. result.r = p;
  41441. result.g = v;
  41442. result.b = t;
  41443. break;
  41444. case 3:
  41445. result.r = p;
  41446. result.g = q;
  41447. result.b = v;
  41448. break;
  41449. case 4:
  41450. result.r = t;
  41451. result.g = p;
  41452. result.b = v;
  41453. break;
  41454. default:// case 5:
  41455. result.r = v;
  41456. result.g = p;
  41457. result.b = q;
  41458. break;
  41459. }
  41460. }
  41461. result.a = 1;
  41462. };
  41463. /**
  41464. * Returns a value clamped between min and max
  41465. * @param value The value to clamp
  41466. * @param min The minimum of value
  41467. * @param max The maximum of value
  41468. * @returns The clamped value.
  41469. */
  41470. ColorCurves.clamp = function (value, min, max) {
  41471. return Math.min(Math.max(value, min), max);
  41472. };
  41473. /**
  41474. * Clones the current color curve instance.
  41475. * @return The cloned curves
  41476. */
  41477. ColorCurves.prototype.clone = function () {
  41478. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41479. };
  41480. /**
  41481. * Serializes the current color curve instance to a json representation.
  41482. * @return a JSON representation
  41483. */
  41484. ColorCurves.prototype.serialize = function () {
  41485. return BABYLON.SerializationHelper.Serialize(this);
  41486. };
  41487. /**
  41488. * Parses the color curve from a json representation.
  41489. * @param source the JSON source to parse
  41490. * @return The parsed curves
  41491. */
  41492. ColorCurves.Parse = function (source) {
  41493. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41494. };
  41495. __decorate([
  41496. BABYLON.serialize()
  41497. ], ColorCurves.prototype, "_globalHue", void 0);
  41498. __decorate([
  41499. BABYLON.serialize()
  41500. ], ColorCurves.prototype, "_globalDensity", void 0);
  41501. __decorate([
  41502. BABYLON.serialize()
  41503. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41504. __decorate([
  41505. BABYLON.serialize()
  41506. ], ColorCurves.prototype, "_globalExposure", void 0);
  41507. __decorate([
  41508. BABYLON.serialize()
  41509. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41510. __decorate([
  41511. BABYLON.serialize()
  41512. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41513. __decorate([
  41514. BABYLON.serialize()
  41515. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41516. __decorate([
  41517. BABYLON.serialize()
  41518. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41519. __decorate([
  41520. BABYLON.serialize()
  41521. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41522. __decorate([
  41523. BABYLON.serialize()
  41524. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41525. __decorate([
  41526. BABYLON.serialize()
  41527. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41528. __decorate([
  41529. BABYLON.serialize()
  41530. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41531. return ColorCurves;
  41532. }());
  41533. BABYLON.ColorCurves = ColorCurves;
  41534. })(BABYLON || (BABYLON = {}));
  41535. //# sourceMappingURL=babylon.colorCurves.js.map
  41536. var BABYLON;
  41537. (function (BABYLON) {
  41538. var PostProcessRenderPipelineManager = (function () {
  41539. function PostProcessRenderPipelineManager() {
  41540. this._renderPipelines = {};
  41541. }
  41542. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  41543. this._renderPipelines[renderPipeline._name] = renderPipeline;
  41544. };
  41545. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  41546. var renderPipeline = this._renderPipelines[renderPipelineName];
  41547. if (!renderPipeline) {
  41548. return;
  41549. }
  41550. renderPipeline._attachCameras(cameras, unique);
  41551. };
  41552. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  41553. var renderPipeline = this._renderPipelines[renderPipelineName];
  41554. if (!renderPipeline) {
  41555. return;
  41556. }
  41557. renderPipeline._detachCameras(cameras);
  41558. };
  41559. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  41560. var renderPipeline = this._renderPipelines[renderPipelineName];
  41561. if (!renderPipeline) {
  41562. return;
  41563. }
  41564. renderPipeline._enableEffect(renderEffectName, cameras);
  41565. };
  41566. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  41567. var renderPipeline = this._renderPipelines[renderPipelineName];
  41568. if (!renderPipeline) {
  41569. return;
  41570. }
  41571. renderPipeline._disableEffect(renderEffectName, cameras);
  41572. };
  41573. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  41574. var renderPipeline = this._renderPipelines[renderPipelineName];
  41575. if (!renderPipeline) {
  41576. return;
  41577. }
  41578. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  41579. };
  41580. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  41581. var renderPipeline = this._renderPipelines[renderPipelineName];
  41582. if (!renderPipeline) {
  41583. return;
  41584. }
  41585. renderPipeline._disableDisplayOnlyPass(cameras);
  41586. };
  41587. PostProcessRenderPipelineManager.prototype.update = function () {
  41588. for (var renderPipelineName in this._renderPipelines) {
  41589. var pipeline = this._renderPipelines[renderPipelineName];
  41590. if (!pipeline.isSupported) {
  41591. pipeline.dispose();
  41592. delete this._renderPipelines[renderPipelineName];
  41593. }
  41594. else {
  41595. pipeline._update();
  41596. }
  41597. }
  41598. };
  41599. return PostProcessRenderPipelineManager;
  41600. }());
  41601. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  41602. })(BABYLON || (BABYLON = {}));
  41603. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  41604. var BABYLON;
  41605. (function (BABYLON) {
  41606. var PostProcessRenderPass = (function () {
  41607. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  41608. this._enabled = true;
  41609. this._refCount = 0;
  41610. this._name = name;
  41611. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  41612. this.setRenderList(renderList);
  41613. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  41614. this._renderTexture.onAfterRenderObservable.add(afterRender);
  41615. this._scene = scene;
  41616. this._renderList = renderList;
  41617. }
  41618. // private
  41619. PostProcessRenderPass.prototype._incRefCount = function () {
  41620. if (this._refCount === 0) {
  41621. this._scene.customRenderTargets.push(this._renderTexture);
  41622. }
  41623. return ++this._refCount;
  41624. };
  41625. PostProcessRenderPass.prototype._decRefCount = function () {
  41626. this._refCount--;
  41627. if (this._refCount <= 0) {
  41628. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  41629. }
  41630. return this._refCount;
  41631. };
  41632. PostProcessRenderPass.prototype._update = function () {
  41633. this.setRenderList(this._renderList);
  41634. };
  41635. // public
  41636. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  41637. this._renderTexture.renderList = renderList;
  41638. };
  41639. PostProcessRenderPass.prototype.getRenderTexture = function () {
  41640. return this._renderTexture;
  41641. };
  41642. return PostProcessRenderPass;
  41643. }());
  41644. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  41645. })(BABYLON || (BABYLON = {}));
  41646. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  41647. var BABYLON;
  41648. (function (BABYLON) {
  41649. var PostProcessRenderEffect = (function () {
  41650. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  41651. this._engine = engine;
  41652. this._name = name;
  41653. this._singleInstance = singleInstance || true;
  41654. this._getPostProcess = getPostProcess;
  41655. this._cameras = [];
  41656. this._indicesForCamera = [];
  41657. this._postProcesses = {};
  41658. this._renderPasses = {};
  41659. this._renderEffectAsPasses = {};
  41660. }
  41661. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  41662. get: function () {
  41663. for (var index in this._postProcesses) {
  41664. if (!this._postProcesses[index].isSupported) {
  41665. return false;
  41666. }
  41667. }
  41668. return true;
  41669. },
  41670. enumerable: true,
  41671. configurable: true
  41672. });
  41673. PostProcessRenderEffect.prototype._update = function () {
  41674. for (var renderPassName in this._renderPasses) {
  41675. this._renderPasses[renderPassName]._update();
  41676. }
  41677. };
  41678. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  41679. this._renderPasses[renderPass._name] = renderPass;
  41680. this._linkParameters();
  41681. };
  41682. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  41683. delete this._renderPasses[renderPass._name];
  41684. this._linkParameters();
  41685. };
  41686. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  41687. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  41688. this._linkParameters();
  41689. };
  41690. PostProcessRenderEffect.prototype.getPass = function (passName) {
  41691. for (var renderPassName in this._renderPasses) {
  41692. if (renderPassName === passName) {
  41693. return this._renderPasses[passName];
  41694. }
  41695. }
  41696. };
  41697. PostProcessRenderEffect.prototype.emptyPasses = function () {
  41698. this._renderPasses = {};
  41699. this._linkParameters();
  41700. };
  41701. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  41702. var cameraKey;
  41703. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  41704. for (var i = 0; i < _cam.length; i++) {
  41705. var camera = _cam[i];
  41706. var cameraName = camera.name;
  41707. if (this._singleInstance) {
  41708. cameraKey = 0;
  41709. }
  41710. else {
  41711. cameraKey = cameraName;
  41712. }
  41713. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  41714. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  41715. if (!this._indicesForCamera[cameraName]) {
  41716. this._indicesForCamera[cameraName] = [];
  41717. }
  41718. this._indicesForCamera[cameraName].push(index);
  41719. if (this._cameras.indexOf(camera) === -1) {
  41720. this._cameras[cameraName] = camera;
  41721. }
  41722. for (var passName in this._renderPasses) {
  41723. this._renderPasses[passName]._incRefCount();
  41724. }
  41725. }
  41726. this._linkParameters();
  41727. };
  41728. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  41729. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  41730. for (var i = 0; i < _cam.length; i++) {
  41731. var camera = _cam[i];
  41732. var cameraName = camera.name;
  41733. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  41734. var index = this._cameras.indexOf(cameraName);
  41735. this._indicesForCamera.splice(index, 1);
  41736. this._cameras.splice(index, 1);
  41737. for (var passName in this._renderPasses) {
  41738. this._renderPasses[passName]._decRefCount();
  41739. }
  41740. }
  41741. };
  41742. PostProcessRenderEffect.prototype._enable = function (cameras) {
  41743. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  41744. for (var i = 0; i < _cam.length; i++) {
  41745. var camera = _cam[i];
  41746. var cameraName = camera.name;
  41747. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  41748. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  41749. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  41750. }
  41751. }
  41752. for (var passName in this._renderPasses) {
  41753. this._renderPasses[passName]._incRefCount();
  41754. }
  41755. }
  41756. };
  41757. PostProcessRenderEffect.prototype._disable = function (cameras) {
  41758. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  41759. for (var i = 0; i < _cam.length; i++) {
  41760. var camera = _cam[i];
  41761. var cameraName = camera.Name;
  41762. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  41763. for (var passName in this._renderPasses) {
  41764. this._renderPasses[passName]._decRefCount();
  41765. }
  41766. }
  41767. };
  41768. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  41769. if (this._singleInstance) {
  41770. return this._postProcesses[0];
  41771. }
  41772. else {
  41773. return this._postProcesses[camera.name];
  41774. }
  41775. };
  41776. PostProcessRenderEffect.prototype._linkParameters = function () {
  41777. var _this = this;
  41778. for (var index in this._postProcesses) {
  41779. if (this.applyParameters) {
  41780. this.applyParameters(this._postProcesses[index]);
  41781. }
  41782. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  41783. _this._linkTextures(effect);
  41784. });
  41785. }
  41786. };
  41787. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  41788. for (var renderPassName in this._renderPasses) {
  41789. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  41790. }
  41791. for (var renderEffectName in this._renderEffectAsPasses) {
  41792. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  41793. }
  41794. };
  41795. return PostProcessRenderEffect;
  41796. }());
  41797. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  41798. })(BABYLON || (BABYLON = {}));
  41799. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  41800. var BABYLON;
  41801. (function (BABYLON) {
  41802. var PostProcessRenderPipeline = (function () {
  41803. function PostProcessRenderPipeline(engine, name) {
  41804. this._engine = engine;
  41805. this._name = name;
  41806. this._renderEffects = new Array();
  41807. this._renderEffectsForIsolatedPass = new Array();
  41808. this._cameras = [];
  41809. }
  41810. PostProcessRenderPipeline.prototype.getClassName = function () {
  41811. return "PostProcessRenderPipeline";
  41812. };
  41813. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  41814. get: function () {
  41815. for (var renderEffectName in this._renderEffects) {
  41816. if (!this._renderEffects[renderEffectName].isSupported) {
  41817. return false;
  41818. }
  41819. }
  41820. return true;
  41821. },
  41822. enumerable: true,
  41823. configurable: true
  41824. });
  41825. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  41826. this._renderEffects[renderEffect._name] = renderEffect;
  41827. };
  41828. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  41829. var renderEffects = this._renderEffects[renderEffectName];
  41830. if (!renderEffects) {
  41831. return;
  41832. }
  41833. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  41834. };
  41835. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  41836. var renderEffects = this._renderEffects[renderEffectName];
  41837. if (!renderEffects) {
  41838. return;
  41839. }
  41840. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  41841. };
  41842. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  41843. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  41844. var indicesToDelete = [];
  41845. var i;
  41846. for (i = 0; i < _cam.length; i++) {
  41847. var camera = _cam[i];
  41848. var cameraName = camera.name;
  41849. if (this._cameras.indexOf(camera) === -1) {
  41850. this._cameras[cameraName] = camera;
  41851. }
  41852. else if (unique) {
  41853. indicesToDelete.push(i);
  41854. }
  41855. }
  41856. for (i = 0; i < indicesToDelete.length; i++) {
  41857. cameras.splice(indicesToDelete[i], 1);
  41858. }
  41859. for (var renderEffectName in this._renderEffects) {
  41860. this._renderEffects[renderEffectName]._attachCameras(_cam);
  41861. }
  41862. };
  41863. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  41864. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  41865. for (var renderEffectName in this._renderEffects) {
  41866. this._renderEffects[renderEffectName]._detachCameras(_cam);
  41867. }
  41868. for (var i = 0; i < _cam.length; i++) {
  41869. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  41870. }
  41871. };
  41872. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  41873. var _this = this;
  41874. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  41875. var pass = null;
  41876. var renderEffectName;
  41877. for (renderEffectName in this._renderEffects) {
  41878. pass = this._renderEffects[renderEffectName].getPass(passName);
  41879. if (pass != null) {
  41880. break;
  41881. }
  41882. }
  41883. if (pass === null) {
  41884. return;
  41885. }
  41886. for (renderEffectName in this._renderEffects) {
  41887. this._renderEffects[renderEffectName]._disable(_cam);
  41888. }
  41889. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  41890. for (var i = 0; i < _cam.length; i++) {
  41891. var camera = _cam[i];
  41892. var cameraName = camera.name;
  41893. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  41894. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  41895. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  41896. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  41897. }
  41898. };
  41899. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  41900. var _this = this;
  41901. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  41902. for (var i = 0; i < _cam.length; i++) {
  41903. var camera = _cam[i];
  41904. var cameraName = camera.name;
  41905. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  41906. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  41907. }
  41908. for (var renderEffectName in this._renderEffects) {
  41909. this._renderEffects[renderEffectName]._enable(_cam);
  41910. }
  41911. };
  41912. PostProcessRenderPipeline.prototype._update = function () {
  41913. for (var renderEffectName in this._renderEffects) {
  41914. this._renderEffects[renderEffectName]._update();
  41915. }
  41916. for (var i = 0; i < this._cameras.length; i++) {
  41917. var cameraName = this._cameras[i].name;
  41918. if (this._renderEffectsForIsolatedPass[cameraName]) {
  41919. this._renderEffectsForIsolatedPass[cameraName]._update();
  41920. }
  41921. }
  41922. };
  41923. PostProcessRenderPipeline.prototype._reset = function () {
  41924. this._renderEffects = new Array();
  41925. this._renderEffectsForIsolatedPass = new Array();
  41926. };
  41927. PostProcessRenderPipeline.prototype.dispose = function () {
  41928. // Must be implemented by children
  41929. };
  41930. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  41931. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  41932. __decorate([
  41933. BABYLON.serialize()
  41934. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  41935. return PostProcessRenderPipeline;
  41936. }());
  41937. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  41938. })(BABYLON || (BABYLON = {}));
  41939. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  41940. var BABYLON;
  41941. (function (BABYLON) {
  41942. var DefaultRenderingPipeline = (function (_super) {
  41943. __extends(DefaultRenderingPipeline, _super);
  41944. /**
  41945. * @constructor
  41946. * @param {string} name - The rendering pipeline name
  41947. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  41948. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  41949. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  41950. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  41951. */
  41952. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  41953. if (automaticBuild === void 0) { automaticBuild = true; }
  41954. var _this = _super.call(this, scene.getEngine(), name) || this;
  41955. _this.PassPostProcessId = "PassPostProcessEffect";
  41956. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  41957. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  41958. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  41959. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  41960. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  41961. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  41962. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  41963. // IAnimatable
  41964. _this.animations = [];
  41965. // Values
  41966. _this._bloomEnabled = false;
  41967. _this._fxaaEnabled = false;
  41968. _this._imageProcessingEnabled = true;
  41969. _this._bloomScale = 0.6;
  41970. _this._buildAllowed = true;
  41971. /**
  41972. * Specifies the size of the bloom blur kernel, relative to the final output size
  41973. */
  41974. _this.bloomKernel = 64;
  41975. /**
  41976. * Specifies the weight of the bloom in the final rendering
  41977. */
  41978. _this._bloomWeight = 0.15;
  41979. _this._cameras = cameras || [];
  41980. _this._buildAllowed = automaticBuild;
  41981. // Initialize
  41982. _this._scene = scene;
  41983. var caps = _this._scene.getEngine().getCaps();
  41984. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  41985. // Misc
  41986. if (_this._hdr) {
  41987. if (caps.textureHalfFloatRender) {
  41988. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  41989. }
  41990. else if (caps.textureFloatRender) {
  41991. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  41992. }
  41993. }
  41994. else {
  41995. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  41996. }
  41997. // Attach
  41998. scene.postProcessRenderPipelineManager.addPipeline(_this);
  41999. _this._buildPipeline();
  42000. return _this;
  42001. }
  42002. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  42003. get: function () {
  42004. return this._bloomWeight;
  42005. },
  42006. set: function (value) {
  42007. if (this._bloomWeight === value) {
  42008. return;
  42009. }
  42010. this._bloomWeight = value;
  42011. if (this._hdr && this.copyBack) {
  42012. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  42013. }
  42014. },
  42015. enumerable: true,
  42016. configurable: true
  42017. });
  42018. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  42019. get: function () {
  42020. return this._bloomScale;
  42021. },
  42022. set: function (value) {
  42023. if (this._bloomScale === value) {
  42024. return;
  42025. }
  42026. this._bloomScale = value;
  42027. this._buildPipeline();
  42028. },
  42029. enumerable: true,
  42030. configurable: true
  42031. });
  42032. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  42033. get: function () {
  42034. return this._bloomEnabled;
  42035. },
  42036. set: function (enabled) {
  42037. if (this._bloomEnabled === enabled) {
  42038. return;
  42039. }
  42040. this._bloomEnabled = enabled;
  42041. this._buildPipeline();
  42042. },
  42043. enumerable: true,
  42044. configurable: true
  42045. });
  42046. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  42047. get: function () {
  42048. return this._fxaaEnabled;
  42049. },
  42050. set: function (enabled) {
  42051. if (this._fxaaEnabled === enabled) {
  42052. return;
  42053. }
  42054. this._fxaaEnabled = enabled;
  42055. this._buildPipeline();
  42056. },
  42057. enumerable: true,
  42058. configurable: true
  42059. });
  42060. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  42061. get: function () {
  42062. return this._imageProcessingEnabled;
  42063. },
  42064. set: function (enabled) {
  42065. if (this._imageProcessingEnabled === enabled) {
  42066. return;
  42067. }
  42068. this._imageProcessingEnabled = enabled;
  42069. this._buildPipeline();
  42070. },
  42071. enumerable: true,
  42072. configurable: true
  42073. });
  42074. /**
  42075. * Force the compilation of the entire pipeline.
  42076. */
  42077. DefaultRenderingPipeline.prototype.prepare = function () {
  42078. var previousState = this._buildAllowed;
  42079. this._buildAllowed = true;
  42080. this._buildPipeline();
  42081. this._buildAllowed = previousState;
  42082. };
  42083. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  42084. var _this = this;
  42085. if (!this._buildAllowed) {
  42086. return;
  42087. }
  42088. var engine = this._scene.getEngine();
  42089. this._disposePostProcesses();
  42090. this._reset();
  42091. if (this.bloomEnabled) {
  42092. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42093. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  42094. if (!this._hdr) {
  42095. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42096. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  42097. this.highlights.autoClear = false;
  42098. this.highlights.alwaysForcePOT = true;
  42099. }
  42100. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42101. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  42102. this.blurX.alwaysForcePOT = true;
  42103. this.blurX.autoClear = false;
  42104. this.blurX.onActivateObservable.add(function () {
  42105. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  42106. _this.blurX.kernel = _this.bloomKernel * dw;
  42107. });
  42108. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42109. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  42110. this.blurY.alwaysForcePOT = true;
  42111. this.blurY.autoClear = false;
  42112. this.blurY.onActivateObservable.add(function () {
  42113. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  42114. _this.blurY.kernel = _this.bloomKernel * dh;
  42115. });
  42116. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42117. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  42118. this.copyBack.alwaysForcePOT = true;
  42119. if (this._hdr) {
  42120. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  42121. var w = this.bloomWeight;
  42122. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  42123. }
  42124. else {
  42125. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  42126. }
  42127. this.copyBack.autoClear = false;
  42128. }
  42129. if (this._imageProcessingEnabled) {
  42130. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42131. if (this._hdr) {
  42132. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  42133. }
  42134. }
  42135. if (this.fxaaEnabled) {
  42136. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42137. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  42138. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42139. }
  42140. else {
  42141. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42142. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  42143. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42144. }
  42145. if (this.bloomEnabled) {
  42146. if (this._hdr) {
  42147. this.copyBack.shareOutputWith(this.blurX);
  42148. if (this.imageProcessing) {
  42149. this.imageProcessing.shareOutputWith(this.pass);
  42150. this.imageProcessing.autoClear = false;
  42151. }
  42152. else if (this.fxaa) {
  42153. this.fxaa.shareOutputWith(this.pass);
  42154. }
  42155. else {
  42156. this.finalMerge.shareOutputWith(this.pass);
  42157. }
  42158. }
  42159. else {
  42160. if (this.fxaa) {
  42161. this.fxaa.shareOutputWith(this.pass);
  42162. }
  42163. else {
  42164. this.finalMerge.shareOutputWith(this.pass);
  42165. }
  42166. }
  42167. }
  42168. if (this._cameras !== null) {
  42169. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  42170. }
  42171. };
  42172. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  42173. for (var i = 0; i < this._cameras.length; i++) {
  42174. var camera = this._cameras[i];
  42175. if (this.pass) {
  42176. this.pass.dispose(camera);
  42177. }
  42178. if (this.highlights) {
  42179. this.highlights.dispose(camera);
  42180. }
  42181. if (this.blurX) {
  42182. this.blurX.dispose(camera);
  42183. }
  42184. if (this.blurY) {
  42185. this.blurY.dispose(camera);
  42186. }
  42187. if (this.copyBack) {
  42188. this.copyBack.dispose(camera);
  42189. }
  42190. if (this.imageProcessing) {
  42191. this.imageProcessing.dispose(camera);
  42192. }
  42193. if (this.fxaa) {
  42194. this.fxaa.dispose(camera);
  42195. }
  42196. if (this.finalMerge) {
  42197. this.finalMerge.dispose(camera);
  42198. }
  42199. }
  42200. this.pass = null;
  42201. this.highlights = null;
  42202. this.blurX = null;
  42203. this.blurY = null;
  42204. this.copyBack = null;
  42205. this.imageProcessing = null;
  42206. this.fxaa = null;
  42207. this.finalMerge = null;
  42208. };
  42209. // Dispose
  42210. DefaultRenderingPipeline.prototype.dispose = function () {
  42211. this._disposePostProcesses();
  42212. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  42213. _super.prototype.dispose.call(this);
  42214. };
  42215. // Serialize rendering pipeline
  42216. DefaultRenderingPipeline.prototype.serialize = function () {
  42217. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42218. serializationObject.customType = "DefaultRenderingPipeline";
  42219. return serializationObject;
  42220. };
  42221. // Parse serialized pipeline
  42222. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  42223. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  42224. };
  42225. __decorate([
  42226. BABYLON.serialize()
  42227. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  42228. __decorate([
  42229. BABYLON.serialize()
  42230. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  42231. __decorate([
  42232. BABYLON.serialize()
  42233. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  42234. __decorate([
  42235. BABYLON.serialize()
  42236. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  42237. __decorate([
  42238. BABYLON.serialize()
  42239. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  42240. __decorate([
  42241. BABYLON.serialize()
  42242. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  42243. __decorate([
  42244. BABYLON.serialize()
  42245. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  42246. __decorate([
  42247. BABYLON.serialize()
  42248. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  42249. return DefaultRenderingPipeline;
  42250. }(BABYLON.PostProcessRenderPipeline));
  42251. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  42252. })(BABYLON || (BABYLON = {}));
  42253. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  42254. var BABYLON;
  42255. (function (BABYLON) {
  42256. /**
  42257. * This groups together the common properties used for image processing either in direct forward pass
  42258. * or through post processing effect depending on the use of the image processing pipeline in your scene
  42259. * or not.
  42260. */
  42261. var ImageProcessingConfiguration = (function () {
  42262. function ImageProcessingConfiguration() {
  42263. /**
  42264. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  42265. */
  42266. this.colorCurves = new BABYLON.ColorCurves();
  42267. this._colorCurvesEnabled = false;
  42268. this._colorGradingEnabled = false;
  42269. this._colorGradingWithGreenDepth = false;
  42270. this._colorGradingBGR = false;
  42271. this._exposure = 1.0;
  42272. this._toneMappingEnabled = false;
  42273. this._contrast = 1.0;
  42274. /**
  42275. * Vignette stretch size.
  42276. */
  42277. this.vignetteStretch = 0;
  42278. /**
  42279. * Vignette centre X Offset.
  42280. */
  42281. this.vignetteCentreX = 0;
  42282. /**
  42283. * Vignette centre Y Offset.
  42284. */
  42285. this.vignetteCentreY = 0;
  42286. /**
  42287. * Vignette weight or intensity of the vignette effect.
  42288. */
  42289. this.vignetteWeight = 1.5;
  42290. /**
  42291. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  42292. * if vignetteEnabled is set to true.
  42293. */
  42294. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  42295. /**
  42296. * Camera field of view used by the Vignette effect.
  42297. */
  42298. this.vignetteCameraFov = 0.5;
  42299. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  42300. this._vignetteEnabled = false;
  42301. this._applyByPostProcess = false;
  42302. /**
  42303. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  42304. * @type {BABYLON.Observable}
  42305. */
  42306. this.onUpdateParameters = new BABYLON.Observable();
  42307. }
  42308. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  42309. /**
  42310. * Gets wether the color curves effect is enabled.
  42311. */
  42312. get: function () {
  42313. return this._colorCurvesEnabled;
  42314. },
  42315. /**
  42316. * Sets wether the color curves effect is enabled.
  42317. */
  42318. set: function (value) {
  42319. if (this._colorCurvesEnabled === value) {
  42320. return;
  42321. }
  42322. this._colorCurvesEnabled = value;
  42323. this._updateParameters();
  42324. },
  42325. enumerable: true,
  42326. configurable: true
  42327. });
  42328. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  42329. /**
  42330. * Gets wether the color grading effect is enabled.
  42331. */
  42332. get: function () {
  42333. return this._colorGradingEnabled;
  42334. },
  42335. /**
  42336. * Sets wether the color grading effect is enabled.
  42337. */
  42338. set: function (value) {
  42339. if (this._colorGradingEnabled === value) {
  42340. return;
  42341. }
  42342. this._colorGradingEnabled = value;
  42343. this._updateParameters();
  42344. },
  42345. enumerable: true,
  42346. configurable: true
  42347. });
  42348. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  42349. /**
  42350. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  42351. */
  42352. get: function () {
  42353. return this._colorGradingWithGreenDepth;
  42354. },
  42355. /**
  42356. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  42357. */
  42358. set: function (value) {
  42359. if (this._colorGradingWithGreenDepth === value) {
  42360. return;
  42361. }
  42362. this._colorGradingWithGreenDepth = value;
  42363. this._updateParameters();
  42364. },
  42365. enumerable: true,
  42366. configurable: true
  42367. });
  42368. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  42369. /**
  42370. * Gets wether the color grading texture contains BGR values.
  42371. */
  42372. get: function () {
  42373. return this._colorGradingBGR;
  42374. },
  42375. /**
  42376. * Sets wether the color grading texture contains BGR values.
  42377. */
  42378. set: function (value) {
  42379. if (this._colorGradingBGR === value) {
  42380. return;
  42381. }
  42382. this._colorGradingBGR = value;
  42383. this._updateParameters();
  42384. },
  42385. enumerable: true,
  42386. configurable: true
  42387. });
  42388. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  42389. /**
  42390. * Gets the Exposure used in the effect.
  42391. */
  42392. get: function () {
  42393. return this._exposure;
  42394. },
  42395. /**
  42396. * Sets the Exposure used in the effect.
  42397. */
  42398. set: function (value) {
  42399. if (this._exposure === value) {
  42400. return;
  42401. }
  42402. this._exposure = value;
  42403. this._updateParameters();
  42404. },
  42405. enumerable: true,
  42406. configurable: true
  42407. });
  42408. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  42409. /**
  42410. * Gets wether the tone mapping effect is enabled.
  42411. */
  42412. get: function () {
  42413. return this._toneMappingEnabled;
  42414. },
  42415. /**
  42416. * Sets wether the tone mapping effect is enabled.
  42417. */
  42418. set: function (value) {
  42419. if (this._toneMappingEnabled === value) {
  42420. return;
  42421. }
  42422. this._toneMappingEnabled = value;
  42423. this._updateParameters();
  42424. },
  42425. enumerable: true,
  42426. configurable: true
  42427. });
  42428. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  42429. /**
  42430. * Gets the contrast used in the effect.
  42431. */
  42432. get: function () {
  42433. return this._contrast;
  42434. },
  42435. /**
  42436. * Sets the contrast used in the effect.
  42437. */
  42438. set: function (value) {
  42439. if (this._contrast === value) {
  42440. return;
  42441. }
  42442. this._contrast = value;
  42443. this._updateParameters();
  42444. },
  42445. enumerable: true,
  42446. configurable: true
  42447. });
  42448. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  42449. /**
  42450. * Gets the vignette blend mode allowing different kind of effect.
  42451. */
  42452. get: function () {
  42453. return this._vignetteBlendMode;
  42454. },
  42455. /**
  42456. * Sets the vignette blend mode allowing different kind of effect.
  42457. */
  42458. set: function (value) {
  42459. if (this._vignetteBlendMode === value) {
  42460. return;
  42461. }
  42462. this._vignetteBlendMode = value;
  42463. this._updateParameters();
  42464. },
  42465. enumerable: true,
  42466. configurable: true
  42467. });
  42468. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  42469. /**
  42470. * Gets wether the vignette effect is enabled.
  42471. */
  42472. get: function () {
  42473. return this._vignetteEnabled;
  42474. },
  42475. /**
  42476. * Sets wether the vignette effect is enabled.
  42477. */
  42478. set: function (value) {
  42479. if (this._vignetteEnabled === value) {
  42480. return;
  42481. }
  42482. this._vignetteEnabled = value;
  42483. this._updateParameters();
  42484. },
  42485. enumerable: true,
  42486. configurable: true
  42487. });
  42488. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  42489. /**
  42490. * Gets wether the image processing is applied through a post process or not.
  42491. */
  42492. get: function () {
  42493. return this._applyByPostProcess;
  42494. },
  42495. /**
  42496. * Sets wether the image processing is applied through a post process or not.
  42497. */
  42498. set: function (value) {
  42499. if (this._applyByPostProcess === value) {
  42500. return;
  42501. }
  42502. this._applyByPostProcess = value;
  42503. this._updateParameters();
  42504. },
  42505. enumerable: true,
  42506. configurable: true
  42507. });
  42508. /**
  42509. * Method called each time the image processing information changes requires to recompile the effect.
  42510. */
  42511. ImageProcessingConfiguration.prototype._updateParameters = function () {
  42512. this.onUpdateParameters.notifyObservers(this);
  42513. };
  42514. ImageProcessingConfiguration.prototype.getClassName = function () {
  42515. return "ImageProcessingConfiguration";
  42516. };
  42517. /**
  42518. * Prepare the list of uniforms associated with the Image Processing effects.
  42519. * @param uniformsList The list of uniforms used in the effect
  42520. * @param defines the list of defines currently in use
  42521. */
  42522. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  42523. if (defines.EXPOSURE) {
  42524. uniforms.push("exposureLinear");
  42525. }
  42526. if (defines.CONTRAST) {
  42527. uniforms.push("contrast");
  42528. }
  42529. if (defines.COLORGRADING) {
  42530. uniforms.push("colorTransformSettings");
  42531. }
  42532. if (defines.VIGNETTE) {
  42533. uniforms.push("vInverseScreenSize");
  42534. uniforms.push("vignetteSettings1");
  42535. uniforms.push("vignetteSettings2");
  42536. }
  42537. if (defines.COLORCURVES) {
  42538. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  42539. }
  42540. };
  42541. /**
  42542. * Prepare the list of samplers associated with the Image Processing effects.
  42543. * @param uniformsList The list of uniforms used in the effect
  42544. * @param defines the list of defines currently in use
  42545. */
  42546. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  42547. if (defines.COLORGRADING) {
  42548. samplersList.push("txColorTransform");
  42549. }
  42550. };
  42551. /**
  42552. * Prepare the list of defines associated to the shader.
  42553. * @param defines the list of defines to complete
  42554. */
  42555. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  42556. defines.VIGNETTE = this.vignetteEnabled;
  42557. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  42558. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  42559. defines.TONEMAPPING = this.toneMappingEnabled;
  42560. defines.CONTRAST = (this.contrast !== 1.0);
  42561. defines.EXPOSURE = (this.exposure !== 1.0);
  42562. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  42563. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  42564. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  42565. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  42566. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  42567. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  42568. };
  42569. /**
  42570. * Returns true if all the image processing information are ready.
  42571. */
  42572. ImageProcessingConfiguration.prototype.isReady = function () {
  42573. // Color Grading texure can not be none blocking.
  42574. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  42575. };
  42576. /**
  42577. * Binds the image processing to the shader.
  42578. * @param effect The effect to bind to
  42579. */
  42580. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  42581. if (aspectRatio === void 0) { aspectRatio = 1; }
  42582. // Color Curves
  42583. if (this._colorCurvesEnabled) {
  42584. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  42585. }
  42586. // Vignette
  42587. if (this._vignetteEnabled) {
  42588. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  42589. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  42590. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  42591. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  42592. var vignetteScaleX = vignetteScaleY * aspectRatio;
  42593. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  42594. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  42595. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  42596. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  42597. var vignettePower = -2.0 * this.vignetteWeight;
  42598. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  42599. }
  42600. // Exposure
  42601. effect.setFloat("exposureLinear", this.exposure);
  42602. // Contrast
  42603. effect.setFloat("contrast", this.contrast);
  42604. // Color transform settings
  42605. if (this.colorGradingTexture) {
  42606. effect.setTexture("txColorTransform", this.colorGradingTexture);
  42607. var textureSize = this.colorGradingTexture.getSize().height;
  42608. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  42609. 0.5 / textureSize, // textureOffset
  42610. textureSize, // textureSize
  42611. this.colorGradingTexture.level // weight
  42612. );
  42613. }
  42614. };
  42615. /**
  42616. * Clones the current image processing instance.
  42617. * @return The cloned image processing
  42618. */
  42619. ImageProcessingConfiguration.prototype.clone = function () {
  42620. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  42621. };
  42622. /**
  42623. * Serializes the current image processing instance to a json representation.
  42624. * @return a JSON representation
  42625. */
  42626. ImageProcessingConfiguration.prototype.serialize = function () {
  42627. return BABYLON.SerializationHelper.Serialize(this);
  42628. };
  42629. /**
  42630. * Parses the image processing from a json representation.
  42631. * @param source the JSON source to parse
  42632. * @return The parsed image processing
  42633. */
  42634. ImageProcessingConfiguration.Parse = function (source) {
  42635. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  42636. };
  42637. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  42638. /**
  42639. * Used to apply the vignette as a mix with the pixel color.
  42640. */
  42641. get: function () {
  42642. return this._VIGNETTEMODE_MULTIPLY;
  42643. },
  42644. enumerable: true,
  42645. configurable: true
  42646. });
  42647. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  42648. /**
  42649. * Used to apply the vignette as a replacement of the pixel color.
  42650. */
  42651. get: function () {
  42652. return this._VIGNETTEMODE_OPAQUE;
  42653. },
  42654. enumerable: true,
  42655. configurable: true
  42656. });
  42657. // Static constants associated to the image processing.
  42658. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  42659. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  42660. __decorate([
  42661. BABYLON.serializeAsColorCurves()
  42662. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  42663. __decorate([
  42664. BABYLON.serialize()
  42665. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  42666. __decorate([
  42667. BABYLON.serializeAsTexture()
  42668. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  42669. __decorate([
  42670. BABYLON.serialize()
  42671. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  42672. __decorate([
  42673. BABYLON.serialize()
  42674. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  42675. __decorate([
  42676. BABYLON.serialize()
  42677. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  42678. __decorate([
  42679. BABYLON.serialize()
  42680. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  42681. __decorate([
  42682. BABYLON.serialize()
  42683. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  42684. __decorate([
  42685. BABYLON.serialize()
  42686. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  42687. __decorate([
  42688. BABYLON.serialize()
  42689. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  42690. __decorate([
  42691. BABYLON.serialize()
  42692. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  42693. __decorate([
  42694. BABYLON.serialize()
  42695. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  42696. __decorate([
  42697. BABYLON.serialize()
  42698. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  42699. __decorate([
  42700. BABYLON.serializeAsColor4()
  42701. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  42702. __decorate([
  42703. BABYLON.serialize()
  42704. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  42705. __decorate([
  42706. BABYLON.serialize()
  42707. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  42708. __decorate([
  42709. BABYLON.serialize()
  42710. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  42711. __decorate([
  42712. BABYLON.serialize()
  42713. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  42714. return ImageProcessingConfiguration;
  42715. }());
  42716. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  42717. })(BABYLON || (BABYLON = {}));
  42718. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  42719. /// <reference path="babylon.mesh.ts" />
  42720. var BABYLON;
  42721. (function (BABYLON) {
  42722. var GroundMesh = (function (_super) {
  42723. __extends(GroundMesh, _super);
  42724. function GroundMesh(name, scene) {
  42725. var _this = _super.call(this, name, scene) || this;
  42726. _this.generateOctree = false;
  42727. _this._worldInverse = new BABYLON.Matrix();
  42728. return _this;
  42729. }
  42730. GroundMesh.prototype.getClassName = function () {
  42731. return "GroundMesh";
  42732. };
  42733. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  42734. get: function () {
  42735. return Math.min(this._subdivisionsX, this._subdivisionsY);
  42736. },
  42737. enumerable: true,
  42738. configurable: true
  42739. });
  42740. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  42741. get: function () {
  42742. return this._subdivisionsX;
  42743. },
  42744. enumerable: true,
  42745. configurable: true
  42746. });
  42747. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  42748. get: function () {
  42749. return this._subdivisionsY;
  42750. },
  42751. enumerable: true,
  42752. configurable: true
  42753. });
  42754. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  42755. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  42756. this._subdivisionsX = chunksCount;
  42757. this._subdivisionsY = chunksCount;
  42758. this.subdivide(chunksCount);
  42759. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  42760. };
  42761. /**
  42762. * Returns a height (y) value in the Worl system :
  42763. * the ground altitude at the coordinates (x, z) expressed in the World system.
  42764. * Returns the ground y position if (x, z) are outside the ground surface.
  42765. */
  42766. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  42767. var world = this.getWorldMatrix();
  42768. var invMat = BABYLON.Tmp.Matrix[5];
  42769. world.invertToRef(invMat);
  42770. var tmpVect = BABYLON.Tmp.Vector3[8];
  42771. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  42772. x = tmpVect.x;
  42773. z = tmpVect.z;
  42774. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42775. return this.position.y;
  42776. }
  42777. if (!this._heightQuads || this._heightQuads.length == 0) {
  42778. this._initHeightQuads();
  42779. this._computeHeightQuads();
  42780. }
  42781. var facet = this._getFacetAt(x, z);
  42782. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  42783. // return y in the World system
  42784. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  42785. return tmpVect.y;
  42786. };
  42787. /**
  42788. * Returns a normalized vector (Vector3) orthogonal to the ground
  42789. * at the ground coordinates (x, z) expressed in the World system.
  42790. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  42791. */
  42792. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  42793. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  42794. this.getNormalAtCoordinatesToRef(x, z, normal);
  42795. return normal;
  42796. };
  42797. /**
  42798. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  42799. * at the ground coordinates (x, z) expressed in the World system.
  42800. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  42801. * Returns the GroundMesh.
  42802. */
  42803. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  42804. var world = this.getWorldMatrix();
  42805. var tmpMat = BABYLON.Tmp.Matrix[5];
  42806. world.invertToRef(tmpMat);
  42807. var tmpVect = BABYLON.Tmp.Vector3[8];
  42808. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  42809. x = tmpVect.x;
  42810. z = tmpVect.z;
  42811. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42812. return this;
  42813. }
  42814. if (!this._heightQuads || this._heightQuads.length == 0) {
  42815. this._initHeightQuads();
  42816. this._computeHeightQuads();
  42817. }
  42818. var facet = this._getFacetAt(x, z);
  42819. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  42820. return this;
  42821. };
  42822. /**
  42823. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  42824. * if the ground has been updated.
  42825. * This can be used in the render loop.
  42826. * Returns the GroundMesh.
  42827. */
  42828. GroundMesh.prototype.updateCoordinateHeights = function () {
  42829. if (!this._heightQuads || this._heightQuads.length == 0) {
  42830. this._initHeightQuads();
  42831. }
  42832. this._computeHeightQuads();
  42833. return this;
  42834. };
  42835. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  42836. GroundMesh.prototype._getFacetAt = function (x, z) {
  42837. // retrieve col and row from x, z coordinates in the ground local system
  42838. var subdivisionsX = this._subdivisionsX;
  42839. var subdivisionsY = this._subdivisionsY;
  42840. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  42841. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  42842. var quad = this._heightQuads[row * this._subdivisionsX + col];
  42843. var facet;
  42844. if (z < quad.slope.x * x + quad.slope.y) {
  42845. facet = quad.facet1;
  42846. }
  42847. else {
  42848. facet = quad.facet2;
  42849. }
  42850. return facet;
  42851. };
  42852. // Creates and populates the heightMap array with "facet" elements :
  42853. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  42854. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42855. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42856. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42857. // Returns the GroundMesh.
  42858. GroundMesh.prototype._initHeightQuads = function () {
  42859. var subdivisionsX = this._subdivisionsX;
  42860. var subdivisionsY = this._subdivisionsY;
  42861. this._heightQuads = new Array();
  42862. for (var row = 0; row < subdivisionsY; row++) {
  42863. for (var col = 0; col < subdivisionsX; col++) {
  42864. 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) };
  42865. this._heightQuads[row * subdivisionsX + col] = quad;
  42866. }
  42867. }
  42868. return this;
  42869. };
  42870. // Compute each quad element values and update the the heightMap array :
  42871. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42872. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42873. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42874. // Returns the GroundMesh.
  42875. GroundMesh.prototype._computeHeightQuads = function () {
  42876. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42877. var v1 = BABYLON.Tmp.Vector3[3];
  42878. var v2 = BABYLON.Tmp.Vector3[2];
  42879. var v3 = BABYLON.Tmp.Vector3[1];
  42880. var v4 = BABYLON.Tmp.Vector3[0];
  42881. var v1v2 = BABYLON.Tmp.Vector3[4];
  42882. var v1v3 = BABYLON.Tmp.Vector3[5];
  42883. var v1v4 = BABYLON.Tmp.Vector3[6];
  42884. var norm1 = BABYLON.Tmp.Vector3[7];
  42885. var norm2 = BABYLON.Tmp.Vector3[8];
  42886. var i = 0;
  42887. var j = 0;
  42888. var k = 0;
  42889. var cd = 0; // 2D slope coefficient : z = cd * x + h
  42890. var h = 0;
  42891. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  42892. var d2 = 0;
  42893. var subdivisionsX = this._subdivisionsX;
  42894. var subdivisionsY = this._subdivisionsY;
  42895. for (var row = 0; row < subdivisionsY; row++) {
  42896. for (var col = 0; col < subdivisionsX; col++) {
  42897. i = col * 3;
  42898. j = row * (subdivisionsX + 1) * 3;
  42899. k = (row + 1) * (subdivisionsX + 1) * 3;
  42900. v1.x = positions[j + i];
  42901. v1.y = positions[j + i + 1];
  42902. v1.z = positions[j + i + 2];
  42903. v2.x = positions[j + i + 3];
  42904. v2.y = positions[j + i + 4];
  42905. v2.z = positions[j + i + 5];
  42906. v3.x = positions[k + i];
  42907. v3.y = positions[k + i + 1];
  42908. v3.z = positions[k + i + 2];
  42909. v4.x = positions[k + i + 3];
  42910. v4.y = positions[k + i + 4];
  42911. v4.z = positions[k + i + 5];
  42912. // 2D slope V1V4
  42913. cd = (v4.z - v1.z) / (v4.x - v1.x);
  42914. h = v1.z - cd * v1.x; // v1 belongs to the slope
  42915. // facet equations :
  42916. // we compute each facet normal vector
  42917. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  42918. // we compute the value d by applying the equation to v1 which belongs to the plane
  42919. // then we store the facet equation in a Vector4
  42920. v2.subtractToRef(v1, v1v2);
  42921. v3.subtractToRef(v1, v1v3);
  42922. v4.subtractToRef(v1, v1v4);
  42923. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  42924. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  42925. norm1.normalize();
  42926. norm2.normalize();
  42927. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  42928. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  42929. var quad = this._heightQuads[row * subdivisionsX + col];
  42930. quad.slope.copyFromFloats(cd, h);
  42931. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  42932. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  42933. }
  42934. }
  42935. return this;
  42936. };
  42937. GroundMesh.prototype.serialize = function (serializationObject) {
  42938. _super.prototype.serialize.call(this, serializationObject);
  42939. serializationObject.subdivisionsX = this._subdivisionsX;
  42940. serializationObject.subdivisionsY = this._subdivisionsY;
  42941. serializationObject.minX = this._minX;
  42942. serializationObject.maxX = this._maxX;
  42943. serializationObject.minZ = this._minZ;
  42944. serializationObject.maxZ = this._maxZ;
  42945. serializationObject.width = this._width;
  42946. serializationObject.height = this._height;
  42947. };
  42948. GroundMesh.Parse = function (parsedMesh, scene) {
  42949. var result = new GroundMesh(parsedMesh.name, scene);
  42950. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  42951. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  42952. result._minX = parsedMesh.minX;
  42953. result._maxX = parsedMesh.maxX;
  42954. result._minZ = parsedMesh.minZ;
  42955. result._maxZ = parsedMesh.maxZ;
  42956. result._width = parsedMesh.width;
  42957. result._height = parsedMesh.height;
  42958. return result;
  42959. };
  42960. return GroundMesh;
  42961. }(BABYLON.Mesh));
  42962. BABYLON.GroundMesh = GroundMesh;
  42963. })(BABYLON || (BABYLON = {}));
  42964. //# sourceMappingURL=babylon.groundMesh.js.map
  42965. var BABYLON;
  42966. (function (BABYLON) {
  42967. /**
  42968. * Creates an instance based on a source mesh.
  42969. */
  42970. var InstancedMesh = (function (_super) {
  42971. __extends(InstancedMesh, _super);
  42972. function InstancedMesh(name, source) {
  42973. var _this = _super.call(this, name, source.getScene()) || this;
  42974. source.instances.push(_this);
  42975. _this._sourceMesh = source;
  42976. _this.position.copyFrom(source.position);
  42977. _this.rotation.copyFrom(source.rotation);
  42978. _this.scaling.copyFrom(source.scaling);
  42979. if (source.rotationQuaternion) {
  42980. _this.rotationQuaternion = source.rotationQuaternion.clone();
  42981. }
  42982. _this.infiniteDistance = source.infiniteDistance;
  42983. _this.setPivotMatrix(source.getPivotMatrix());
  42984. _this.refreshBoundingInfo();
  42985. _this._syncSubMeshes();
  42986. return _this;
  42987. }
  42988. /**
  42989. * Returns the string "InstancedMesh".
  42990. */
  42991. InstancedMesh.prototype.getClassName = function () {
  42992. return "InstancedMesh";
  42993. };
  42994. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  42995. // Methods
  42996. get: function () {
  42997. return this._sourceMesh.receiveShadows;
  42998. },
  42999. enumerable: true,
  43000. configurable: true
  43001. });
  43002. Object.defineProperty(InstancedMesh.prototype, "material", {
  43003. get: function () {
  43004. return this._sourceMesh.material;
  43005. },
  43006. enumerable: true,
  43007. configurable: true
  43008. });
  43009. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  43010. get: function () {
  43011. return this._sourceMesh.visibility;
  43012. },
  43013. enumerable: true,
  43014. configurable: true
  43015. });
  43016. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  43017. get: function () {
  43018. return this._sourceMesh.skeleton;
  43019. },
  43020. enumerable: true,
  43021. configurable: true
  43022. });
  43023. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  43024. get: function () {
  43025. return this._sourceMesh.renderingGroupId;
  43026. },
  43027. enumerable: true,
  43028. configurable: true
  43029. });
  43030. /**
  43031. * Returns the total number of vertices (integer).
  43032. */
  43033. InstancedMesh.prototype.getTotalVertices = function () {
  43034. return this._sourceMesh.getTotalVertices();
  43035. };
  43036. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  43037. get: function () {
  43038. return this._sourceMesh;
  43039. },
  43040. enumerable: true,
  43041. configurable: true
  43042. });
  43043. /**
  43044. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  43045. */
  43046. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  43047. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  43048. };
  43049. /**
  43050. * Sets the vertex data of the mesh geometry for the requested `kind`.
  43051. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  43052. * The `data` are either a numeric array either a Float32Array.
  43053. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  43054. * 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).
  43055. * Note that a new underlying VertexBuffer object is created each call.
  43056. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  43057. *
  43058. * Possible `kind` values :
  43059. * - BABYLON.VertexBuffer.PositionKind
  43060. * - BABYLON.VertexBuffer.UVKind
  43061. * - BABYLON.VertexBuffer.UV2Kind
  43062. * - BABYLON.VertexBuffer.UV3Kind
  43063. * - BABYLON.VertexBuffer.UV4Kind
  43064. * - BABYLON.VertexBuffer.UV5Kind
  43065. * - BABYLON.VertexBuffer.UV6Kind
  43066. * - BABYLON.VertexBuffer.ColorKind
  43067. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43068. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43069. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43070. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43071. *
  43072. * Returns the Mesh.
  43073. */
  43074. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  43075. if (this.sourceMesh) {
  43076. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  43077. }
  43078. return this.sourceMesh;
  43079. };
  43080. /**
  43081. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  43082. * If the mesh has no geometry, it is simply returned as it is.
  43083. * The `data` are either a numeric array either a Float32Array.
  43084. * No new underlying VertexBuffer object is created.
  43085. * 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.
  43086. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  43087. *
  43088. * Possible `kind` values :
  43089. * - BABYLON.VertexBuffer.PositionKind
  43090. * - BABYLON.VertexBuffer.UVKind
  43091. * - BABYLON.VertexBuffer.UV2Kind
  43092. * - BABYLON.VertexBuffer.UV3Kind
  43093. * - BABYLON.VertexBuffer.UV4Kind
  43094. * - BABYLON.VertexBuffer.UV5Kind
  43095. * - BABYLON.VertexBuffer.UV6Kind
  43096. * - BABYLON.VertexBuffer.ColorKind
  43097. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43098. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43099. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43100. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43101. *
  43102. * Returns the Mesh.
  43103. */
  43104. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  43105. if (this.sourceMesh) {
  43106. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  43107. }
  43108. return this.sourceMesh;
  43109. };
  43110. /**
  43111. * Sets the mesh indices.
  43112. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  43113. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  43114. * This method creates a new index buffer each call.
  43115. * Returns the Mesh.
  43116. */
  43117. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  43118. if (this.sourceMesh) {
  43119. this.sourceMesh.setIndices(indices, totalVertices);
  43120. }
  43121. return this.sourceMesh;
  43122. };
  43123. /**
  43124. * Boolean : True if the mesh owns the requested kind of data.
  43125. */
  43126. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  43127. return this._sourceMesh.isVerticesDataPresent(kind);
  43128. };
  43129. /**
  43130. * Returns an array of indices (IndicesArray).
  43131. */
  43132. InstancedMesh.prototype.getIndices = function () {
  43133. return this._sourceMesh.getIndices();
  43134. };
  43135. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  43136. get: function () {
  43137. return this._sourceMesh._positions;
  43138. },
  43139. enumerable: true,
  43140. configurable: true
  43141. });
  43142. /**
  43143. * Sets a new updated BoundingInfo to the mesh.
  43144. * Returns the mesh.
  43145. */
  43146. InstancedMesh.prototype.refreshBoundingInfo = function () {
  43147. var meshBB = this._sourceMesh.getBoundingInfo();
  43148. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  43149. this._updateBoundingInfo();
  43150. return this;
  43151. };
  43152. InstancedMesh.prototype._preActivate = function () {
  43153. if (this._currentLOD) {
  43154. this._currentLOD._preActivate();
  43155. }
  43156. return this;
  43157. };
  43158. InstancedMesh.prototype._activate = function (renderId) {
  43159. if (this._currentLOD) {
  43160. this._currentLOD._registerInstanceForRenderId(this, renderId);
  43161. }
  43162. return this;
  43163. };
  43164. /**
  43165. * Returns the current associated LOD AbstractMesh.
  43166. */
  43167. InstancedMesh.prototype.getLOD = function (camera) {
  43168. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  43169. if (this._currentLOD === this.sourceMesh) {
  43170. return this;
  43171. }
  43172. return this._currentLOD;
  43173. };
  43174. InstancedMesh.prototype._syncSubMeshes = function () {
  43175. this.releaseSubMeshes();
  43176. if (this._sourceMesh.subMeshes) {
  43177. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  43178. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  43179. }
  43180. }
  43181. return this;
  43182. };
  43183. InstancedMesh.prototype._generatePointsArray = function () {
  43184. return this._sourceMesh._generatePointsArray();
  43185. };
  43186. /**
  43187. * Creates a new InstancedMesh from the current mesh.
  43188. * - name (string) : the cloned mesh name
  43189. * - newParent (optional Node) : the optional Node to parent the clone to.
  43190. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  43191. *
  43192. * Returns the clone.
  43193. */
  43194. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43195. var result = this._sourceMesh.createInstance(name);
  43196. // Deep copy
  43197. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  43198. // Bounding info
  43199. this.refreshBoundingInfo();
  43200. // Parent
  43201. if (newParent) {
  43202. result.parent = newParent;
  43203. }
  43204. if (!doNotCloneChildren) {
  43205. // Children
  43206. for (var index = 0; index < this.getScene().meshes.length; index++) {
  43207. var mesh = this.getScene().meshes[index];
  43208. if (mesh.parent === this) {
  43209. mesh.clone(mesh.name, result);
  43210. }
  43211. }
  43212. }
  43213. result.computeWorldMatrix(true);
  43214. return result;
  43215. };
  43216. /**
  43217. * Disposes the InstancedMesh.
  43218. * Returns nothing.
  43219. */
  43220. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  43221. // Remove from mesh
  43222. var index = this._sourceMesh.instances.indexOf(this);
  43223. this._sourceMesh.instances.splice(index, 1);
  43224. _super.prototype.dispose.call(this, doNotRecurse);
  43225. };
  43226. return InstancedMesh;
  43227. }(BABYLON.AbstractMesh));
  43228. BABYLON.InstancedMesh = InstancedMesh;
  43229. })(BABYLON || (BABYLON = {}));
  43230. //# sourceMappingURL=babylon.instancedMesh.js.map
  43231. /// <reference path="babylon.mesh.ts" />
  43232. var BABYLON;
  43233. (function (BABYLON) {
  43234. var LinesMesh = (function (_super) {
  43235. __extends(LinesMesh, _super);
  43236. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  43237. if (parent === void 0) { parent = null; }
  43238. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  43239. _this.useVertexColor = useVertexColor;
  43240. _this.color = new BABYLON.Color3(1, 1, 1);
  43241. _this.alpha = 1;
  43242. if (source) {
  43243. _this.color = source.color.clone();
  43244. _this.alpha = source.alpha;
  43245. _this.useVertexColor = source.useVertexColor;
  43246. }
  43247. _this._intersectionThreshold = 0.1;
  43248. var options = {
  43249. attributes: [BABYLON.VertexBuffer.PositionKind],
  43250. uniforms: ["world", "viewProjection"],
  43251. needAlphaBlending: false,
  43252. };
  43253. if (!useVertexColor) {
  43254. options.uniforms.push("color");
  43255. options.needAlphaBlending = true;
  43256. }
  43257. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  43258. return _this;
  43259. }
  43260. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  43261. /**
  43262. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43263. * This margin is expressed in world space coordinates, so its value may vary.
  43264. * Default value is 0.1
  43265. * @returns the intersection Threshold value.
  43266. */
  43267. get: function () {
  43268. return this._intersectionThreshold;
  43269. },
  43270. /**
  43271. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43272. * This margin is expressed in world space coordinates, so its value may vary.
  43273. * @param value the new threshold to apply
  43274. */
  43275. set: function (value) {
  43276. if (this._intersectionThreshold === value) {
  43277. return;
  43278. }
  43279. this._intersectionThreshold = value;
  43280. if (this.geometry) {
  43281. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  43282. }
  43283. },
  43284. enumerable: true,
  43285. configurable: true
  43286. });
  43287. /**
  43288. * Returns the string "LineMesh"
  43289. */
  43290. LinesMesh.prototype.getClassName = function () {
  43291. return "LinesMesh";
  43292. };
  43293. Object.defineProperty(LinesMesh.prototype, "material", {
  43294. get: function () {
  43295. return this._colorShader;
  43296. },
  43297. enumerable: true,
  43298. configurable: true
  43299. });
  43300. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  43301. get: function () {
  43302. return false;
  43303. },
  43304. enumerable: true,
  43305. configurable: true
  43306. });
  43307. LinesMesh.prototype.createInstance = function (name) {
  43308. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  43309. return null;
  43310. };
  43311. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  43312. // VBOs
  43313. this._geometry._bind(this._colorShader.getEffect());
  43314. // Color
  43315. if (!this.useVertexColor) {
  43316. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  43317. }
  43318. return this;
  43319. };
  43320. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  43321. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  43322. return this;
  43323. }
  43324. var engine = this.getScene().getEngine();
  43325. // Draw order
  43326. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  43327. return this;
  43328. };
  43329. LinesMesh.prototype.dispose = function (doNotRecurse) {
  43330. this._colorShader.dispose();
  43331. _super.prototype.dispose.call(this, doNotRecurse);
  43332. };
  43333. /**
  43334. * Returns a new LineMesh object cloned from the current one.
  43335. */
  43336. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43337. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  43338. };
  43339. return LinesMesh;
  43340. }(BABYLON.Mesh));
  43341. BABYLON.LinesMesh = LinesMesh;
  43342. })(BABYLON || (BABYLON = {}));
  43343. //# sourceMappingURL=babylon.linesMesh.js.map
  43344. var BABYLON;
  43345. (function (BABYLON) {
  43346. var StandardMaterialDefines = (function (_super) {
  43347. __extends(StandardMaterialDefines, _super);
  43348. function StandardMaterialDefines() {
  43349. var _this = _super.call(this) || this;
  43350. _this.MAINUV1 = false;
  43351. _this.MAINUV2 = false;
  43352. _this.DIFFUSE = false;
  43353. _this.DIFFUSEDIRECTUV = 0;
  43354. _this.AMBIENT = false;
  43355. _this.AMBIENTDIRECTUV = 0;
  43356. _this.OPACITY = false;
  43357. _this.OPACITYDIRECTUV = 0;
  43358. _this.OPACITYRGB = false;
  43359. _this.REFLECTION = false;
  43360. _this.EMISSIVE = false;
  43361. _this.EMISSIVEDIRECTUV = 0;
  43362. _this.SPECULAR = false;
  43363. _this.SPECULARDIRECTUV = 0;
  43364. _this.BUMP = false;
  43365. _this.BUMPDIRECTUV = 0;
  43366. _this.PARALLAX = false;
  43367. _this.PARALLAXOCCLUSION = false;
  43368. _this.SPECULAROVERALPHA = false;
  43369. _this.CLIPPLANE = false;
  43370. _this.ALPHATEST = false;
  43371. _this.ALPHAFROMDIFFUSE = false;
  43372. _this.POINTSIZE = false;
  43373. _this.FOG = false;
  43374. _this.SPECULARTERM = false;
  43375. _this.DIFFUSEFRESNEL = false;
  43376. _this.OPACITYFRESNEL = false;
  43377. _this.REFLECTIONFRESNEL = false;
  43378. _this.REFRACTIONFRESNEL = false;
  43379. _this.EMISSIVEFRESNEL = false;
  43380. _this.FRESNEL = false;
  43381. _this.NORMAL = false;
  43382. _this.UV1 = false;
  43383. _this.UV2 = false;
  43384. _this.VERTEXCOLOR = false;
  43385. _this.VERTEXALPHA = false;
  43386. _this.NUM_BONE_INFLUENCERS = 0;
  43387. _this.BonesPerMesh = 0;
  43388. _this.INSTANCES = false;
  43389. _this.GLOSSINESS = false;
  43390. _this.ROUGHNESS = false;
  43391. _this.EMISSIVEASILLUMINATION = false;
  43392. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43393. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43394. _this.LIGHTMAP = false;
  43395. _this.LIGHTMAPDIRECTUV = 0;
  43396. _this.USELIGHTMAPASSHADOWMAP = false;
  43397. _this.REFLECTIONMAP_3D = false;
  43398. _this.REFLECTIONMAP_SPHERICAL = false;
  43399. _this.REFLECTIONMAP_PLANAR = false;
  43400. _this.REFLECTIONMAP_CUBIC = false;
  43401. _this.REFLECTIONMAP_PROJECTION = false;
  43402. _this.REFLECTIONMAP_SKYBOX = false;
  43403. _this.REFLECTIONMAP_EXPLICIT = false;
  43404. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43405. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43406. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43407. _this.INVERTCUBICMAP = false;
  43408. _this.LOGARITHMICDEPTH = false;
  43409. _this.REFRACTION = false;
  43410. _this.REFRACTIONMAP_3D = false;
  43411. _this.REFLECTIONOVERALPHA = false;
  43412. _this.TWOSIDEDLIGHTING = false;
  43413. _this.SHADOWFLOAT = false;
  43414. _this.MORPHTARGETS = false;
  43415. _this.MORPHTARGETS_NORMAL = false;
  43416. _this.MORPHTARGETS_TANGENT = false;
  43417. _this.NUM_MORPH_INFLUENCERS = 0;
  43418. _this.USERIGHTHANDEDSYSTEM = false;
  43419. _this.IMAGEPROCESSING = false;
  43420. _this.VIGNETTE = false;
  43421. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43422. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43423. _this.TONEMAPPING = false;
  43424. _this.CONTRAST = false;
  43425. _this.COLORCURVES = false;
  43426. _this.COLORGRADING = false;
  43427. _this.SAMPLER3DGREENDEPTH = false;
  43428. _this.SAMPLER3DBGRMAP = false;
  43429. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43430. _this.EXPOSURE = false;
  43431. _this.rebuild();
  43432. return _this;
  43433. }
  43434. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43435. var modes = [
  43436. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43437. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43438. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43439. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43440. ];
  43441. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43442. var mode = modes_1[_i];
  43443. this[mode] = (mode === modeToEnable);
  43444. }
  43445. };
  43446. return StandardMaterialDefines;
  43447. }(BABYLON.MaterialDefines));
  43448. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43449. var StandardMaterial = (function (_super) {
  43450. __extends(StandardMaterial, _super);
  43451. function StandardMaterial(name, scene) {
  43452. var _this = _super.call(this, name, scene) || this;
  43453. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43454. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43455. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43456. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43457. _this.specularPower = 64;
  43458. _this._useAlphaFromDiffuseTexture = false;
  43459. _this._useEmissiveAsIllumination = false;
  43460. _this._linkEmissiveWithDiffuse = false;
  43461. _this._useSpecularOverAlpha = false;
  43462. _this._useReflectionOverAlpha = false;
  43463. _this._disableLighting = false;
  43464. _this._useParallax = false;
  43465. _this._useParallaxOcclusion = false;
  43466. _this.parallaxScaleBias = 0.05;
  43467. _this._roughness = 0;
  43468. _this.indexOfRefraction = 0.98;
  43469. _this.invertRefractionY = true;
  43470. _this._useLightmapAsShadowmap = false;
  43471. _this._useReflectionFresnelFromSpecular = false;
  43472. _this._useGlossinessFromSpecularMapAlpha = false;
  43473. _this._maxSimultaneousLights = 4;
  43474. /**
  43475. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43476. */
  43477. _this._invertNormalMapX = false;
  43478. /**
  43479. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43480. */
  43481. _this._invertNormalMapY = false;
  43482. /**
  43483. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43484. */
  43485. _this._twoSidedLighting = false;
  43486. _this._renderTargets = new BABYLON.SmartArray(16);
  43487. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43488. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43489. // Setup the default processing configuration to the scene.
  43490. _this._attachImageProcessingConfiguration(null);
  43491. _this.getRenderTargetTextures = function () {
  43492. _this._renderTargets.reset();
  43493. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43494. _this._renderTargets.push(_this._reflectionTexture);
  43495. }
  43496. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43497. _this._renderTargets.push(_this._refractionTexture);
  43498. }
  43499. return _this._renderTargets;
  43500. };
  43501. return _this;
  43502. }
  43503. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43504. /**
  43505. * Gets the image processing configuration used either in this material.
  43506. */
  43507. get: function () {
  43508. return this._imageProcessingConfiguration;
  43509. },
  43510. /**
  43511. * Sets the Default image processing configuration used either in the this material.
  43512. *
  43513. * If sets to null, the scene one is in use.
  43514. */
  43515. set: function (value) {
  43516. this._attachImageProcessingConfiguration(value);
  43517. // Ensure the effect will be rebuilt.
  43518. this._markAllSubMeshesAsTexturesDirty();
  43519. },
  43520. enumerable: true,
  43521. configurable: true
  43522. });
  43523. /**
  43524. * Attaches a new image processing configuration to the Standard Material.
  43525. * @param configuration
  43526. */
  43527. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43528. var _this = this;
  43529. if (configuration === this._imageProcessingConfiguration) {
  43530. return;
  43531. }
  43532. // Detaches observer.
  43533. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43534. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43535. }
  43536. // Pick the scene configuration if needed.
  43537. if (!configuration) {
  43538. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43539. }
  43540. else {
  43541. this._imageProcessingConfiguration = configuration;
  43542. }
  43543. // Attaches observer.
  43544. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43545. _this._markAllSubMeshesAsImageProcessingDirty();
  43546. });
  43547. };
  43548. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43549. /**
  43550. * Gets wether the color curves effect is enabled.
  43551. */
  43552. get: function () {
  43553. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43554. },
  43555. /**
  43556. * Sets wether the color curves effect is enabled.
  43557. */
  43558. set: function (value) {
  43559. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43560. },
  43561. enumerable: true,
  43562. configurable: true
  43563. });
  43564. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43565. /**
  43566. * Gets wether the color grading effect is enabled.
  43567. */
  43568. get: function () {
  43569. return this.imageProcessingConfiguration.colorGradingEnabled;
  43570. },
  43571. /**
  43572. * Gets wether the color grading effect is enabled.
  43573. */
  43574. set: function (value) {
  43575. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43576. },
  43577. enumerable: true,
  43578. configurable: true
  43579. });
  43580. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43581. /**
  43582. * Gets wether tonemapping is enabled or not.
  43583. */
  43584. get: function () {
  43585. return this._imageProcessingConfiguration.toneMappingEnabled;
  43586. },
  43587. /**
  43588. * Sets wether tonemapping is enabled or not
  43589. */
  43590. set: function (value) {
  43591. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43592. },
  43593. enumerable: true,
  43594. configurable: true
  43595. });
  43596. ;
  43597. ;
  43598. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43599. /**
  43600. * The camera exposure used on this material.
  43601. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43602. * This corresponds to a photographic exposure.
  43603. */
  43604. get: function () {
  43605. return this._imageProcessingConfiguration.exposure;
  43606. },
  43607. /**
  43608. * The camera exposure used on this material.
  43609. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43610. * This corresponds to a photographic exposure.
  43611. */
  43612. set: function (value) {
  43613. this._imageProcessingConfiguration.exposure = value;
  43614. },
  43615. enumerable: true,
  43616. configurable: true
  43617. });
  43618. ;
  43619. ;
  43620. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43621. /**
  43622. * Gets The camera contrast used on this material.
  43623. */
  43624. get: function () {
  43625. return this._imageProcessingConfiguration.contrast;
  43626. },
  43627. /**
  43628. * Sets The camera contrast used on this material.
  43629. */
  43630. set: function (value) {
  43631. this._imageProcessingConfiguration.contrast = value;
  43632. },
  43633. enumerable: true,
  43634. configurable: true
  43635. });
  43636. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43637. /**
  43638. * Gets the Color Grading 2D Lookup Texture.
  43639. */
  43640. get: function () {
  43641. return this._imageProcessingConfiguration.colorGradingTexture;
  43642. },
  43643. /**
  43644. * Sets the Color Grading 2D Lookup Texture.
  43645. */
  43646. set: function (value) {
  43647. this._imageProcessingConfiguration.colorGradingTexture = value;
  43648. },
  43649. enumerable: true,
  43650. configurable: true
  43651. });
  43652. StandardMaterial.prototype.getClassName = function () {
  43653. return "StandardMaterial";
  43654. };
  43655. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43656. get: function () {
  43657. return this._useLogarithmicDepth;
  43658. },
  43659. set: function (value) {
  43660. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43661. this._markAllSubMeshesAsMiscDirty();
  43662. },
  43663. enumerable: true,
  43664. configurable: true
  43665. });
  43666. StandardMaterial.prototype.needAlphaBlending = function () {
  43667. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43668. };
  43669. StandardMaterial.prototype.needAlphaTesting = function () {
  43670. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43671. };
  43672. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43673. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43674. };
  43675. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43676. return this._diffuseTexture;
  43677. };
  43678. /**
  43679. * Child classes can use it to update shaders
  43680. */
  43681. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43682. if (this.isFrozen) {
  43683. if (this._wasPreviouslyReady && subMesh.effect) {
  43684. return true;
  43685. }
  43686. }
  43687. if (!subMesh._materialDefines) {
  43688. subMesh._materialDefines = new StandardMaterialDefines();
  43689. }
  43690. var scene = this.getScene();
  43691. var defines = subMesh._materialDefines;
  43692. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43693. if (defines._renderId === scene.getRenderId()) {
  43694. return true;
  43695. }
  43696. }
  43697. var engine = scene.getEngine();
  43698. // Lights
  43699. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43700. // Textures
  43701. if (defines._areTexturesDirty) {
  43702. defines._needUVs = false;
  43703. defines.MAINUV1 = false;
  43704. defines.MAINUV2 = false;
  43705. if (scene.texturesEnabled) {
  43706. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43707. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43708. return false;
  43709. }
  43710. else {
  43711. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43712. }
  43713. }
  43714. else {
  43715. defines.DIFFUSE = false;
  43716. }
  43717. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43718. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43719. return false;
  43720. }
  43721. else {
  43722. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43723. }
  43724. }
  43725. else {
  43726. defines.AMBIENT = false;
  43727. }
  43728. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43729. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43730. return false;
  43731. }
  43732. else {
  43733. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43734. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43735. }
  43736. }
  43737. else {
  43738. defines.OPACITY = false;
  43739. }
  43740. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43741. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43742. return false;
  43743. }
  43744. else {
  43745. defines._needNormals = true;
  43746. defines.REFLECTION = true;
  43747. defines.ROUGHNESS = (this._roughness > 0);
  43748. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43749. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43750. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43751. switch (this._reflectionTexture.coordinatesMode) {
  43752. case BABYLON.Texture.CUBIC_MODE:
  43753. case BABYLON.Texture.INVCUBIC_MODE:
  43754. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43755. break;
  43756. case BABYLON.Texture.EXPLICIT_MODE:
  43757. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43758. break;
  43759. case BABYLON.Texture.PLANAR_MODE:
  43760. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43761. break;
  43762. case BABYLON.Texture.PROJECTION_MODE:
  43763. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43764. break;
  43765. case BABYLON.Texture.SKYBOX_MODE:
  43766. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43767. break;
  43768. case BABYLON.Texture.SPHERICAL_MODE:
  43769. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43770. break;
  43771. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43772. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43773. break;
  43774. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43775. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43776. break;
  43777. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43778. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43779. break;
  43780. }
  43781. }
  43782. }
  43783. else {
  43784. defines.REFLECTION = false;
  43785. }
  43786. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43787. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43788. return false;
  43789. }
  43790. else {
  43791. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43792. }
  43793. }
  43794. else {
  43795. defines.EMISSIVE = false;
  43796. }
  43797. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43798. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43799. return false;
  43800. }
  43801. else {
  43802. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43803. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43804. }
  43805. }
  43806. else {
  43807. defines.LIGHTMAP = false;
  43808. }
  43809. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43810. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43811. return false;
  43812. }
  43813. else {
  43814. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43815. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43816. }
  43817. }
  43818. else {
  43819. defines.SPECULAR = false;
  43820. }
  43821. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43822. // Bump texure can not be not blocking.
  43823. if (!this._bumpTexture.isReady()) {
  43824. return false;
  43825. }
  43826. else {
  43827. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43828. defines.PARALLAX = this._useParallax;
  43829. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43830. }
  43831. }
  43832. else {
  43833. defines.BUMP = false;
  43834. }
  43835. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43836. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43837. return false;
  43838. }
  43839. else {
  43840. defines._needUVs = true;
  43841. defines.REFRACTION = true;
  43842. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43843. }
  43844. }
  43845. else {
  43846. defines.REFRACTION = false;
  43847. }
  43848. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43849. }
  43850. else {
  43851. defines.DIFFUSE = false;
  43852. defines.AMBIENT = false;
  43853. defines.OPACITY = false;
  43854. defines.REFLECTION = false;
  43855. defines.EMISSIVE = false;
  43856. defines.LIGHTMAP = false;
  43857. defines.BUMP = false;
  43858. defines.REFRACTION = false;
  43859. }
  43860. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43861. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43862. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43863. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43864. }
  43865. if (defines._areImageProcessingDirty) {
  43866. if (!this._imageProcessingConfiguration.isReady()) {
  43867. return false;
  43868. }
  43869. this._imageProcessingConfiguration.prepareDefines(defines);
  43870. }
  43871. if (defines._areFresnelDirty) {
  43872. if (StandardMaterial.FresnelEnabled) {
  43873. // Fresnel
  43874. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43875. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43876. this._reflectionFresnelParameters) {
  43877. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43878. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43879. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43880. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43881. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43882. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43883. defines._needNormals = true;
  43884. defines.FRESNEL = true;
  43885. }
  43886. }
  43887. else {
  43888. defines.FRESNEL = false;
  43889. }
  43890. }
  43891. // Misc.
  43892. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  43893. // Attribs
  43894. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43895. // Values that need to be evaluated on every frame
  43896. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43897. // Get correct effect
  43898. if (defines.isDirty) {
  43899. defines.markAsProcessed();
  43900. scene.resetCachedMaterial();
  43901. // Fallbacks
  43902. var fallbacks = new BABYLON.EffectFallbacks();
  43903. if (defines.REFLECTION) {
  43904. fallbacks.addFallback(0, "REFLECTION");
  43905. }
  43906. if (defines.SPECULAR) {
  43907. fallbacks.addFallback(0, "SPECULAR");
  43908. }
  43909. if (defines.BUMP) {
  43910. fallbacks.addFallback(0, "BUMP");
  43911. }
  43912. if (defines.PARALLAX) {
  43913. fallbacks.addFallback(1, "PARALLAX");
  43914. }
  43915. if (defines.PARALLAXOCCLUSION) {
  43916. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43917. }
  43918. if (defines.SPECULAROVERALPHA) {
  43919. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43920. }
  43921. if (defines.FOG) {
  43922. fallbacks.addFallback(1, "FOG");
  43923. }
  43924. if (defines.POINTSIZE) {
  43925. fallbacks.addFallback(0, "POINTSIZE");
  43926. }
  43927. if (defines.LOGARITHMICDEPTH) {
  43928. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43929. }
  43930. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43931. if (defines.SPECULARTERM) {
  43932. fallbacks.addFallback(0, "SPECULARTERM");
  43933. }
  43934. if (defines.DIFFUSEFRESNEL) {
  43935. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43936. }
  43937. if (defines.OPACITYFRESNEL) {
  43938. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43939. }
  43940. if (defines.REFLECTIONFRESNEL) {
  43941. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43942. }
  43943. if (defines.EMISSIVEFRESNEL) {
  43944. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43945. }
  43946. if (defines.FRESNEL) {
  43947. fallbacks.addFallback(4, "FRESNEL");
  43948. }
  43949. //Attributes
  43950. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43951. if (defines.NORMAL) {
  43952. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43953. }
  43954. if (defines.UV1) {
  43955. attribs.push(BABYLON.VertexBuffer.UVKind);
  43956. }
  43957. if (defines.UV2) {
  43958. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43959. }
  43960. if (defines.VERTEXCOLOR) {
  43961. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43962. }
  43963. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43964. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43965. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43966. var shaderName = "default";
  43967. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43968. "vFogInfos", "vFogColor", "pointSize",
  43969. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43970. "mBones",
  43971. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43972. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43973. "logarithmicDepthConstant", "vNormalReoderParams"
  43974. ];
  43975. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43976. var uniformBuffers = ["Material", "Scene"];
  43977. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43978. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43979. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43980. uniformsNames: uniforms,
  43981. uniformBuffersNames: uniformBuffers,
  43982. samplers: samplers,
  43983. defines: defines,
  43984. maxSimultaneousLights: this._maxSimultaneousLights
  43985. });
  43986. if (this.customShaderNameResolve) {
  43987. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43988. }
  43989. var join = defines.toString();
  43990. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43991. attributes: attribs,
  43992. uniformsNames: uniforms,
  43993. uniformBuffersNames: uniformBuffers,
  43994. samplers: samplers,
  43995. defines: join,
  43996. fallbacks: fallbacks,
  43997. onCompiled: this.onCompiled,
  43998. onError: this.onError,
  43999. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44000. }, engine), defines);
  44001. this.buildUniformLayout();
  44002. }
  44003. if (!subMesh.effect.isReady()) {
  44004. return false;
  44005. }
  44006. defines._renderId = scene.getRenderId();
  44007. this._wasPreviouslyReady = true;
  44008. return true;
  44009. };
  44010. StandardMaterial.prototype.buildUniformLayout = function () {
  44011. // Order is important !
  44012. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  44013. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  44014. this._uniformBuffer.addUniform("opacityParts", 4);
  44015. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  44016. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  44017. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  44018. this._uniformBuffer.addUniform("refractionRightColor", 4);
  44019. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  44020. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  44021. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  44022. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  44023. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44024. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44025. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44026. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44027. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  44028. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44029. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  44030. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44031. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44032. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44033. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44034. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44035. this._uniformBuffer.addUniform("specularMatrix", 16);
  44036. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44037. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  44038. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44039. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44040. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44041. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44042. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44043. this._uniformBuffer.addUniform("pointSize", 1);
  44044. this._uniformBuffer.create();
  44045. };
  44046. StandardMaterial.prototype.unbind = function () {
  44047. if (this._activeEffect) {
  44048. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44049. this._activeEffect.setTexture("reflection2DSampler", null);
  44050. }
  44051. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44052. this._activeEffect.setTexture("refraction2DSampler", null);
  44053. }
  44054. }
  44055. _super.prototype.unbind.call(this);
  44056. };
  44057. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44058. var scene = this.getScene();
  44059. var defines = subMesh._materialDefines;
  44060. if (!defines) {
  44061. return;
  44062. }
  44063. var effect = subMesh.effect;
  44064. this._activeEffect = effect;
  44065. // Matrices
  44066. this.bindOnlyWorldMatrix(world);
  44067. // Bones
  44068. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44069. if (this._mustRebind(scene, effect, mesh.visibility)) {
  44070. this._uniformBuffer.bindToEffect(effect, "Material");
  44071. this.bindViewProjection(effect);
  44072. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44073. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44074. // Fresnel
  44075. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44076. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44077. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44078. }
  44079. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44080. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44081. }
  44082. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44083. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44084. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44085. }
  44086. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44087. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44088. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44089. }
  44090. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44091. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44092. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44093. }
  44094. }
  44095. // Textures
  44096. if (scene.texturesEnabled) {
  44097. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44098. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44099. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44100. }
  44101. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44102. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44103. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44104. }
  44105. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44106. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44107. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44108. }
  44109. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44110. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44111. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44112. }
  44113. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44114. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44115. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44116. }
  44117. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44118. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44119. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44120. }
  44121. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44122. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44123. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44124. }
  44125. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44126. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44127. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44128. if (scene._mirroredCameraPosition) {
  44129. this._uniformBuffer.updateFloat4("vNormalReoderParams", this.invertNormalMapX ? 0 : 1.0, this.invertNormalMapX ? 1.0 : -1.0, this.invertNormalMapY ? 0 : 1.0, this.invertNormalMapY ? 1.0 : -1.0);
  44130. }
  44131. else {
  44132. this._uniformBuffer.updateFloat4("vNormalReoderParams", this.invertNormalMapX ? 1.0 : 0, this.invertNormalMapX ? -1.0 : 1.0, this.invertNormalMapY ? 1.0 : 0, this.invertNormalMapY ? -1.0 : 1.0);
  44133. }
  44134. }
  44135. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44136. var depth = 1.0;
  44137. if (!this._refractionTexture.isCube) {
  44138. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44139. if (this._refractionTexture.depth) {
  44140. depth = this._refractionTexture.depth;
  44141. }
  44142. }
  44143. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44144. }
  44145. }
  44146. // Point size
  44147. if (this.pointsCloud) {
  44148. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44149. }
  44150. if (defines.SPECULARTERM) {
  44151. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44152. }
  44153. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44154. // Diffuse
  44155. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44156. }
  44157. // Textures
  44158. if (scene.texturesEnabled) {
  44159. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44160. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44161. }
  44162. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44163. effect.setTexture("ambientSampler", this._ambientTexture);
  44164. }
  44165. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44166. effect.setTexture("opacitySampler", this._opacityTexture);
  44167. }
  44168. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44169. if (this._reflectionTexture.isCube) {
  44170. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44171. }
  44172. else {
  44173. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44174. }
  44175. }
  44176. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44177. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44178. }
  44179. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44180. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44181. }
  44182. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44183. effect.setTexture("specularSampler", this._specularTexture);
  44184. }
  44185. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44186. effect.setTexture("bumpSampler", this._bumpTexture);
  44187. }
  44188. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44189. var depth = 1.0;
  44190. if (this._refractionTexture.isCube) {
  44191. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44192. }
  44193. else {
  44194. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44195. }
  44196. }
  44197. }
  44198. // Clip plane
  44199. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44200. // Colors
  44201. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44202. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44203. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44204. }
  44205. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  44206. // Lights
  44207. if (scene.lightsEnabled && !this._disableLighting) {
  44208. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44209. }
  44210. // View
  44211. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44212. this.bindView(effect);
  44213. }
  44214. // Fog
  44215. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44216. // Morph targets
  44217. if (defines.NUM_MORPH_INFLUENCERS) {
  44218. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44219. }
  44220. // Log. depth
  44221. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44222. // image processing
  44223. this._imageProcessingConfiguration.bind(this._activeEffect);
  44224. }
  44225. this._uniformBuffer.update();
  44226. this._afterBind(mesh, this._activeEffect);
  44227. };
  44228. StandardMaterial.prototype.getAnimatables = function () {
  44229. var results = [];
  44230. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44231. results.push(this._diffuseTexture);
  44232. }
  44233. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44234. results.push(this._ambientTexture);
  44235. }
  44236. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44237. results.push(this._opacityTexture);
  44238. }
  44239. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44240. results.push(this._reflectionTexture);
  44241. }
  44242. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44243. results.push(this._emissiveTexture);
  44244. }
  44245. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44246. results.push(this._specularTexture);
  44247. }
  44248. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44249. results.push(this._bumpTexture);
  44250. }
  44251. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44252. results.push(this._lightmapTexture);
  44253. }
  44254. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44255. results.push(this._refractionTexture);
  44256. }
  44257. return results;
  44258. };
  44259. StandardMaterial.prototype.getActiveTextures = function () {
  44260. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44261. if (this._diffuseTexture) {
  44262. activeTextures.push(this._diffuseTexture);
  44263. }
  44264. if (this._ambientTexture) {
  44265. activeTextures.push(this._ambientTexture);
  44266. }
  44267. if (this._opacityTexture) {
  44268. activeTextures.push(this._opacityTexture);
  44269. }
  44270. if (this._reflectionTexture) {
  44271. activeTextures.push(this._reflectionTexture);
  44272. }
  44273. if (this._emissiveTexture) {
  44274. activeTextures.push(this._emissiveTexture);
  44275. }
  44276. if (this._specularTexture) {
  44277. activeTextures.push(this._specularTexture);
  44278. }
  44279. if (this._bumpTexture) {
  44280. activeTextures.push(this._bumpTexture);
  44281. }
  44282. if (this._lightmapTexture) {
  44283. activeTextures.push(this._lightmapTexture);
  44284. }
  44285. if (this._refractionTexture) {
  44286. activeTextures.push(this._refractionTexture);
  44287. }
  44288. return activeTextures;
  44289. };
  44290. StandardMaterial.prototype.hasTexture = function (texture) {
  44291. if (_super.prototype.hasTexture.call(this, texture)) {
  44292. return true;
  44293. }
  44294. if (this._diffuseTexture === texture) {
  44295. return true;
  44296. }
  44297. if (this._ambientTexture === texture) {
  44298. return true;
  44299. }
  44300. if (this._opacityTexture === texture) {
  44301. return true;
  44302. }
  44303. if (this._reflectionTexture === texture) {
  44304. return true;
  44305. }
  44306. if (this._emissiveTexture === texture) {
  44307. return true;
  44308. }
  44309. if (this._specularTexture === texture) {
  44310. return true;
  44311. }
  44312. if (this._bumpTexture === texture) {
  44313. return true;
  44314. }
  44315. if (this._lightmapTexture === texture) {
  44316. return true;
  44317. }
  44318. if (this._refractionTexture === texture) {
  44319. return true;
  44320. }
  44321. return false;
  44322. };
  44323. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44324. if (forceDisposeTextures) {
  44325. if (this._diffuseTexture) {
  44326. this._diffuseTexture.dispose();
  44327. }
  44328. if (this._ambientTexture) {
  44329. this._ambientTexture.dispose();
  44330. }
  44331. if (this._opacityTexture) {
  44332. this._opacityTexture.dispose();
  44333. }
  44334. if (this._reflectionTexture) {
  44335. this._reflectionTexture.dispose();
  44336. }
  44337. if (this._emissiveTexture) {
  44338. this._emissiveTexture.dispose();
  44339. }
  44340. if (this._specularTexture) {
  44341. this._specularTexture.dispose();
  44342. }
  44343. if (this._bumpTexture) {
  44344. this._bumpTexture.dispose();
  44345. }
  44346. if (this._lightmapTexture) {
  44347. this._lightmapTexture.dispose();
  44348. }
  44349. if (this._refractionTexture) {
  44350. this._refractionTexture.dispose();
  44351. }
  44352. }
  44353. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44354. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44355. }
  44356. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44357. };
  44358. StandardMaterial.prototype.clone = function (name) {
  44359. var _this = this;
  44360. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44361. result.name = name;
  44362. result.id = name;
  44363. return result;
  44364. };
  44365. StandardMaterial.prototype.serialize = function () {
  44366. return BABYLON.SerializationHelper.Serialize(this);
  44367. };
  44368. // Statics
  44369. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44370. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44371. };
  44372. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44373. get: function () {
  44374. return StandardMaterial._DiffuseTextureEnabled;
  44375. },
  44376. set: function (value) {
  44377. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44378. return;
  44379. }
  44380. StandardMaterial._DiffuseTextureEnabled = value;
  44381. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44382. },
  44383. enumerable: true,
  44384. configurable: true
  44385. });
  44386. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44387. get: function () {
  44388. return StandardMaterial._AmbientTextureEnabled;
  44389. },
  44390. set: function (value) {
  44391. if (StandardMaterial._AmbientTextureEnabled === value) {
  44392. return;
  44393. }
  44394. StandardMaterial._AmbientTextureEnabled = value;
  44395. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44396. },
  44397. enumerable: true,
  44398. configurable: true
  44399. });
  44400. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44401. get: function () {
  44402. return StandardMaterial._OpacityTextureEnabled;
  44403. },
  44404. set: function (value) {
  44405. if (StandardMaterial._OpacityTextureEnabled === value) {
  44406. return;
  44407. }
  44408. StandardMaterial._OpacityTextureEnabled = value;
  44409. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44410. },
  44411. enumerable: true,
  44412. configurable: true
  44413. });
  44414. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44415. get: function () {
  44416. return StandardMaterial._ReflectionTextureEnabled;
  44417. },
  44418. set: function (value) {
  44419. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44420. return;
  44421. }
  44422. StandardMaterial._ReflectionTextureEnabled = value;
  44423. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44424. },
  44425. enumerable: true,
  44426. configurable: true
  44427. });
  44428. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44429. get: function () {
  44430. return StandardMaterial._EmissiveTextureEnabled;
  44431. },
  44432. set: function (value) {
  44433. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44434. return;
  44435. }
  44436. StandardMaterial._EmissiveTextureEnabled = value;
  44437. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44438. },
  44439. enumerable: true,
  44440. configurable: true
  44441. });
  44442. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44443. get: function () {
  44444. return StandardMaterial._SpecularTextureEnabled;
  44445. },
  44446. set: function (value) {
  44447. if (StandardMaterial._SpecularTextureEnabled === value) {
  44448. return;
  44449. }
  44450. StandardMaterial._SpecularTextureEnabled = value;
  44451. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44452. },
  44453. enumerable: true,
  44454. configurable: true
  44455. });
  44456. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44457. get: function () {
  44458. return StandardMaterial._BumpTextureEnabled;
  44459. },
  44460. set: function (value) {
  44461. if (StandardMaterial._BumpTextureEnabled === value) {
  44462. return;
  44463. }
  44464. StandardMaterial._BumpTextureEnabled = value;
  44465. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44466. },
  44467. enumerable: true,
  44468. configurable: true
  44469. });
  44470. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44471. get: function () {
  44472. return StandardMaterial._LightmapTextureEnabled;
  44473. },
  44474. set: function (value) {
  44475. if (StandardMaterial._LightmapTextureEnabled === value) {
  44476. return;
  44477. }
  44478. StandardMaterial._LightmapTextureEnabled = value;
  44479. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44480. },
  44481. enumerable: true,
  44482. configurable: true
  44483. });
  44484. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44485. get: function () {
  44486. return StandardMaterial._RefractionTextureEnabled;
  44487. },
  44488. set: function (value) {
  44489. if (StandardMaterial._RefractionTextureEnabled === value) {
  44490. return;
  44491. }
  44492. StandardMaterial._RefractionTextureEnabled = value;
  44493. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44494. },
  44495. enumerable: true,
  44496. configurable: true
  44497. });
  44498. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44499. get: function () {
  44500. return StandardMaterial._ColorGradingTextureEnabled;
  44501. },
  44502. set: function (value) {
  44503. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44504. return;
  44505. }
  44506. StandardMaterial._ColorGradingTextureEnabled = value;
  44507. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44508. },
  44509. enumerable: true,
  44510. configurable: true
  44511. });
  44512. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44513. get: function () {
  44514. return StandardMaterial._FresnelEnabled;
  44515. },
  44516. set: function (value) {
  44517. if (StandardMaterial._FresnelEnabled === value) {
  44518. return;
  44519. }
  44520. StandardMaterial._FresnelEnabled = value;
  44521. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44522. },
  44523. enumerable: true,
  44524. configurable: true
  44525. });
  44526. // Flags used to enable or disable a type of texture for all Standard Materials
  44527. StandardMaterial._DiffuseTextureEnabled = true;
  44528. StandardMaterial._AmbientTextureEnabled = true;
  44529. StandardMaterial._OpacityTextureEnabled = true;
  44530. StandardMaterial._ReflectionTextureEnabled = true;
  44531. StandardMaterial._EmissiveTextureEnabled = true;
  44532. StandardMaterial._SpecularTextureEnabled = true;
  44533. StandardMaterial._BumpTextureEnabled = true;
  44534. StandardMaterial._LightmapTextureEnabled = true;
  44535. StandardMaterial._RefractionTextureEnabled = true;
  44536. StandardMaterial._ColorGradingTextureEnabled = true;
  44537. StandardMaterial._FresnelEnabled = true;
  44538. __decorate([
  44539. BABYLON.serializeAsTexture("diffuseTexture")
  44540. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44541. __decorate([
  44542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44543. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44544. __decorate([
  44545. BABYLON.serializeAsTexture("ambientTexture")
  44546. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44547. __decorate([
  44548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44549. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44550. __decorate([
  44551. BABYLON.serializeAsTexture("opacityTexture")
  44552. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44553. __decorate([
  44554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44555. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44556. __decorate([
  44557. BABYLON.serializeAsTexture("reflectionTexture")
  44558. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44559. __decorate([
  44560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44561. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44562. __decorate([
  44563. BABYLON.serializeAsTexture("emissiveTexture")
  44564. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44565. __decorate([
  44566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44567. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44568. __decorate([
  44569. BABYLON.serializeAsTexture("specularTexture")
  44570. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44571. __decorate([
  44572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44573. ], StandardMaterial.prototype, "specularTexture", void 0);
  44574. __decorate([
  44575. BABYLON.serializeAsTexture("bumpTexture")
  44576. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44577. __decorate([
  44578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44579. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44580. __decorate([
  44581. BABYLON.serializeAsTexture("lightmapTexture")
  44582. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44583. __decorate([
  44584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44585. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44586. __decorate([
  44587. BABYLON.serializeAsTexture("refractionTexture")
  44588. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44589. __decorate([
  44590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44591. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44592. __decorate([
  44593. BABYLON.serializeAsColor3("ambient")
  44594. ], StandardMaterial.prototype, "ambientColor", void 0);
  44595. __decorate([
  44596. BABYLON.serializeAsColor3("diffuse")
  44597. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44598. __decorate([
  44599. BABYLON.serializeAsColor3("specular")
  44600. ], StandardMaterial.prototype, "specularColor", void 0);
  44601. __decorate([
  44602. BABYLON.serializeAsColor3("emissive")
  44603. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44604. __decorate([
  44605. BABYLON.serialize()
  44606. ], StandardMaterial.prototype, "specularPower", void 0);
  44607. __decorate([
  44608. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44609. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44610. __decorate([
  44611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44612. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44613. __decorate([
  44614. BABYLON.serialize("useEmissiveAsIllumination")
  44615. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44616. __decorate([
  44617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44618. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44619. __decorate([
  44620. BABYLON.serialize("linkEmissiveWithDiffuse")
  44621. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44622. __decorate([
  44623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44624. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44625. __decorate([
  44626. BABYLON.serialize("useSpecularOverAlpha")
  44627. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44628. __decorate([
  44629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44630. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44631. __decorate([
  44632. BABYLON.serialize("useReflectionOverAlpha")
  44633. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44634. __decorate([
  44635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44636. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44637. __decorate([
  44638. BABYLON.serialize("disableLighting")
  44639. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44640. __decorate([
  44641. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44642. ], StandardMaterial.prototype, "disableLighting", void 0);
  44643. __decorate([
  44644. BABYLON.serialize("useParallax")
  44645. ], StandardMaterial.prototype, "_useParallax", void 0);
  44646. __decorate([
  44647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44648. ], StandardMaterial.prototype, "useParallax", void 0);
  44649. __decorate([
  44650. BABYLON.serialize("useParallaxOcclusion")
  44651. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44652. __decorate([
  44653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44654. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44655. __decorate([
  44656. BABYLON.serialize()
  44657. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44658. __decorate([
  44659. BABYLON.serialize("roughness")
  44660. ], StandardMaterial.prototype, "_roughness", void 0);
  44661. __decorate([
  44662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44663. ], StandardMaterial.prototype, "roughness", void 0);
  44664. __decorate([
  44665. BABYLON.serialize()
  44666. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44667. __decorate([
  44668. BABYLON.serialize()
  44669. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44670. __decorate([
  44671. BABYLON.serialize("useLightmapAsShadowmap")
  44672. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44673. __decorate([
  44674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44675. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44676. __decorate([
  44677. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44678. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44679. __decorate([
  44680. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44681. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44682. __decorate([
  44683. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44684. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44685. __decorate([
  44686. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44687. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44688. __decorate([
  44689. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44690. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44691. __decorate([
  44692. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44693. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44694. __decorate([
  44695. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44696. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44697. __decorate([
  44698. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44699. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44700. __decorate([
  44701. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44702. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44703. __decorate([
  44704. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44705. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44706. __decorate([
  44707. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44708. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44709. __decorate([
  44710. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44711. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44712. __decorate([
  44713. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44714. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44715. __decorate([
  44716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44717. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44718. __decorate([
  44719. BABYLON.serialize("maxSimultaneousLights")
  44720. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44721. __decorate([
  44722. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44723. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44724. __decorate([
  44725. BABYLON.serialize("invertNormalMapX")
  44726. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44727. __decorate([
  44728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44729. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44730. __decorate([
  44731. BABYLON.serialize("invertNormalMapY")
  44732. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44733. __decorate([
  44734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44735. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44736. __decorate([
  44737. BABYLON.serialize("twoSidedLighting")
  44738. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44739. __decorate([
  44740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44741. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44742. __decorate([
  44743. BABYLON.serialize()
  44744. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44745. return StandardMaterial;
  44746. }(BABYLON.PushMaterial));
  44747. BABYLON.StandardMaterial = StandardMaterial;
  44748. })(BABYLON || (BABYLON = {}));
  44749. //# sourceMappingURL=babylon.standardMaterial.js.map
  44750. var BABYLON;
  44751. (function (BABYLON) {
  44752. /**
  44753. * This class implement a typical dictionary using a string as key and the generic type T as value.
  44754. * The underlying implementation relies on an associative array to ensure the best performances.
  44755. * The value can be anything including 'null' but except 'undefined'
  44756. */
  44757. var StringDictionary = (function () {
  44758. function StringDictionary() {
  44759. this._count = 0;
  44760. this._data = {};
  44761. }
  44762. /**
  44763. * This will clear this dictionary and copy the content from the 'source' one.
  44764. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  44765. * @param source the dictionary to take the content from and copy to this dictionary
  44766. */
  44767. StringDictionary.prototype.copyFrom = function (source) {
  44768. var _this = this;
  44769. this.clear();
  44770. source.forEach(function (t, v) { return _this.add(t, v); });
  44771. };
  44772. /**
  44773. * Get a value based from its key
  44774. * @param key the given key to get the matching value from
  44775. * @return the value if found, otherwise undefined is returned
  44776. */
  44777. StringDictionary.prototype.get = function (key) {
  44778. var val = this._data[key];
  44779. if (val !== undefined) {
  44780. return val;
  44781. }
  44782. return undefined;
  44783. };
  44784. /**
  44785. * Get a value from its key or add it if it doesn't exist.
  44786. * This method will ensure you that a given key/data will be present in the dictionary.
  44787. * @param key the given key to get the matching value from
  44788. * @param factory the factory that will create the value if the key is not present in the dictionary.
  44789. * The factory will only be invoked if there's no data for the given key.
  44790. * @return the value corresponding to the key.
  44791. */
  44792. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  44793. var val = this.get(key);
  44794. if (val !== undefined) {
  44795. return val;
  44796. }
  44797. val = factory(key);
  44798. if (val) {
  44799. this.add(key, val);
  44800. }
  44801. return val;
  44802. };
  44803. /**
  44804. * Get a value from its key if present in the dictionary otherwise add it
  44805. * @param key the key to get the value from
  44806. * @param val if there's no such key/value pair in the dictionary add it with this value
  44807. * @return the value corresponding to the key
  44808. */
  44809. StringDictionary.prototype.getOrAdd = function (key, val) {
  44810. var curVal = this.get(key);
  44811. if (curVal !== undefined) {
  44812. return curVal;
  44813. }
  44814. this.add(key, val);
  44815. return val;
  44816. };
  44817. /**
  44818. * Check if there's a given key in the dictionary
  44819. * @param key the key to check for
  44820. * @return true if the key is present, false otherwise
  44821. */
  44822. StringDictionary.prototype.contains = function (key) {
  44823. return this._data[key] !== undefined;
  44824. };
  44825. /**
  44826. * Add a new key and its corresponding value
  44827. * @param key the key to add
  44828. * @param value the value corresponding to the key
  44829. * @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
  44830. */
  44831. StringDictionary.prototype.add = function (key, value) {
  44832. if (this._data[key] !== undefined) {
  44833. return false;
  44834. }
  44835. this._data[key] = value;
  44836. ++this._count;
  44837. return true;
  44838. };
  44839. StringDictionary.prototype.set = function (key, value) {
  44840. if (this._data[key] === undefined) {
  44841. return false;
  44842. }
  44843. this._data[key] = value;
  44844. return true;
  44845. };
  44846. /**
  44847. * Get the element of the given key and remove it from the dictionary
  44848. * @param key
  44849. */
  44850. StringDictionary.prototype.getAndRemove = function (key) {
  44851. var val = this.get(key);
  44852. if (val !== undefined) {
  44853. delete this._data[key];
  44854. --this._count;
  44855. return val;
  44856. }
  44857. return null;
  44858. };
  44859. /**
  44860. * Remove a key/value from the dictionary.
  44861. * @param key the key to remove
  44862. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  44863. */
  44864. StringDictionary.prototype.remove = function (key) {
  44865. if (this.contains(key)) {
  44866. delete this._data[key];
  44867. --this._count;
  44868. return true;
  44869. }
  44870. return false;
  44871. };
  44872. /**
  44873. * Clear the whole content of the dictionary
  44874. */
  44875. StringDictionary.prototype.clear = function () {
  44876. this._data = {};
  44877. this._count = 0;
  44878. };
  44879. Object.defineProperty(StringDictionary.prototype, "count", {
  44880. get: function () {
  44881. return this._count;
  44882. },
  44883. enumerable: true,
  44884. configurable: true
  44885. });
  44886. /**
  44887. * Execute a callback on each key/val of the dictionary.
  44888. * Note that you can remove any element in this dictionary in the callback implementation
  44889. * @param callback the callback to execute on a given key/value pair
  44890. */
  44891. StringDictionary.prototype.forEach = function (callback) {
  44892. for (var cur in this._data) {
  44893. var val = this._data[cur];
  44894. callback(cur, val);
  44895. }
  44896. };
  44897. /**
  44898. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  44899. * If the callback returns null or undefined the method will iterate to the next key/value pair
  44900. * Note that you can remove any element in this dictionary in the callback implementation
  44901. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  44902. */
  44903. StringDictionary.prototype.first = function (callback) {
  44904. for (var cur in this._data) {
  44905. var val = this._data[cur];
  44906. var res = callback(cur, val);
  44907. if (res) {
  44908. return res;
  44909. }
  44910. }
  44911. return null;
  44912. };
  44913. return StringDictionary;
  44914. }());
  44915. BABYLON.StringDictionary = StringDictionary;
  44916. })(BABYLON || (BABYLON = {}));
  44917. //# sourceMappingURL=babylon.stringDictionary.js.map
  44918. var BABYLON;
  44919. (function (BABYLON) {
  44920. var DynamicFloatArrayElementInfo = (function () {
  44921. function DynamicFloatArrayElementInfo() {
  44922. }
  44923. return DynamicFloatArrayElementInfo;
  44924. }());
  44925. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  44926. /**
  44927. * 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.
  44928. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  44929. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  44930. * 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.
  44931. * 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.
  44932. * 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".
  44933. */
  44934. var DynamicFloatArray = (function () {
  44935. /**
  44936. * Construct an instance of the dynamic float array
  44937. * @param stride size of one element in float (i.e. not bytes!)
  44938. * @param initialElementCount the number of available entries at construction
  44939. */
  44940. function DynamicFloatArray(stride, initialElementCount) {
  44941. this.compareValueOffset = null;
  44942. this.sortingAscending = true;
  44943. this._stride = stride;
  44944. this.buffer = new Float32Array(stride * initialElementCount);
  44945. this._lastUsed = 0;
  44946. this._firstFree = 0;
  44947. this._allEntries = new Array(initialElementCount);
  44948. this._freeEntries = new Array(initialElementCount);
  44949. for (var i = 0; i < initialElementCount; i++) {
  44950. var element = new DynamicFloatArrayElementInfo();
  44951. element.offset = i * stride;
  44952. this._allEntries[i] = element;
  44953. this._freeEntries[initialElementCount - i - 1] = element;
  44954. }
  44955. }
  44956. /**
  44957. * Allocate an element in the array.
  44958. * @return the element info instance that contains the offset into the main buffer of the element's location.
  44959. * Beware, this offset may change when you call pack()
  44960. */
  44961. DynamicFloatArray.prototype.allocElement = function () {
  44962. if (this._freeEntries.length === 0) {
  44963. this._growBuffer();
  44964. }
  44965. var el = this._freeEntries.pop();
  44966. this._lastUsed = Math.max(el.offset, this._lastUsed);
  44967. if (el.offset === this._firstFree) {
  44968. if (this._freeEntries.length > 0) {
  44969. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  44970. }
  44971. else {
  44972. this._firstFree += this._stride;
  44973. }
  44974. }
  44975. return el;
  44976. };
  44977. /**
  44978. * Free the element corresponding to the given element info
  44979. * @param elInfo the element that describe the allocated element
  44980. */
  44981. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  44982. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  44983. this._freeEntries.push(elInfo);
  44984. };
  44985. /**
  44986. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  44987. * 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().
  44988. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  44989. */
  44990. DynamicFloatArray.prototype.pack = function () {
  44991. // no free slot? no need to pack
  44992. if (this._freeEntries.length === 0) {
  44993. return this.buffer;
  44994. }
  44995. // If the buffer is already packed the last used will always be lower than the first free
  44996. // 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.
  44997. if (this._lastUsed < this._firstFree) {
  44998. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  44999. return elementsBuffer_1;
  45000. }
  45001. var s = this._stride;
  45002. // 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
  45003. var lastFree = new DynamicFloatArrayElementInfo();
  45004. lastFree.offset = this.totalElementCount * s;
  45005. this._freeEntries.push(lastFree);
  45006. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  45007. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45008. var firstFreeSlotOffset = sortedFree[0].offset;
  45009. var freeZoneSize = 1;
  45010. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  45011. var prevOffset = sortedFree[0].offset;
  45012. for (var i = 1; i < sortedFree.length; i++) {
  45013. // 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
  45014. if (firstFreeSlotOffset >= occupiedZoneSize) {
  45015. break;
  45016. }
  45017. var curFree = sortedFree[i];
  45018. var curOffset = curFree.offset;
  45019. // Compute the distance between this offset and the previous
  45020. var distance = curOffset - prevOffset;
  45021. // If the distance is the stride size, they are adjacent, it good, move to the next
  45022. if (distance === s) {
  45023. // Free zone is one element bigger
  45024. ++freeZoneSize;
  45025. // as we're about to iterate to the next, the cur becomes the previous...
  45026. prevOffset = curOffset;
  45027. continue;
  45028. }
  45029. // Distance is bigger, which means there's x element between the previous free and this one
  45030. var usedRange = (distance / s) - 1;
  45031. // Two cases the free zone is smaller than the data to move or bigger
  45032. // Copy what can fit in the free zone
  45033. var curMoveOffset = curOffset - s;
  45034. var copyCount = Math.min(freeZoneSize, usedRange);
  45035. for (var j = 0; j < copyCount; j++) {
  45036. var freeI = firstFreeSlotOffset / s;
  45037. var curI = curMoveOffset / s;
  45038. var moveEl = sortedAll[curI];
  45039. this._moveElement(moveEl, firstFreeSlotOffset);
  45040. var replacedEl = sortedAll[freeI];
  45041. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  45042. replacedEl.offset = curMoveOffset;
  45043. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  45044. sortedAll[freeI] = moveEl;
  45045. sortedAll[curI] = replacedEl;
  45046. curMoveOffset -= s;
  45047. firstFreeSlotOffset += s;
  45048. }
  45049. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  45050. if (freeZoneSize <= usedRange) {
  45051. firstFreeSlotOffset = curMoveOffset + s;
  45052. freeZoneSize = 1 + copyCount;
  45053. }
  45054. else {
  45055. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  45056. }
  45057. // as we're about to iterate to the next, the cur becomes the previous...
  45058. prevOffset = curOffset;
  45059. }
  45060. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  45061. this._lastUsed = firstFreeSlotOffset - s;
  45062. this._firstFree = firstFreeSlotOffset;
  45063. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  45064. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  45065. this._allEntries = sortedAll;
  45066. return elementsBuffer;
  45067. };
  45068. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  45069. for (var i = 0; i < this._stride; i++) {
  45070. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  45071. }
  45072. element.offset = destOffset;
  45073. };
  45074. DynamicFloatArray.prototype._growBuffer = function () {
  45075. // Allocate the new buffer with 50% more entries, copy the content of the current one
  45076. var newElCount = Math.floor(this.totalElementCount * 1.5);
  45077. var newBuffer = new Float32Array(newElCount * this._stride);
  45078. newBuffer.set(this.buffer);
  45079. var curCount = this.totalElementCount;
  45080. var addedCount = newElCount - this.totalElementCount;
  45081. for (var i = 0; i < addedCount; i++) {
  45082. var element = new DynamicFloatArrayElementInfo();
  45083. element.offset = (curCount + i) * this.stride;
  45084. this._allEntries.push(element);
  45085. this._freeEntries[addedCount - i - 1] = element;
  45086. }
  45087. this._firstFree = curCount * this.stride;
  45088. this.buffer = newBuffer;
  45089. };
  45090. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  45091. /**
  45092. * Get the total count of entries that can fit in the current buffer
  45093. * @returns the elements count
  45094. */
  45095. get: function () {
  45096. return this._allEntries.length;
  45097. },
  45098. enumerable: true,
  45099. configurable: true
  45100. });
  45101. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  45102. /**
  45103. * Get the count of free entries that can still be allocated without resizing the buffer
  45104. * @returns the free elements count
  45105. */
  45106. get: function () {
  45107. return this._freeEntries.length;
  45108. },
  45109. enumerable: true,
  45110. configurable: true
  45111. });
  45112. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  45113. /**
  45114. * Get the count of allocated elements
  45115. * @returns the allocated elements count
  45116. */
  45117. get: function () {
  45118. return this._allEntries.length - this._freeEntries.length;
  45119. },
  45120. enumerable: true,
  45121. configurable: true
  45122. });
  45123. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  45124. /**
  45125. * Return the size of one element in float
  45126. * @returns the size in float
  45127. */
  45128. get: function () {
  45129. return this._stride;
  45130. },
  45131. enumerable: true,
  45132. configurable: true
  45133. });
  45134. DynamicFloatArray.prototype.sort = function () {
  45135. var _this = this;
  45136. if (!this.compareValueOffset) {
  45137. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  45138. }
  45139. var count = this.usedElementCount;
  45140. // Do we have to (re)create the sort table?
  45141. if (!this._sortTable || this._sortTable.length < count) {
  45142. // 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...
  45143. var newCount = Math.min(this.totalElementCount, count * 2);
  45144. this._sortTable = new Array(newCount);
  45145. }
  45146. if (!this._sortedTable || this._sortedTable.length !== count) {
  45147. this._sortedTable = new Array(count);
  45148. }
  45149. // Because, you know...
  45150. this.pack();
  45151. //let stride = this.stride;
  45152. //for (let i = 0; i < count; i++) {
  45153. // let si = this._sortTable[i];
  45154. // if (!si) {
  45155. // si = new SortInfo();
  45156. // this._sortTable[i] = si;
  45157. // }
  45158. // si.entry = this._allEntries[i];
  45159. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  45160. // si.swapedOffset = null;
  45161. // this._sortedTable[i] = si;
  45162. //}
  45163. var curOffset = 0;
  45164. var stride = this.stride;
  45165. for (var i = 0; i < count; i++, curOffset += stride) {
  45166. var si = this._sortTable[i];
  45167. if (!si) {
  45168. si = new SortInfo();
  45169. this._sortTable[i] = si;
  45170. }
  45171. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  45172. si.offset = curOffset;
  45173. si.swapedOffset = null;
  45174. this._sortedTable[i] = si;
  45175. }
  45176. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  45177. if (this.sortingAscending) {
  45178. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  45179. }
  45180. else {
  45181. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  45182. }
  45183. var swapElements = function (src, dst) {
  45184. for (var i = 0; i < stride; i++) {
  45185. var tps = _this.buffer[dst + i];
  45186. _this.buffer[dst + i] = _this.buffer[src + i];
  45187. _this.buffer[src + i] = tps;
  45188. }
  45189. };
  45190. // 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:
  45191. // 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),
  45192. // and I still want something with a good algorithm complexity.
  45193. // 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,
  45194. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  45195. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  45196. // 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
  45197. // until we find a SortInfo object without a swapedOffset which means we got the right location
  45198. // 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
  45199. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  45200. for (var i = 0; i < count; i++) {
  45201. // Get the element to move
  45202. var sourceSI = this._sortedTable[i];
  45203. var destSI = this._sortTable[i];
  45204. var sourceOff = sourceSI.offset;
  45205. // If the source changed location, find the new one
  45206. if (sourceSI.swapedOffset) {
  45207. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  45208. var curSI = sourceSI;
  45209. while (curSI.swapedOffset) {
  45210. curSI = this._sortTable[curSI.swapedOffset / stride];
  45211. }
  45212. // Finally get the right location
  45213. sourceOff = curSI.offset;
  45214. }
  45215. // Tag the element being replaced with its new location
  45216. destSI.swapedOffset = sourceOff;
  45217. // Swap elements (only if needed)
  45218. if (sourceOff !== destSI.offset) {
  45219. swapElements(sourceOff, destSI.offset);
  45220. }
  45221. // Update the offset in the corresponding DFAE
  45222. //sourceSI.entry.offset = destSI.entry.offset;
  45223. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  45224. }
  45225. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45226. return true;
  45227. };
  45228. return DynamicFloatArray;
  45229. }());
  45230. BABYLON.DynamicFloatArray = DynamicFloatArray;
  45231. var SortInfo = (function () {
  45232. function SortInfo() {
  45233. this.compareData = this.offset = this.swapedOffset = null;
  45234. }
  45235. return SortInfo;
  45236. }());
  45237. })(BABYLON || (BABYLON = {}));
  45238. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  45239. var BABYLON;
  45240. (function (BABYLON) {
  45241. var Condition = (function () {
  45242. function Condition(actionManager) {
  45243. this._actionManager = actionManager;
  45244. }
  45245. Condition.prototype.isValid = function () {
  45246. return true;
  45247. };
  45248. Condition.prototype._getProperty = function (propertyPath) {
  45249. return this._actionManager._getProperty(propertyPath);
  45250. };
  45251. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  45252. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45253. };
  45254. Condition.prototype.serialize = function () {
  45255. };
  45256. Condition.prototype._serialize = function (serializedCondition) {
  45257. return {
  45258. type: 2,
  45259. children: [],
  45260. name: serializedCondition.name,
  45261. properties: serializedCondition.properties
  45262. };
  45263. };
  45264. return Condition;
  45265. }());
  45266. BABYLON.Condition = Condition;
  45267. var ValueCondition = (function (_super) {
  45268. __extends(ValueCondition, _super);
  45269. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  45270. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  45271. var _this = _super.call(this, actionManager) || this;
  45272. _this.propertyPath = propertyPath;
  45273. _this.value = value;
  45274. _this.operator = operator;
  45275. _this._target = target;
  45276. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  45277. _this._property = _this._getProperty(_this.propertyPath);
  45278. return _this;
  45279. }
  45280. Object.defineProperty(ValueCondition, "IsEqual", {
  45281. get: function () {
  45282. return ValueCondition._IsEqual;
  45283. },
  45284. enumerable: true,
  45285. configurable: true
  45286. });
  45287. Object.defineProperty(ValueCondition, "IsDifferent", {
  45288. get: function () {
  45289. return ValueCondition._IsDifferent;
  45290. },
  45291. enumerable: true,
  45292. configurable: true
  45293. });
  45294. Object.defineProperty(ValueCondition, "IsGreater", {
  45295. get: function () {
  45296. return ValueCondition._IsGreater;
  45297. },
  45298. enumerable: true,
  45299. configurable: true
  45300. });
  45301. Object.defineProperty(ValueCondition, "IsLesser", {
  45302. get: function () {
  45303. return ValueCondition._IsLesser;
  45304. },
  45305. enumerable: true,
  45306. configurable: true
  45307. });
  45308. // Methods
  45309. ValueCondition.prototype.isValid = function () {
  45310. switch (this.operator) {
  45311. case ValueCondition.IsGreater:
  45312. return this._effectiveTarget[this._property] > this.value;
  45313. case ValueCondition.IsLesser:
  45314. return this._effectiveTarget[this._property] < this.value;
  45315. case ValueCondition.IsEqual:
  45316. case ValueCondition.IsDifferent:
  45317. var check;
  45318. if (this.value.equals) {
  45319. check = this.value.equals(this._effectiveTarget[this._property]);
  45320. }
  45321. else {
  45322. check = this.value === this._effectiveTarget[this._property];
  45323. }
  45324. return this.operator === ValueCondition.IsEqual ? check : !check;
  45325. }
  45326. return false;
  45327. };
  45328. ValueCondition.prototype.serialize = function () {
  45329. return this._serialize({
  45330. name: "ValueCondition",
  45331. properties: [
  45332. BABYLON.Action._GetTargetProperty(this._target),
  45333. { name: "propertyPath", value: this.propertyPath },
  45334. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45335. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  45336. ]
  45337. });
  45338. };
  45339. ValueCondition.GetOperatorName = function (operator) {
  45340. switch (operator) {
  45341. case ValueCondition._IsEqual: return "IsEqual";
  45342. case ValueCondition._IsDifferent: return "IsDifferent";
  45343. case ValueCondition._IsGreater: return "IsGreater";
  45344. case ValueCondition._IsLesser: return "IsLesser";
  45345. default: return "";
  45346. }
  45347. };
  45348. // Statics
  45349. ValueCondition._IsEqual = 0;
  45350. ValueCondition._IsDifferent = 1;
  45351. ValueCondition._IsGreater = 2;
  45352. ValueCondition._IsLesser = 3;
  45353. return ValueCondition;
  45354. }(Condition));
  45355. BABYLON.ValueCondition = ValueCondition;
  45356. var PredicateCondition = (function (_super) {
  45357. __extends(PredicateCondition, _super);
  45358. function PredicateCondition(actionManager, predicate) {
  45359. var _this = _super.call(this, actionManager) || this;
  45360. _this.predicate = predicate;
  45361. return _this;
  45362. }
  45363. PredicateCondition.prototype.isValid = function () {
  45364. return this.predicate();
  45365. };
  45366. return PredicateCondition;
  45367. }(Condition));
  45368. BABYLON.PredicateCondition = PredicateCondition;
  45369. var StateCondition = (function (_super) {
  45370. __extends(StateCondition, _super);
  45371. function StateCondition(actionManager, target, value) {
  45372. var _this = _super.call(this, actionManager) || this;
  45373. _this.value = value;
  45374. _this._target = target;
  45375. return _this;
  45376. }
  45377. // Methods
  45378. StateCondition.prototype.isValid = function () {
  45379. return this._target.state === this.value;
  45380. };
  45381. StateCondition.prototype.serialize = function () {
  45382. return this._serialize({
  45383. name: "StateCondition",
  45384. properties: [
  45385. BABYLON.Action._GetTargetProperty(this._target),
  45386. { name: "value", value: this.value }
  45387. ]
  45388. });
  45389. };
  45390. return StateCondition;
  45391. }(Condition));
  45392. BABYLON.StateCondition = StateCondition;
  45393. })(BABYLON || (BABYLON = {}));
  45394. //# sourceMappingURL=babylon.condition.js.map
  45395. var BABYLON;
  45396. (function (BABYLON) {
  45397. var Action = (function () {
  45398. function Action(triggerOptions, condition) {
  45399. this.triggerOptions = triggerOptions;
  45400. if (triggerOptions.parameter) {
  45401. this.trigger = triggerOptions.trigger;
  45402. this._triggerParameter = triggerOptions.parameter;
  45403. }
  45404. else {
  45405. this.trigger = triggerOptions;
  45406. }
  45407. this._nextActiveAction = this;
  45408. this._condition = condition;
  45409. }
  45410. // Methods
  45411. Action.prototype._prepare = function () {
  45412. };
  45413. Action.prototype.getTriggerParameter = function () {
  45414. return this._triggerParameter;
  45415. };
  45416. Action.prototype._executeCurrent = function (evt) {
  45417. if (this._nextActiveAction._condition) {
  45418. var condition = this._nextActiveAction._condition;
  45419. var currentRenderId = this._actionManager.getScene().getRenderId();
  45420. // We cache the current evaluation for the current frame
  45421. if (condition._evaluationId === currentRenderId) {
  45422. if (!condition._currentResult) {
  45423. return;
  45424. }
  45425. }
  45426. else {
  45427. condition._evaluationId = currentRenderId;
  45428. if (!condition.isValid()) {
  45429. condition._currentResult = false;
  45430. return;
  45431. }
  45432. condition._currentResult = true;
  45433. }
  45434. }
  45435. this._nextActiveAction.execute(evt);
  45436. this.skipToNextActiveAction();
  45437. };
  45438. Action.prototype.execute = function (evt) {
  45439. };
  45440. Action.prototype.skipToNextActiveAction = function () {
  45441. if (this._nextActiveAction._child) {
  45442. if (!this._nextActiveAction._child._actionManager) {
  45443. this._nextActiveAction._child._actionManager = this._actionManager;
  45444. }
  45445. this._nextActiveAction = this._nextActiveAction._child;
  45446. }
  45447. else {
  45448. this._nextActiveAction = this;
  45449. }
  45450. };
  45451. Action.prototype.then = function (action) {
  45452. this._child = action;
  45453. action._actionManager = this._actionManager;
  45454. action._prepare();
  45455. return action;
  45456. };
  45457. Action.prototype._getProperty = function (propertyPath) {
  45458. return this._actionManager._getProperty(propertyPath);
  45459. };
  45460. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  45461. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45462. };
  45463. Action.prototype.serialize = function (parent) {
  45464. };
  45465. // Called by BABYLON.Action objects in serialize(...). Internal use
  45466. Action.prototype._serialize = function (serializedAction, parent) {
  45467. var serializationObject = {
  45468. type: 1,
  45469. children: [],
  45470. name: serializedAction.name,
  45471. properties: serializedAction.properties || []
  45472. };
  45473. // Serialize child
  45474. if (this._child) {
  45475. this._child.serialize(serializationObject);
  45476. }
  45477. // Check if "this" has a condition
  45478. if (this._condition) {
  45479. var serializedCondition = this._condition.serialize();
  45480. serializedCondition.children.push(serializationObject);
  45481. if (parent) {
  45482. parent.children.push(serializedCondition);
  45483. }
  45484. return serializedCondition;
  45485. }
  45486. if (parent) {
  45487. parent.children.push(serializationObject);
  45488. }
  45489. return serializationObject;
  45490. };
  45491. Action._SerializeValueAsString = function (value) {
  45492. if (typeof value === "number") {
  45493. return value.toString();
  45494. }
  45495. if (typeof value === "boolean") {
  45496. return value ? "true" : "false";
  45497. }
  45498. if (value instanceof BABYLON.Vector2) {
  45499. return value.x + ", " + value.y;
  45500. }
  45501. if (value instanceof BABYLON.Vector3) {
  45502. return value.x + ", " + value.y + ", " + value.z;
  45503. }
  45504. if (value instanceof BABYLON.Color3) {
  45505. return value.r + ", " + value.g + ", " + value.b;
  45506. }
  45507. if (value instanceof BABYLON.Color4) {
  45508. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  45509. }
  45510. return value; // string
  45511. };
  45512. Action._GetTargetProperty = function (target) {
  45513. return {
  45514. name: "target",
  45515. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  45516. : target instanceof BABYLON.Light ? "LightProperties"
  45517. : target instanceof BABYLON.Camera ? "CameraProperties"
  45518. : "SceneProperties",
  45519. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  45520. };
  45521. };
  45522. return Action;
  45523. }());
  45524. BABYLON.Action = Action;
  45525. })(BABYLON || (BABYLON = {}));
  45526. //# sourceMappingURL=babylon.action.js.map
  45527. var BABYLON;
  45528. (function (BABYLON) {
  45529. /**
  45530. * ActionEvent is the event beint sent when an action is triggered.
  45531. */
  45532. var ActionEvent = (function () {
  45533. /**
  45534. * @param source The mesh or sprite that triggered the action.
  45535. * @param pointerX The X mouse cursor position at the time of the event
  45536. * @param pointerY The Y mouse cursor position at the time of the event
  45537. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  45538. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  45539. */
  45540. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  45541. this.source = source;
  45542. this.pointerX = pointerX;
  45543. this.pointerY = pointerY;
  45544. this.meshUnderPointer = meshUnderPointer;
  45545. this.sourceEvent = sourceEvent;
  45546. this.additionalData = additionalData;
  45547. }
  45548. /**
  45549. * Helper function to auto-create an ActionEvent from a source mesh.
  45550. * @param source The source mesh that triggered the event
  45551. * @param evt {Event} The original (browser) event
  45552. */
  45553. ActionEvent.CreateNew = function (source, evt, additionalData) {
  45554. var scene = source.getScene();
  45555. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45556. };
  45557. /**
  45558. * Helper function to auto-create an ActionEvent from a source mesh.
  45559. * @param source The source sprite that triggered the event
  45560. * @param scene Scene associated with the sprite
  45561. * @param evt {Event} The original (browser) event
  45562. */
  45563. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  45564. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45565. };
  45566. /**
  45567. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  45568. * @param scene the scene where the event occurred
  45569. * @param evt {Event} The original (browser) event
  45570. */
  45571. ActionEvent.CreateNewFromScene = function (scene, evt) {
  45572. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  45573. };
  45574. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  45575. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  45576. };
  45577. return ActionEvent;
  45578. }());
  45579. BABYLON.ActionEvent = ActionEvent;
  45580. /**
  45581. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  45582. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  45583. */
  45584. var ActionManager = (function () {
  45585. function ActionManager(scene) {
  45586. // Members
  45587. this.actions = new Array();
  45588. this.hoverCursor = '';
  45589. this._scene = scene;
  45590. scene._actionManagers.push(this);
  45591. }
  45592. Object.defineProperty(ActionManager, "NothingTrigger", {
  45593. get: function () {
  45594. return ActionManager._NothingTrigger;
  45595. },
  45596. enumerable: true,
  45597. configurable: true
  45598. });
  45599. Object.defineProperty(ActionManager, "OnPickTrigger", {
  45600. get: function () {
  45601. return ActionManager._OnPickTrigger;
  45602. },
  45603. enumerable: true,
  45604. configurable: true
  45605. });
  45606. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  45607. get: function () {
  45608. return ActionManager._OnLeftPickTrigger;
  45609. },
  45610. enumerable: true,
  45611. configurable: true
  45612. });
  45613. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  45614. get: function () {
  45615. return ActionManager._OnRightPickTrigger;
  45616. },
  45617. enumerable: true,
  45618. configurable: true
  45619. });
  45620. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  45621. get: function () {
  45622. return ActionManager._OnCenterPickTrigger;
  45623. },
  45624. enumerable: true,
  45625. configurable: true
  45626. });
  45627. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  45628. get: function () {
  45629. return ActionManager._OnPickDownTrigger;
  45630. },
  45631. enumerable: true,
  45632. configurable: true
  45633. });
  45634. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  45635. get: function () {
  45636. return ActionManager._OnDoublePickTrigger;
  45637. },
  45638. enumerable: true,
  45639. configurable: true
  45640. });
  45641. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  45642. get: function () {
  45643. return ActionManager._OnPickUpTrigger;
  45644. },
  45645. enumerable: true,
  45646. configurable: true
  45647. });
  45648. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  45649. /// This trigger will only be raised if you also declared a OnPickDown
  45650. get: function () {
  45651. return ActionManager._OnPickOutTrigger;
  45652. },
  45653. enumerable: true,
  45654. configurable: true
  45655. });
  45656. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  45657. get: function () {
  45658. return ActionManager._OnLongPressTrigger;
  45659. },
  45660. enumerable: true,
  45661. configurable: true
  45662. });
  45663. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  45664. get: function () {
  45665. return ActionManager._OnPointerOverTrigger;
  45666. },
  45667. enumerable: true,
  45668. configurable: true
  45669. });
  45670. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  45671. get: function () {
  45672. return ActionManager._OnPointerOutTrigger;
  45673. },
  45674. enumerable: true,
  45675. configurable: true
  45676. });
  45677. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  45678. get: function () {
  45679. return ActionManager._OnEveryFrameTrigger;
  45680. },
  45681. enumerable: true,
  45682. configurable: true
  45683. });
  45684. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  45685. get: function () {
  45686. return ActionManager._OnIntersectionEnterTrigger;
  45687. },
  45688. enumerable: true,
  45689. configurable: true
  45690. });
  45691. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  45692. get: function () {
  45693. return ActionManager._OnIntersectionExitTrigger;
  45694. },
  45695. enumerable: true,
  45696. configurable: true
  45697. });
  45698. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  45699. get: function () {
  45700. return ActionManager._OnKeyDownTrigger;
  45701. },
  45702. enumerable: true,
  45703. configurable: true
  45704. });
  45705. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  45706. get: function () {
  45707. return ActionManager._OnKeyUpTrigger;
  45708. },
  45709. enumerable: true,
  45710. configurable: true
  45711. });
  45712. // Methods
  45713. ActionManager.prototype.dispose = function () {
  45714. var index = this._scene._actionManagers.indexOf(this);
  45715. for (var i = 0; i < this.actions.length; i++) {
  45716. var action = this.actions[i];
  45717. ActionManager.Triggers[action.trigger]--;
  45718. if (ActionManager.Triggers[action.trigger] === 0) {
  45719. delete ActionManager.Triggers[action.trigger];
  45720. }
  45721. }
  45722. if (index > -1) {
  45723. this._scene._actionManagers.splice(index, 1);
  45724. }
  45725. };
  45726. ActionManager.prototype.getScene = function () {
  45727. return this._scene;
  45728. };
  45729. /**
  45730. * Does this action manager handles actions of any of the given triggers
  45731. * @param {number[]} triggers - the triggers to be tested
  45732. * @return {boolean} whether one (or more) of the triggers is handeled
  45733. */
  45734. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  45735. for (var index = 0; index < this.actions.length; index++) {
  45736. var action = this.actions[index];
  45737. if (triggers.indexOf(action.trigger) > -1) {
  45738. return true;
  45739. }
  45740. }
  45741. return false;
  45742. };
  45743. /**
  45744. * Does this action manager handles actions of a given trigger
  45745. * @param {number} trigger - the trigger to be tested
  45746. * @return {boolean} whether the trigger is handeled
  45747. */
  45748. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  45749. for (var index = 0; index < this.actions.length; index++) {
  45750. var action = this.actions[index];
  45751. if (action.trigger === trigger) {
  45752. return true;
  45753. }
  45754. }
  45755. return false;
  45756. };
  45757. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  45758. /**
  45759. * Does this action manager has pointer triggers
  45760. * @return {boolean} whether or not it has pointer triggers
  45761. */
  45762. get: function () {
  45763. for (var index = 0; index < this.actions.length; index++) {
  45764. var action = this.actions[index];
  45765. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  45766. return true;
  45767. }
  45768. }
  45769. return false;
  45770. },
  45771. enumerable: true,
  45772. configurable: true
  45773. });
  45774. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  45775. /**
  45776. * Does this action manager has pick triggers
  45777. * @return {boolean} whether or not it has pick triggers
  45778. */
  45779. get: function () {
  45780. for (var index = 0; index < this.actions.length; index++) {
  45781. var action = this.actions[index];
  45782. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  45783. return true;
  45784. }
  45785. }
  45786. return false;
  45787. },
  45788. enumerable: true,
  45789. configurable: true
  45790. });
  45791. Object.defineProperty(ActionManager, "HasTriggers", {
  45792. /**
  45793. * Does exist one action manager with at least one trigger
  45794. * @return {boolean} whether or not it exists one action manager with one trigger
  45795. **/
  45796. get: function () {
  45797. for (var t in ActionManager.Triggers) {
  45798. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45799. return true;
  45800. }
  45801. }
  45802. return false;
  45803. },
  45804. enumerable: true,
  45805. configurable: true
  45806. });
  45807. Object.defineProperty(ActionManager, "HasPickTriggers", {
  45808. /**
  45809. * Does exist one action manager with at least one pick trigger
  45810. * @return {boolean} whether or not it exists one action manager with one pick trigger
  45811. **/
  45812. get: function () {
  45813. for (var t in ActionManager.Triggers) {
  45814. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45815. var t_int = parseInt(t);
  45816. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  45817. return true;
  45818. }
  45819. }
  45820. }
  45821. return false;
  45822. },
  45823. enumerable: true,
  45824. configurable: true
  45825. });
  45826. /**
  45827. * Does exist one action manager that handles actions of a given trigger
  45828. * @param {number} trigger - the trigger to be tested
  45829. * @return {boolean} whether the trigger is handeled by at least one action manager
  45830. **/
  45831. ActionManager.HasSpecificTrigger = function (trigger) {
  45832. for (var t in ActionManager.Triggers) {
  45833. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45834. var t_int = parseInt(t);
  45835. if (t_int === trigger) {
  45836. return true;
  45837. }
  45838. }
  45839. }
  45840. return false;
  45841. };
  45842. /**
  45843. * Registers an action to this action manager
  45844. * @param {BABYLON.Action} action - the action to be registered
  45845. * @return {BABYLON.Action} the action amended (prepared) after registration
  45846. */
  45847. ActionManager.prototype.registerAction = function (action) {
  45848. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  45849. if (this.getScene().actionManager !== this) {
  45850. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  45851. return null;
  45852. }
  45853. }
  45854. this.actions.push(action);
  45855. if (ActionManager.Triggers[action.trigger]) {
  45856. ActionManager.Triggers[action.trigger]++;
  45857. }
  45858. else {
  45859. ActionManager.Triggers[action.trigger] = 1;
  45860. }
  45861. action._actionManager = this;
  45862. action._prepare();
  45863. return action;
  45864. };
  45865. /**
  45866. * Process a specific trigger
  45867. * @param {number} trigger - the trigger to process
  45868. * @param evt {BABYLON.ActionEvent} the event details to be processed
  45869. */
  45870. ActionManager.prototype.processTrigger = function (trigger, evt) {
  45871. for (var index = 0; index < this.actions.length; index++) {
  45872. var action = this.actions[index];
  45873. if (action.trigger === trigger) {
  45874. if (trigger === ActionManager.OnKeyUpTrigger
  45875. || trigger === ActionManager.OnKeyDownTrigger) {
  45876. var parameter = action.getTriggerParameter();
  45877. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  45878. if (!parameter.toLowerCase) {
  45879. continue;
  45880. }
  45881. var lowerCase = parameter.toLowerCase();
  45882. if (lowerCase !== evt.sourceEvent.key) {
  45883. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  45884. var actualkey = String.fromCharCode(unicode).toLowerCase();
  45885. if (actualkey !== lowerCase) {
  45886. continue;
  45887. }
  45888. }
  45889. }
  45890. }
  45891. action._executeCurrent(evt);
  45892. }
  45893. }
  45894. };
  45895. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  45896. var properties = propertyPath.split(".");
  45897. for (var index = 0; index < properties.length - 1; index++) {
  45898. target = target[properties[index]];
  45899. }
  45900. return target;
  45901. };
  45902. ActionManager.prototype._getProperty = function (propertyPath) {
  45903. var properties = propertyPath.split(".");
  45904. return properties[properties.length - 1];
  45905. };
  45906. ActionManager.prototype.serialize = function (name) {
  45907. var root = {
  45908. children: [],
  45909. name: name,
  45910. type: 3,
  45911. properties: [] // Empty for root but required
  45912. };
  45913. for (var i = 0; i < this.actions.length; i++) {
  45914. var triggerObject = {
  45915. type: 0,
  45916. children: [],
  45917. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  45918. properties: []
  45919. };
  45920. var triggerOptions = this.actions[i].triggerOptions;
  45921. if (triggerOptions && typeof triggerOptions !== "number") {
  45922. if (triggerOptions.parameter instanceof BABYLON.Node) {
  45923. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  45924. }
  45925. else {
  45926. var parameter = {};
  45927. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  45928. if (triggerOptions.parameter.mesh) {
  45929. parameter._meshId = triggerOptions.parameter.mesh.id;
  45930. }
  45931. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  45932. }
  45933. }
  45934. // Serialize child action, recursively
  45935. this.actions[i].serialize(triggerObject);
  45936. // Add serialized trigger
  45937. root.children.push(triggerObject);
  45938. }
  45939. return root;
  45940. };
  45941. ActionManager.Parse = function (parsedActions, object, scene) {
  45942. var actionManager = new BABYLON.ActionManager(scene);
  45943. if (object === null)
  45944. scene.actionManager = actionManager;
  45945. else
  45946. object.actionManager = actionManager;
  45947. // instanciate a new object
  45948. var instanciate = function (name, params) {
  45949. var newInstance = Object.create(BABYLON[name].prototype);
  45950. newInstance.constructor.apply(newInstance, params);
  45951. return newInstance;
  45952. };
  45953. var parseParameter = function (name, value, target, propertyPath) {
  45954. if (propertyPath === null) {
  45955. // String, boolean or float
  45956. var floatValue = parseFloat(value);
  45957. if (value === "true" || value === "false")
  45958. return value === "true";
  45959. else
  45960. return isNaN(floatValue) ? value : floatValue;
  45961. }
  45962. var effectiveTarget = propertyPath.split(".");
  45963. var values = value.split(",");
  45964. // Get effective Target
  45965. for (var i = 0; i < effectiveTarget.length; i++) {
  45966. target = target[effectiveTarget[i]];
  45967. }
  45968. // Return appropriate value with its type
  45969. if (typeof (target) === "boolean")
  45970. return values[0] === "true";
  45971. if (typeof (target) === "string")
  45972. return values[0];
  45973. // Parameters with multiple values such as Vector3 etc.
  45974. var split = new Array();
  45975. for (var i = 0; i < values.length; i++)
  45976. split.push(parseFloat(values[i]));
  45977. if (target instanceof BABYLON.Vector3)
  45978. return BABYLON.Vector3.FromArray(split);
  45979. if (target instanceof BABYLON.Vector4)
  45980. return BABYLON.Vector4.FromArray(split);
  45981. if (target instanceof BABYLON.Color3)
  45982. return BABYLON.Color3.FromArray(split);
  45983. if (target instanceof BABYLON.Color4)
  45984. return BABYLON.Color4.FromArray(split);
  45985. return parseFloat(values[0]);
  45986. };
  45987. // traverse graph per trigger
  45988. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  45989. if (combineArray === void 0) { combineArray = null; }
  45990. if (parsedAction.detached)
  45991. return;
  45992. var parameters = new Array();
  45993. var target = null;
  45994. var propertyPath = null;
  45995. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  45996. // Parameters
  45997. if (parsedAction.type === 2)
  45998. parameters.push(actionManager);
  45999. else
  46000. parameters.push(trigger);
  46001. if (combine) {
  46002. var actions = new Array();
  46003. for (var j = 0; j < parsedAction.combine.length; j++) {
  46004. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  46005. }
  46006. parameters.push(actions);
  46007. }
  46008. else {
  46009. for (var i = 0; i < parsedAction.properties.length; i++) {
  46010. var value = parsedAction.properties[i].value;
  46011. var name = parsedAction.properties[i].name;
  46012. var targetType = parsedAction.properties[i].targetType;
  46013. if (name === "target")
  46014. if (targetType !== null && targetType === "SceneProperties")
  46015. value = target = scene;
  46016. else
  46017. value = target = scene.getNodeByName(value);
  46018. else if (name === "parent")
  46019. value = scene.getNodeByName(value);
  46020. else if (name === "sound")
  46021. value = scene.getSoundByName(value);
  46022. else if (name !== "propertyPath") {
  46023. if (parsedAction.type === 2 && name === "operator")
  46024. value = BABYLON.ValueCondition[value];
  46025. else
  46026. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  46027. }
  46028. else {
  46029. propertyPath = value;
  46030. }
  46031. parameters.push(value);
  46032. }
  46033. }
  46034. if (combineArray === null) {
  46035. parameters.push(condition);
  46036. }
  46037. else {
  46038. parameters.push(null);
  46039. }
  46040. // If interpolate value action
  46041. if (parsedAction.name === "InterpolateValueAction") {
  46042. var param = parameters[parameters.length - 2];
  46043. parameters[parameters.length - 1] = param;
  46044. parameters[parameters.length - 2] = condition;
  46045. }
  46046. // Action or condition(s) and not CombineAction
  46047. var newAction = instanciate(parsedAction.name, parameters);
  46048. if (newAction instanceof BABYLON.Condition && condition !== null) {
  46049. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  46050. if (action)
  46051. action.then(nothing);
  46052. else
  46053. actionManager.registerAction(nothing);
  46054. action = nothing;
  46055. }
  46056. if (combineArray === null) {
  46057. if (newAction instanceof BABYLON.Condition) {
  46058. condition = newAction;
  46059. newAction = action;
  46060. }
  46061. else {
  46062. condition = null;
  46063. if (action)
  46064. action.then(newAction);
  46065. else
  46066. actionManager.registerAction(newAction);
  46067. }
  46068. }
  46069. else {
  46070. combineArray.push(newAction);
  46071. }
  46072. for (var i = 0; i < parsedAction.children.length; i++)
  46073. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  46074. };
  46075. // triggers
  46076. for (var i = 0; i < parsedActions.children.length; i++) {
  46077. var triggerParams;
  46078. var trigger = parsedActions.children[i];
  46079. if (trigger.properties.length > 0) {
  46080. var param = trigger.properties[0].value;
  46081. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  46082. if (value._meshId) {
  46083. value.mesh = scene.getMeshByID(value._meshId);
  46084. }
  46085. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  46086. }
  46087. else
  46088. triggerParams = BABYLON.ActionManager[trigger.name];
  46089. for (var j = 0; j < trigger.children.length; j++) {
  46090. if (!trigger.detached)
  46091. traverse(trigger.children[j], triggerParams, null, null);
  46092. }
  46093. }
  46094. };
  46095. ActionManager.GetTriggerName = function (trigger) {
  46096. switch (trigger) {
  46097. case 0: return "NothingTrigger";
  46098. case 1: return "OnPickTrigger";
  46099. case 2: return "OnLeftPickTrigger";
  46100. case 3: return "OnRightPickTrigger";
  46101. case 4: return "OnCenterPickTrigger";
  46102. case 5: return "OnPickDownTrigger";
  46103. case 6: return "OnPickUpTrigger";
  46104. case 7: return "OnLongPressTrigger";
  46105. case 8: return "OnPointerOverTrigger";
  46106. case 9: return "OnPointerOutTrigger";
  46107. case 10: return "OnEveryFrameTrigger";
  46108. case 11: return "OnIntersectionEnterTrigger";
  46109. case 12: return "OnIntersectionExitTrigger";
  46110. case 13: return "OnKeyDownTrigger";
  46111. case 14: return "OnKeyUpTrigger";
  46112. case 15: return "OnPickOutTrigger";
  46113. default: return "";
  46114. }
  46115. };
  46116. // Statics
  46117. ActionManager._NothingTrigger = 0;
  46118. ActionManager._OnPickTrigger = 1;
  46119. ActionManager._OnLeftPickTrigger = 2;
  46120. ActionManager._OnRightPickTrigger = 3;
  46121. ActionManager._OnCenterPickTrigger = 4;
  46122. ActionManager._OnPickDownTrigger = 5;
  46123. ActionManager._OnDoublePickTrigger = 6;
  46124. ActionManager._OnPickUpTrigger = 7;
  46125. ActionManager._OnLongPressTrigger = 8;
  46126. ActionManager._OnPointerOverTrigger = 9;
  46127. ActionManager._OnPointerOutTrigger = 10;
  46128. ActionManager._OnEveryFrameTrigger = 11;
  46129. ActionManager._OnIntersectionEnterTrigger = 12;
  46130. ActionManager._OnIntersectionExitTrigger = 13;
  46131. ActionManager._OnKeyDownTrigger = 14;
  46132. ActionManager._OnKeyUpTrigger = 15;
  46133. ActionManager._OnPickOutTrigger = 16;
  46134. ActionManager.Triggers = {};
  46135. return ActionManager;
  46136. }());
  46137. BABYLON.ActionManager = ActionManager;
  46138. })(BABYLON || (BABYLON = {}));
  46139. //# sourceMappingURL=babylon.actionManager.js.map
  46140. var BABYLON;
  46141. (function (BABYLON) {
  46142. var InterpolateValueAction = (function (_super) {
  46143. __extends(InterpolateValueAction, _super);
  46144. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  46145. if (duration === void 0) { duration = 1000; }
  46146. var _this = _super.call(this, triggerOptions, condition) || this;
  46147. _this.propertyPath = propertyPath;
  46148. _this.value = value;
  46149. _this.duration = duration;
  46150. _this.stopOtherAnimations = stopOtherAnimations;
  46151. _this.onInterpolationDone = onInterpolationDone;
  46152. _this._target = _this._effectiveTarget = target;
  46153. return _this;
  46154. }
  46155. InterpolateValueAction.prototype._prepare = function () {
  46156. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46157. this._property = this._getProperty(this.propertyPath);
  46158. };
  46159. InterpolateValueAction.prototype.execute = function () {
  46160. var scene = this._actionManager.getScene();
  46161. var keys = [
  46162. {
  46163. frame: 0,
  46164. value: this._effectiveTarget[this._property]
  46165. }, {
  46166. frame: 100,
  46167. value: this.value
  46168. }
  46169. ];
  46170. var dataType;
  46171. if (typeof this.value === "number") {
  46172. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  46173. }
  46174. else if (this.value instanceof BABYLON.Color3) {
  46175. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  46176. }
  46177. else if (this.value instanceof BABYLON.Vector3) {
  46178. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  46179. }
  46180. else if (this.value instanceof BABYLON.Matrix) {
  46181. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  46182. }
  46183. else if (this.value instanceof BABYLON.Quaternion) {
  46184. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  46185. }
  46186. else {
  46187. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  46188. return;
  46189. }
  46190. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  46191. animation.setKeys(keys);
  46192. if (this.stopOtherAnimations) {
  46193. scene.stopAnimation(this._effectiveTarget);
  46194. }
  46195. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  46196. };
  46197. InterpolateValueAction.prototype.serialize = function (parent) {
  46198. return _super.prototype._serialize.call(this, {
  46199. name: "InterpolateValueAction",
  46200. properties: [
  46201. BABYLON.Action._GetTargetProperty(this._target),
  46202. { name: "propertyPath", value: this.propertyPath },
  46203. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46204. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  46205. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  46206. ]
  46207. }, parent);
  46208. };
  46209. return InterpolateValueAction;
  46210. }(BABYLON.Action));
  46211. BABYLON.InterpolateValueAction = InterpolateValueAction;
  46212. })(BABYLON || (BABYLON = {}));
  46213. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  46214. var BABYLON;
  46215. (function (BABYLON) {
  46216. var SwitchBooleanAction = (function (_super) {
  46217. __extends(SwitchBooleanAction, _super);
  46218. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  46219. var _this = _super.call(this, triggerOptions, condition) || this;
  46220. _this.propertyPath = propertyPath;
  46221. _this._target = _this._effectiveTarget = target;
  46222. return _this;
  46223. }
  46224. SwitchBooleanAction.prototype._prepare = function () {
  46225. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46226. this._property = this._getProperty(this.propertyPath);
  46227. };
  46228. SwitchBooleanAction.prototype.execute = function () {
  46229. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  46230. };
  46231. SwitchBooleanAction.prototype.serialize = function (parent) {
  46232. return _super.prototype._serialize.call(this, {
  46233. name: "SwitchBooleanAction",
  46234. properties: [
  46235. BABYLON.Action._GetTargetProperty(this._target),
  46236. { name: "propertyPath", value: this.propertyPath }
  46237. ]
  46238. }, parent);
  46239. };
  46240. return SwitchBooleanAction;
  46241. }(BABYLON.Action));
  46242. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  46243. var SetStateAction = (function (_super) {
  46244. __extends(SetStateAction, _super);
  46245. function SetStateAction(triggerOptions, target, value, condition) {
  46246. var _this = _super.call(this, triggerOptions, condition) || this;
  46247. _this.value = value;
  46248. _this._target = target;
  46249. return _this;
  46250. }
  46251. SetStateAction.prototype.execute = function () {
  46252. this._target.state = this.value;
  46253. };
  46254. SetStateAction.prototype.serialize = function (parent) {
  46255. return _super.prototype._serialize.call(this, {
  46256. name: "SetStateAction",
  46257. properties: [
  46258. BABYLON.Action._GetTargetProperty(this._target),
  46259. { name: "value", value: this.value }
  46260. ]
  46261. }, parent);
  46262. };
  46263. return SetStateAction;
  46264. }(BABYLON.Action));
  46265. BABYLON.SetStateAction = SetStateAction;
  46266. var SetValueAction = (function (_super) {
  46267. __extends(SetValueAction, _super);
  46268. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  46269. var _this = _super.call(this, triggerOptions, condition) || this;
  46270. _this.propertyPath = propertyPath;
  46271. _this.value = value;
  46272. _this._target = _this._effectiveTarget = target;
  46273. return _this;
  46274. }
  46275. SetValueAction.prototype._prepare = function () {
  46276. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46277. this._property = this._getProperty(this.propertyPath);
  46278. };
  46279. SetValueAction.prototype.execute = function () {
  46280. this._effectiveTarget[this._property] = this.value;
  46281. if (this._target.markAsDirty) {
  46282. this._target.markAsDirty(this._property);
  46283. }
  46284. };
  46285. SetValueAction.prototype.serialize = function (parent) {
  46286. return _super.prototype._serialize.call(this, {
  46287. name: "SetValueAction",
  46288. properties: [
  46289. BABYLON.Action._GetTargetProperty(this._target),
  46290. { name: "propertyPath", value: this.propertyPath },
  46291. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46292. ]
  46293. }, parent);
  46294. };
  46295. return SetValueAction;
  46296. }(BABYLON.Action));
  46297. BABYLON.SetValueAction = SetValueAction;
  46298. var IncrementValueAction = (function (_super) {
  46299. __extends(IncrementValueAction, _super);
  46300. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  46301. var _this = _super.call(this, triggerOptions, condition) || this;
  46302. _this.propertyPath = propertyPath;
  46303. _this.value = value;
  46304. _this._target = _this._effectiveTarget = target;
  46305. return _this;
  46306. }
  46307. IncrementValueAction.prototype._prepare = function () {
  46308. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46309. this._property = this._getProperty(this.propertyPath);
  46310. if (typeof this._effectiveTarget[this._property] !== "number") {
  46311. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  46312. }
  46313. };
  46314. IncrementValueAction.prototype.execute = function () {
  46315. this._effectiveTarget[this._property] += this.value;
  46316. if (this._target.markAsDirty) {
  46317. this._target.markAsDirty(this._property);
  46318. }
  46319. };
  46320. IncrementValueAction.prototype.serialize = function (parent) {
  46321. return _super.prototype._serialize.call(this, {
  46322. name: "IncrementValueAction",
  46323. properties: [
  46324. BABYLON.Action._GetTargetProperty(this._target),
  46325. { name: "propertyPath", value: this.propertyPath },
  46326. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46327. ]
  46328. }, parent);
  46329. };
  46330. return IncrementValueAction;
  46331. }(BABYLON.Action));
  46332. BABYLON.IncrementValueAction = IncrementValueAction;
  46333. var PlayAnimationAction = (function (_super) {
  46334. __extends(PlayAnimationAction, _super);
  46335. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  46336. var _this = _super.call(this, triggerOptions, condition) || this;
  46337. _this.from = from;
  46338. _this.to = to;
  46339. _this.loop = loop;
  46340. _this._target = target;
  46341. return _this;
  46342. }
  46343. PlayAnimationAction.prototype._prepare = function () {
  46344. };
  46345. PlayAnimationAction.prototype.execute = function () {
  46346. var scene = this._actionManager.getScene();
  46347. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  46348. };
  46349. PlayAnimationAction.prototype.serialize = function (parent) {
  46350. return _super.prototype._serialize.call(this, {
  46351. name: "PlayAnimationAction",
  46352. properties: [
  46353. BABYLON.Action._GetTargetProperty(this._target),
  46354. { name: "from", value: String(this.from) },
  46355. { name: "to", value: String(this.to) },
  46356. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  46357. ]
  46358. }, parent);
  46359. };
  46360. return PlayAnimationAction;
  46361. }(BABYLON.Action));
  46362. BABYLON.PlayAnimationAction = PlayAnimationAction;
  46363. var StopAnimationAction = (function (_super) {
  46364. __extends(StopAnimationAction, _super);
  46365. function StopAnimationAction(triggerOptions, target, condition) {
  46366. var _this = _super.call(this, triggerOptions, condition) || this;
  46367. _this._target = target;
  46368. return _this;
  46369. }
  46370. StopAnimationAction.prototype._prepare = function () {
  46371. };
  46372. StopAnimationAction.prototype.execute = function () {
  46373. var scene = this._actionManager.getScene();
  46374. scene.stopAnimation(this._target);
  46375. };
  46376. StopAnimationAction.prototype.serialize = function (parent) {
  46377. return _super.prototype._serialize.call(this, {
  46378. name: "StopAnimationAction",
  46379. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  46380. }, parent);
  46381. };
  46382. return StopAnimationAction;
  46383. }(BABYLON.Action));
  46384. BABYLON.StopAnimationAction = StopAnimationAction;
  46385. var DoNothingAction = (function (_super) {
  46386. __extends(DoNothingAction, _super);
  46387. function DoNothingAction(triggerOptions, condition) {
  46388. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  46389. return _super.call(this, triggerOptions, condition) || this;
  46390. }
  46391. DoNothingAction.prototype.execute = function () {
  46392. };
  46393. DoNothingAction.prototype.serialize = function (parent) {
  46394. return _super.prototype._serialize.call(this, {
  46395. name: "DoNothingAction",
  46396. properties: []
  46397. }, parent);
  46398. };
  46399. return DoNothingAction;
  46400. }(BABYLON.Action));
  46401. BABYLON.DoNothingAction = DoNothingAction;
  46402. var CombineAction = (function (_super) {
  46403. __extends(CombineAction, _super);
  46404. function CombineAction(triggerOptions, children, condition) {
  46405. var _this = _super.call(this, triggerOptions, condition) || this;
  46406. _this.children = children;
  46407. return _this;
  46408. }
  46409. CombineAction.prototype._prepare = function () {
  46410. for (var index = 0; index < this.children.length; index++) {
  46411. this.children[index]._actionManager = this._actionManager;
  46412. this.children[index]._prepare();
  46413. }
  46414. };
  46415. CombineAction.prototype.execute = function (evt) {
  46416. for (var index = 0; index < this.children.length; index++) {
  46417. this.children[index].execute(evt);
  46418. }
  46419. };
  46420. CombineAction.prototype.serialize = function (parent) {
  46421. var serializationObject = _super.prototype._serialize.call(this, {
  46422. name: "CombineAction",
  46423. properties: [],
  46424. combine: []
  46425. }, parent);
  46426. for (var i = 0; i < this.children.length; i++) {
  46427. serializationObject.combine.push(this.children[i].serialize(null));
  46428. }
  46429. return serializationObject;
  46430. };
  46431. return CombineAction;
  46432. }(BABYLON.Action));
  46433. BABYLON.CombineAction = CombineAction;
  46434. var ExecuteCodeAction = (function (_super) {
  46435. __extends(ExecuteCodeAction, _super);
  46436. function ExecuteCodeAction(triggerOptions, func, condition) {
  46437. var _this = _super.call(this, triggerOptions, condition) || this;
  46438. _this.func = func;
  46439. return _this;
  46440. }
  46441. ExecuteCodeAction.prototype.execute = function (evt) {
  46442. this.func(evt);
  46443. };
  46444. return ExecuteCodeAction;
  46445. }(BABYLON.Action));
  46446. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  46447. var SetParentAction = (function (_super) {
  46448. __extends(SetParentAction, _super);
  46449. function SetParentAction(triggerOptions, target, parent, condition) {
  46450. var _this = _super.call(this, triggerOptions, condition) || this;
  46451. _this._target = target;
  46452. _this._parent = parent;
  46453. return _this;
  46454. }
  46455. SetParentAction.prototype._prepare = function () {
  46456. };
  46457. SetParentAction.prototype.execute = function () {
  46458. if (this._target.parent === this._parent) {
  46459. return;
  46460. }
  46461. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  46462. invertParentWorldMatrix.invert();
  46463. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  46464. this._target.parent = this._parent;
  46465. };
  46466. SetParentAction.prototype.serialize = function (parent) {
  46467. return _super.prototype._serialize.call(this, {
  46468. name: "SetParentAction",
  46469. properties: [
  46470. BABYLON.Action._GetTargetProperty(this._target),
  46471. BABYLON.Action._GetTargetProperty(this._parent),
  46472. ]
  46473. }, parent);
  46474. };
  46475. return SetParentAction;
  46476. }(BABYLON.Action));
  46477. BABYLON.SetParentAction = SetParentAction;
  46478. var PlaySoundAction = (function (_super) {
  46479. __extends(PlaySoundAction, _super);
  46480. function PlaySoundAction(triggerOptions, sound, condition) {
  46481. var _this = _super.call(this, triggerOptions, condition) || this;
  46482. _this._sound = sound;
  46483. return _this;
  46484. }
  46485. PlaySoundAction.prototype._prepare = function () {
  46486. };
  46487. PlaySoundAction.prototype.execute = function () {
  46488. if (this._sound !== undefined)
  46489. this._sound.play();
  46490. };
  46491. PlaySoundAction.prototype.serialize = function (parent) {
  46492. return _super.prototype._serialize.call(this, {
  46493. name: "PlaySoundAction",
  46494. properties: [{ name: "sound", value: this._sound.name }]
  46495. }, parent);
  46496. };
  46497. return PlaySoundAction;
  46498. }(BABYLON.Action));
  46499. BABYLON.PlaySoundAction = PlaySoundAction;
  46500. var StopSoundAction = (function (_super) {
  46501. __extends(StopSoundAction, _super);
  46502. function StopSoundAction(triggerOptions, sound, condition) {
  46503. var _this = _super.call(this, triggerOptions, condition) || this;
  46504. _this._sound = sound;
  46505. return _this;
  46506. }
  46507. StopSoundAction.prototype._prepare = function () {
  46508. };
  46509. StopSoundAction.prototype.execute = function () {
  46510. if (this._sound !== undefined)
  46511. this._sound.stop();
  46512. };
  46513. StopSoundAction.prototype.serialize = function (parent) {
  46514. return _super.prototype._serialize.call(this, {
  46515. name: "StopSoundAction",
  46516. properties: [{ name: "sound", value: this._sound.name }]
  46517. }, parent);
  46518. };
  46519. return StopSoundAction;
  46520. }(BABYLON.Action));
  46521. BABYLON.StopSoundAction = StopSoundAction;
  46522. })(BABYLON || (BABYLON = {}));
  46523. //# sourceMappingURL=babylon.directActions.js.map
  46524. var BABYLON;
  46525. (function (BABYLON) {
  46526. var Debug;
  46527. (function (Debug) {
  46528. /**
  46529. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  46530. */
  46531. var SkeletonViewer = (function () {
  46532. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  46533. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  46534. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  46535. this.skeleton = skeleton;
  46536. this.mesh = mesh;
  46537. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  46538. this.renderingGroupId = renderingGroupId;
  46539. this.color = BABYLON.Color3.White();
  46540. this._debugLines = [];
  46541. this._isEnabled = false;
  46542. this._scene = scene;
  46543. this.update();
  46544. this._renderFunction = this.update.bind(this);
  46545. }
  46546. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  46547. get: function () {
  46548. return this._isEnabled;
  46549. },
  46550. set: function (value) {
  46551. if (this._isEnabled === value) {
  46552. return;
  46553. }
  46554. this._isEnabled = value;
  46555. if (value) {
  46556. this._scene.registerBeforeRender(this._renderFunction);
  46557. }
  46558. else {
  46559. this._scene.unregisterBeforeRender(this._renderFunction);
  46560. }
  46561. },
  46562. enumerable: true,
  46563. configurable: true
  46564. });
  46565. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  46566. if (x === void 0) { x = 0; }
  46567. if (y === void 0) { y = 0; }
  46568. if (z === void 0) { z = 0; }
  46569. var tmat = BABYLON.Tmp.Matrix[0];
  46570. var parentBone = bone.getParent();
  46571. tmat.copyFrom(bone.getLocalMatrix());
  46572. if (x !== 0 || y !== 0 || z !== 0) {
  46573. var tmat2 = BABYLON.Tmp.Matrix[1];
  46574. BABYLON.Matrix.IdentityToRef(tmat2);
  46575. tmat2.m[12] = x;
  46576. tmat2.m[13] = y;
  46577. tmat2.m[14] = z;
  46578. tmat2.multiplyToRef(tmat, tmat);
  46579. }
  46580. if (parentBone) {
  46581. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  46582. }
  46583. tmat.multiplyToRef(meshMat, tmat);
  46584. position.x = tmat.m[12];
  46585. position.y = tmat.m[13];
  46586. position.z = tmat.m[14];
  46587. };
  46588. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  46589. var len = bones.length;
  46590. var meshPos = this.mesh.position;
  46591. for (var i = 0; i < len; i++) {
  46592. var bone = bones[i];
  46593. var points = this._debugLines[i];
  46594. if (!points) {
  46595. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  46596. this._debugLines[i] = points;
  46597. }
  46598. this._getBonePosition(points[0], bone, meshMat);
  46599. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  46600. points[0].subtractInPlace(meshPos);
  46601. points[1].subtractInPlace(meshPos);
  46602. }
  46603. };
  46604. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  46605. var len = bones.length;
  46606. var boneNum = 0;
  46607. var meshPos = this.mesh.position;
  46608. for (var i = len - 1; i >= 0; i--) {
  46609. var childBone = bones[i];
  46610. var parentBone = childBone.getParent();
  46611. if (!parentBone) {
  46612. continue;
  46613. }
  46614. var points = this._debugLines[boneNum];
  46615. if (!points) {
  46616. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  46617. this._debugLines[boneNum] = points;
  46618. }
  46619. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  46620. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  46621. points[0].subtractInPlace(meshPos);
  46622. points[1].subtractInPlace(meshPos);
  46623. boneNum++;
  46624. }
  46625. };
  46626. SkeletonViewer.prototype.update = function () {
  46627. if (this.autoUpdateBonesMatrices) {
  46628. this.skeleton.computeAbsoluteTransforms();
  46629. }
  46630. if (this.skeleton.bones[0].length === undefined) {
  46631. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  46632. }
  46633. else {
  46634. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  46635. }
  46636. if (!this._debugMesh) {
  46637. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  46638. this._debugMesh.renderingGroupId = this.renderingGroupId;
  46639. }
  46640. else {
  46641. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  46642. }
  46643. this._debugMesh.position.copyFrom(this.mesh.position);
  46644. this._debugMesh.color = this.color;
  46645. };
  46646. SkeletonViewer.prototype.dispose = function () {
  46647. if (this._debugMesh) {
  46648. this.isEnabled = false;
  46649. this._debugMesh.dispose();
  46650. this._debugMesh = null;
  46651. }
  46652. };
  46653. return SkeletonViewer;
  46654. }());
  46655. Debug.SkeletonViewer = SkeletonViewer;
  46656. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  46657. })(BABYLON || (BABYLON = {}));
  46658. //# sourceMappingURL=babylon.skeletonViewer.js.map
  46659. var BABYLON;
  46660. (function (BABYLON) {
  46661. var Debug;
  46662. (function (Debug) {
  46663. var AxesViewer = (function () {
  46664. function AxesViewer(scene, scaleLines) {
  46665. if (scaleLines === void 0) { scaleLines = 1; }
  46666. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  46667. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  46668. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  46669. this.scaleLines = 1;
  46670. this.scaleLines = scaleLines;
  46671. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  46672. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  46673. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  46674. this._xmesh.renderingGroupId = 2;
  46675. this._ymesh.renderingGroupId = 2;
  46676. this._zmesh.renderingGroupId = 2;
  46677. this._xmesh.material.checkReadyOnlyOnce = true;
  46678. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  46679. this._ymesh.material.checkReadyOnlyOnce = true;
  46680. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  46681. this._zmesh.material.checkReadyOnlyOnce = true;
  46682. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  46683. this.scene = scene;
  46684. }
  46685. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  46686. var scaleLines = this.scaleLines;
  46687. this._xmesh.position.copyFrom(position);
  46688. this._ymesh.position.copyFrom(position);
  46689. this._zmesh.position.copyFrom(position);
  46690. var point2 = this._xline[1];
  46691. point2.x = xaxis.x * scaleLines;
  46692. point2.y = xaxis.y * scaleLines;
  46693. point2.z = xaxis.z * scaleLines;
  46694. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  46695. point2 = this._yline[1];
  46696. point2.x = yaxis.x * scaleLines;
  46697. point2.y = yaxis.y * scaleLines;
  46698. point2.z = yaxis.z * scaleLines;
  46699. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  46700. point2 = this._zline[1];
  46701. point2.x = zaxis.x * scaleLines;
  46702. point2.y = zaxis.y * scaleLines;
  46703. point2.z = zaxis.z * scaleLines;
  46704. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  46705. };
  46706. AxesViewer.prototype.dispose = function () {
  46707. if (this._xmesh) {
  46708. this._xmesh.dispose();
  46709. this._ymesh.dispose();
  46710. this._zmesh.dispose();
  46711. this._xmesh = null;
  46712. this._ymesh = null;
  46713. this._zmesh = null;
  46714. this._xline = null;
  46715. this._yline = null;
  46716. this._zline = null;
  46717. this.scene = null;
  46718. }
  46719. };
  46720. return AxesViewer;
  46721. }());
  46722. Debug.AxesViewer = AxesViewer;
  46723. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  46724. })(BABYLON || (BABYLON = {}));
  46725. //# sourceMappingURL=babylon.axesViewer.js.map
  46726. var BABYLON;
  46727. (function (BABYLON) {
  46728. var Debug;
  46729. (function (Debug) {
  46730. var BoneAxesViewer = (function (_super) {
  46731. __extends(BoneAxesViewer, _super);
  46732. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  46733. if (scaleLines === void 0) { scaleLines = 1; }
  46734. var _this = _super.call(this, scene, scaleLines) || this;
  46735. _this.pos = BABYLON.Vector3.Zero();
  46736. _this.xaxis = BABYLON.Vector3.Zero();
  46737. _this.yaxis = BABYLON.Vector3.Zero();
  46738. _this.zaxis = BABYLON.Vector3.Zero();
  46739. _this.mesh = mesh;
  46740. _this.bone = bone;
  46741. return _this;
  46742. }
  46743. BoneAxesViewer.prototype.update = function () {
  46744. var bone = this.bone;
  46745. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  46746. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  46747. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  46748. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  46749. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  46750. };
  46751. BoneAxesViewer.prototype.dispose = function () {
  46752. if (this.pos) {
  46753. this.pos = null;
  46754. this.xaxis = null;
  46755. this.yaxis = null;
  46756. this.zaxis = null;
  46757. this.mesh = null;
  46758. this.bone = null;
  46759. _super.prototype.dispose.call(this);
  46760. }
  46761. };
  46762. return BoneAxesViewer;
  46763. }(Debug.AxesViewer));
  46764. Debug.BoneAxesViewer = BoneAxesViewer;
  46765. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  46766. })(BABYLON || (BABYLON = {}));
  46767. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  46768. var BABYLON;
  46769. (function (BABYLON) {
  46770. var RayHelper = (function () {
  46771. function RayHelper(ray) {
  46772. this.ray = ray;
  46773. }
  46774. RayHelper.CreateAndShow = function (ray, scene, color) {
  46775. var helper = new RayHelper(ray);
  46776. helper.show(scene, color);
  46777. return helper;
  46778. };
  46779. RayHelper.prototype.show = function (scene, color) {
  46780. if (!this._renderFunction) {
  46781. var ray = this.ray;
  46782. this._renderFunction = this._render.bind(this);
  46783. this._scene = scene;
  46784. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  46785. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  46786. this._scene.registerBeforeRender(this._renderFunction);
  46787. }
  46788. if (color) {
  46789. this._renderLine.color.copyFrom(color);
  46790. }
  46791. };
  46792. RayHelper.prototype.hide = function () {
  46793. if (this._renderFunction) {
  46794. this._scene.unregisterBeforeRender(this._renderFunction);
  46795. this._scene = null;
  46796. this._renderFunction = null;
  46797. this._renderLine.dispose();
  46798. this._renderLine = null;
  46799. this._renderPoints = null;
  46800. }
  46801. };
  46802. RayHelper.prototype._render = function () {
  46803. var ray = this.ray;
  46804. var point = this._renderPoints[1];
  46805. var len = Math.min(ray.length, 1000000);
  46806. point.copyFrom(ray.direction);
  46807. point.scaleInPlace(len);
  46808. point.addInPlace(ray.origin);
  46809. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  46810. };
  46811. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  46812. this._attachedToMesh = mesh;
  46813. var ray = this.ray;
  46814. if (!ray.direction) {
  46815. ray.direction = BABYLON.Vector3.Zero();
  46816. }
  46817. if (!ray.origin) {
  46818. ray.origin = BABYLON.Vector3.Zero();
  46819. }
  46820. if (length) {
  46821. ray.length = length;
  46822. }
  46823. if (!meshSpaceOrigin) {
  46824. meshSpaceOrigin = BABYLON.Vector3.Zero();
  46825. }
  46826. if (!meshSpaceDirection) {
  46827. // -1 so that this will work with Mesh.lookAt
  46828. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  46829. }
  46830. if (!this._meshSpaceDirection) {
  46831. this._meshSpaceDirection = meshSpaceDirection.clone();
  46832. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  46833. }
  46834. else {
  46835. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  46836. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  46837. }
  46838. if (!this._updateToMeshFunction) {
  46839. this._updateToMeshFunction = this._updateToMesh.bind(this);
  46840. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  46841. }
  46842. this._updateToMesh();
  46843. };
  46844. RayHelper.prototype.detachFromMesh = function () {
  46845. if (this._attachedToMesh) {
  46846. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  46847. this._attachedToMesh = null;
  46848. this._updateToMeshFunction = null;
  46849. }
  46850. };
  46851. RayHelper.prototype._updateToMesh = function () {
  46852. var ray = this.ray;
  46853. if (this._attachedToMesh._isDisposed) {
  46854. this.detachFromMesh();
  46855. return;
  46856. }
  46857. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  46858. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  46859. };
  46860. RayHelper.prototype.dispose = function () {
  46861. this.hide();
  46862. this.detachFromMesh();
  46863. this.ray = null;
  46864. };
  46865. return RayHelper;
  46866. }());
  46867. BABYLON.RayHelper = RayHelper;
  46868. })(BABYLON || (BABYLON = {}));
  46869. //# sourceMappingURL=babylon.rayHelper.js.map
  46870. var BABYLON;
  46871. (function (BABYLON) {
  46872. var DebugLayer = (function () {
  46873. function DebugLayer(scene) {
  46874. this._scene = scene;
  46875. }
  46876. /** Creates the inspector window. */
  46877. DebugLayer.prototype._createInspector = function (config) {
  46878. if (config === void 0) { config = {}; }
  46879. var popup = config.popup || false;
  46880. var initialTab = config.initialTab || 0;
  46881. var parentElement = config.parentElement || null;
  46882. if (!this._inspector) {
  46883. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  46884. } // else nothing to do,; instance is already existing
  46885. };
  46886. DebugLayer.prototype.isVisible = function () {
  46887. if (!this._inspector) {
  46888. return false;
  46889. }
  46890. return true;
  46891. };
  46892. DebugLayer.prototype.hide = function () {
  46893. if (this._inspector) {
  46894. try {
  46895. this._inspector.dispose();
  46896. }
  46897. catch (e) {
  46898. // If the inspector has been removed directly from the inspector tool
  46899. }
  46900. this._inspector = null;
  46901. }
  46902. };
  46903. DebugLayer.prototype.show = function (config) {
  46904. if (config === void 0) { config = {}; }
  46905. if (typeof INSPECTOR == 'undefined') {
  46906. // Load inspector and add it to the DOM
  46907. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  46908. }
  46909. else {
  46910. // Otherwise creates the inspector
  46911. this._createInspector(config);
  46912. }
  46913. };
  46914. // Get protocol used - http or https
  46915. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  46916. return DebugLayer;
  46917. }());
  46918. BABYLON.DebugLayer = DebugLayer;
  46919. })(BABYLON || (BABYLON = {}));
  46920. //# sourceMappingURL=babylon.debugLayer.js.map
  46921. var BABYLON;
  46922. (function (BABYLON) {
  46923. var Debug;
  46924. (function (Debug) {
  46925. var PhysicsViewer = (function () {
  46926. function PhysicsViewer(scene) {
  46927. this._impostors = [];
  46928. this._meshes = [];
  46929. this._numMeshes = 0;
  46930. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46931. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  46932. }
  46933. PhysicsViewer.prototype._updateDebugMeshes = function () {
  46934. var plugin = this._physicsEnginePlugin;
  46935. for (var i = 0; i < this._numMeshes; i++) {
  46936. if (this._impostors[i].isDisposed) {
  46937. this.hideImpostor(this._impostors[i--]);
  46938. }
  46939. else {
  46940. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  46941. }
  46942. }
  46943. };
  46944. PhysicsViewer.prototype.showImpostor = function (impostor) {
  46945. for (var i = 0; i < this._numMeshes; i++) {
  46946. if (this._impostors[i] == impostor) {
  46947. return;
  46948. }
  46949. }
  46950. var debugMesh = this._getDebugMesh(impostor, this._scene);
  46951. if (debugMesh) {
  46952. this._impostors[this._numMeshes] = impostor;
  46953. this._meshes[this._numMeshes] = debugMesh;
  46954. if (this._numMeshes === 0) {
  46955. this._renderFunction = this._updateDebugMeshes.bind(this);
  46956. this._scene.registerBeforeRender(this._renderFunction);
  46957. }
  46958. this._numMeshes++;
  46959. }
  46960. };
  46961. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  46962. var removed = false;
  46963. for (var i = 0; i < this._numMeshes; i++) {
  46964. if (this._impostors[i] == impostor) {
  46965. this._scene.removeMesh(this._meshes[i]);
  46966. this._meshes[i].dispose();
  46967. this._numMeshes--;
  46968. if (this._numMeshes > 0) {
  46969. this._meshes[i] = this._meshes[this._numMeshes];
  46970. this._impostors[i] = this._impostors[this._numMeshes];
  46971. this._meshes[this._numMeshes] = null;
  46972. this._impostors[this._numMeshes] = null;
  46973. }
  46974. else {
  46975. this._meshes[0] = null;
  46976. this._impostors[0] = null;
  46977. }
  46978. removed = true;
  46979. break;
  46980. }
  46981. }
  46982. if (removed && this._numMeshes === 0) {
  46983. this._scene.unregisterBeforeRender(this._renderFunction);
  46984. }
  46985. };
  46986. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  46987. if (!this._debugMaterial) {
  46988. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  46989. this._debugMaterial.wireframe = true;
  46990. }
  46991. return this._debugMaterial;
  46992. };
  46993. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  46994. if (!this._debugBoxMesh) {
  46995. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  46996. this._debugBoxMesh.renderingGroupId = 1;
  46997. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  46998. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  46999. scene.removeMesh(this._debugBoxMesh);
  47000. }
  47001. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  47002. };
  47003. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  47004. if (!this._debugSphereMesh) {
  47005. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  47006. this._debugSphereMesh.renderingGroupId = 1;
  47007. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  47008. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  47009. scene.removeMesh(this._debugSphereMesh);
  47010. }
  47011. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  47012. };
  47013. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  47014. var body = impostor.physicsBody;
  47015. var shape = body.shapes[0];
  47016. var mesh;
  47017. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  47018. mesh = this._getDebugBoxMesh(scene);
  47019. impostor.getBoxSizeToRef(mesh.scaling);
  47020. }
  47021. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  47022. mesh = this._getDebugSphereMesh(scene);
  47023. var radius = impostor.getRadius();
  47024. mesh.scaling.x = radius * 2;
  47025. mesh.scaling.y = radius * 2;
  47026. mesh.scaling.z = radius * 2;
  47027. }
  47028. return mesh;
  47029. };
  47030. PhysicsViewer.prototype.dispose = function () {
  47031. for (var i = 0; i < this._numMeshes; i++) {
  47032. this.hideImpostor(this._impostors[i]);
  47033. }
  47034. if (this._debugBoxMesh) {
  47035. this._debugBoxMesh.dispose();
  47036. }
  47037. if (this._debugSphereMesh) {
  47038. this._debugSphereMesh.dispose();
  47039. }
  47040. if (this._debugMaterial) {
  47041. this._debugMaterial.dispose();
  47042. }
  47043. this._impostors.length = 0;
  47044. this._scene = null;
  47045. this._physicsEnginePlugin = null;
  47046. };
  47047. return PhysicsViewer;
  47048. }());
  47049. Debug.PhysicsViewer = PhysicsViewer;
  47050. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47051. })(BABYLON || (BABYLON = {}));
  47052. //# sourceMappingURL=babylon.physicsViewer.js.map
  47053. var BABYLON;
  47054. (function (BABYLON) {
  47055. var BoundingBoxRenderer = (function () {
  47056. function BoundingBoxRenderer(scene) {
  47057. this.frontColor = new BABYLON.Color3(1, 1, 1);
  47058. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  47059. this.showBackLines = true;
  47060. this.renderList = new BABYLON.SmartArray(32);
  47061. this._vertexBuffers = {};
  47062. this._scene = scene;
  47063. }
  47064. BoundingBoxRenderer.prototype._prepareRessources = function () {
  47065. if (this._colorShader) {
  47066. return;
  47067. }
  47068. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  47069. attributes: [BABYLON.VertexBuffer.PositionKind],
  47070. uniforms: ["world", "viewProjection", "color"]
  47071. });
  47072. var engine = this._scene.getEngine();
  47073. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  47074. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  47075. 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]);
  47076. };
  47077. BoundingBoxRenderer.prototype.reset = function () {
  47078. this.renderList.reset();
  47079. };
  47080. BoundingBoxRenderer.prototype.render = function () {
  47081. if (this.renderList.length === 0) {
  47082. return;
  47083. }
  47084. this._prepareRessources();
  47085. if (!this._colorShader.isReady()) {
  47086. return;
  47087. }
  47088. var engine = this._scene.getEngine();
  47089. engine.setDepthWrite(false);
  47090. this._colorShader._preBind();
  47091. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  47092. var boundingBox = this.renderList.data[boundingBoxIndex];
  47093. var min = boundingBox.minimum;
  47094. var max = boundingBox.maximum;
  47095. var diff = max.subtract(min);
  47096. var median = min.add(diff.scale(0.5));
  47097. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  47098. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  47099. .multiply(boundingBox.getWorldMatrix());
  47100. // VBOs
  47101. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  47102. if (this.showBackLines) {
  47103. // Back
  47104. engine.setDepthFunctionToGreaterOrEqual();
  47105. this._scene.resetCachedMaterial();
  47106. this._colorShader.setColor4("color", this.backColor.toColor4());
  47107. this._colorShader.bind(worldMatrix);
  47108. // Draw order
  47109. engine.draw(false, 0, 24);
  47110. }
  47111. // Front
  47112. engine.setDepthFunctionToLess();
  47113. this._scene.resetCachedMaterial();
  47114. this._colorShader.setColor4("color", this.frontColor.toColor4());
  47115. this._colorShader.bind(worldMatrix);
  47116. // Draw order
  47117. engine.draw(false, 0, 24);
  47118. }
  47119. this._colorShader.unbind();
  47120. engine.setDepthFunctionToLessOrEqual();
  47121. engine.setDepthWrite(true);
  47122. };
  47123. BoundingBoxRenderer.prototype.dispose = function () {
  47124. if (!this._colorShader) {
  47125. return;
  47126. }
  47127. this.renderList.dispose();
  47128. this._colorShader.dispose();
  47129. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  47130. if (buffer) {
  47131. buffer.dispose();
  47132. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  47133. }
  47134. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47135. };
  47136. return BoundingBoxRenderer;
  47137. }());
  47138. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  47139. })(BABYLON || (BABYLON = {}));
  47140. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  47141. var BABYLON;
  47142. (function (BABYLON) {
  47143. var TextureTools = (function () {
  47144. function TextureTools() {
  47145. }
  47146. /**
  47147. * Uses the GPU to create a copy texture rescaled at a given size
  47148. * @param texture Texture to copy from
  47149. * @param width Desired width
  47150. * @param height Desired height
  47151. * @return Generated texture
  47152. */
  47153. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  47154. if (useBilinearMode === void 0) { useBilinearMode = true; }
  47155. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  47156. var scene = texture.getScene();
  47157. var engine = scene.getEngine();
  47158. rtt.wrapU = texture.wrapU;
  47159. rtt.wrapV = texture.wrapV;
  47160. rtt.uOffset = texture.uOffset;
  47161. rtt.vOffset = texture.vOffset;
  47162. rtt.uScale = texture.uScale;
  47163. rtt.vScale = texture.vScale;
  47164. rtt.uAng = texture.uAng;
  47165. rtt.vAng = texture.vAng;
  47166. rtt.wAng = texture.wAng;
  47167. rtt.coordinatesIndex = texture.coordinatesIndex;
  47168. rtt.level = texture.level;
  47169. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  47170. rtt._texture.isReady = false;
  47171. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47172. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47173. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47174. passPostProcess.getEffect().executeWhenCompiled(function () {
  47175. passPostProcess.onApply = function (effect) {
  47176. effect.setTexture("textureSampler", texture);
  47177. };
  47178. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  47179. engine.unBindFramebuffer(rtt.getInternalTexture());
  47180. rtt.disposeFramebufferObjects();
  47181. passPostProcess.dispose();
  47182. rtt._texture.isReady = true;
  47183. });
  47184. return rtt;
  47185. };
  47186. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  47187. if (!scene._environmentBRDFTexture) {
  47188. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47189. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47190. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47191. scene._environmentBRDFTexture = texture;
  47192. }
  47193. return scene._environmentBRDFTexture;
  47194. };
  47195. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  47196. return TextureTools;
  47197. }());
  47198. BABYLON.TextureTools = TextureTools;
  47199. })(BABYLON || (BABYLON = {}));
  47200. //# sourceMappingURL=babylon.textureTools.js.map
  47201. var BABYLON;
  47202. (function (BABYLON) {
  47203. var SphericalPolynomial = (function () {
  47204. function SphericalPolynomial() {
  47205. this.x = BABYLON.Vector3.Zero();
  47206. this.y = BABYLON.Vector3.Zero();
  47207. this.z = BABYLON.Vector3.Zero();
  47208. this.xx = BABYLON.Vector3.Zero();
  47209. this.yy = BABYLON.Vector3.Zero();
  47210. this.zz = BABYLON.Vector3.Zero();
  47211. this.xy = BABYLON.Vector3.Zero();
  47212. this.yz = BABYLON.Vector3.Zero();
  47213. this.zx = BABYLON.Vector3.Zero();
  47214. }
  47215. SphericalPolynomial.prototype.addAmbient = function (color) {
  47216. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  47217. this.xx = this.xx.add(colorVector);
  47218. this.yy = this.yy.add(colorVector);
  47219. this.zz = this.zz.add(colorVector);
  47220. };
  47221. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  47222. var result = new SphericalPolynomial();
  47223. result.x = harmonics.L11.scale(1.02333);
  47224. result.y = harmonics.L1_1.scale(1.02333);
  47225. result.z = harmonics.L10.scale(1.02333);
  47226. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  47227. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  47228. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  47229. result.yz = harmonics.L2_1.scale(0.858086);
  47230. result.zx = harmonics.L21.scale(0.858086);
  47231. result.xy = harmonics.L2_2.scale(0.858086);
  47232. result.scale(1.0 / Math.PI);
  47233. return result;
  47234. };
  47235. SphericalPolynomial.prototype.scale = function (scale) {
  47236. this.x = this.x.scale(scale);
  47237. this.y = this.y.scale(scale);
  47238. this.z = this.z.scale(scale);
  47239. this.xx = this.xx.scale(scale);
  47240. this.yy = this.yy.scale(scale);
  47241. this.zz = this.zz.scale(scale);
  47242. this.yz = this.yz.scale(scale);
  47243. this.zx = this.zx.scale(scale);
  47244. this.xy = this.xy.scale(scale);
  47245. };
  47246. return SphericalPolynomial;
  47247. }());
  47248. BABYLON.SphericalPolynomial = SphericalPolynomial;
  47249. var SphericalHarmonics = (function () {
  47250. function SphericalHarmonics() {
  47251. this.L00 = BABYLON.Vector3.Zero();
  47252. this.L1_1 = BABYLON.Vector3.Zero();
  47253. this.L10 = BABYLON.Vector3.Zero();
  47254. this.L11 = BABYLON.Vector3.Zero();
  47255. this.L2_2 = BABYLON.Vector3.Zero();
  47256. this.L2_1 = BABYLON.Vector3.Zero();
  47257. this.L20 = BABYLON.Vector3.Zero();
  47258. this.L21 = BABYLON.Vector3.Zero();
  47259. this.L22 = BABYLON.Vector3.Zero();
  47260. }
  47261. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  47262. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  47263. var c = colorVector.scale(deltaSolidAngle);
  47264. this.L00 = this.L00.add(c.scale(0.282095));
  47265. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  47266. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  47267. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  47268. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  47269. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  47270. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  47271. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  47272. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  47273. };
  47274. SphericalHarmonics.prototype.scale = function (scale) {
  47275. this.L00 = this.L00.scale(scale);
  47276. this.L1_1 = this.L1_1.scale(scale);
  47277. this.L10 = this.L10.scale(scale);
  47278. this.L11 = this.L11.scale(scale);
  47279. this.L2_2 = this.L2_2.scale(scale);
  47280. this.L2_1 = this.L2_1.scale(scale);
  47281. this.L20 = this.L20.scale(scale);
  47282. this.L21 = this.L21.scale(scale);
  47283. this.L22 = this.L22.scale(scale);
  47284. };
  47285. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  47286. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  47287. //
  47288. // E_lm = A_l * L_lm
  47289. //
  47290. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  47291. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  47292. // the scaling factors are given in equation 9.
  47293. // Constant (Band 0)
  47294. this.L00 = this.L00.scale(3.141593);
  47295. // Linear (Band 1)
  47296. this.L1_1 = this.L1_1.scale(2.094395);
  47297. this.L10 = this.L10.scale(2.094395);
  47298. this.L11 = this.L11.scale(2.094395);
  47299. // Quadratic (Band 2)
  47300. this.L2_2 = this.L2_2.scale(0.785398);
  47301. this.L2_1 = this.L2_1.scale(0.785398);
  47302. this.L20 = this.L20.scale(0.785398);
  47303. this.L21 = this.L21.scale(0.785398);
  47304. this.L22 = this.L22.scale(0.785398);
  47305. };
  47306. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  47307. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  47308. // L = (1/pi) * E * rho
  47309. //
  47310. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  47311. this.scale(1.0 / Math.PI);
  47312. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  47313. // (The pixel shader must apply albedo after texture fetches, etc).
  47314. };
  47315. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  47316. var result = new SphericalHarmonics();
  47317. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  47318. result.L1_1 = polynomial.y.scale(0.977204);
  47319. result.L10 = polynomial.z.scale(0.977204);
  47320. result.L11 = polynomial.x.scale(0.977204);
  47321. result.L2_2 = polynomial.xy.scale(1.16538);
  47322. result.L2_1 = polynomial.yz.scale(1.16538);
  47323. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  47324. result.L21 = polynomial.zx.scale(1.16538);
  47325. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  47326. result.scale(Math.PI);
  47327. return result;
  47328. };
  47329. return SphericalHarmonics;
  47330. }());
  47331. BABYLON.SphericalHarmonics = SphericalHarmonics;
  47332. })(BABYLON || (BABYLON = {}));
  47333. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  47334. var BABYLON;
  47335. (function (BABYLON) {
  47336. var Internals;
  47337. (function (Internals) {
  47338. var FileFaceOrientation = (function () {
  47339. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  47340. this.name = name;
  47341. this.worldAxisForNormal = worldAxisForNormal;
  47342. this.worldAxisForFileX = worldAxisForFileX;
  47343. this.worldAxisForFileY = worldAxisForFileY;
  47344. }
  47345. return FileFaceOrientation;
  47346. }());
  47347. ;
  47348. /**
  47349. * Helper class dealing with the extraction of spherical polynomial dataArray
  47350. * from a cube map.
  47351. */
  47352. var CubeMapToSphericalPolynomialTools = (function () {
  47353. function CubeMapToSphericalPolynomialTools() {
  47354. }
  47355. /**
  47356. * Converts a texture to the according Spherical Polynomial data.
  47357. * This extracts the first 3 orders only as they are the only one used in the lighting.
  47358. *
  47359. * @param texture The texture to extract the information from.
  47360. * @return The Spherical Polynomial data.
  47361. */
  47362. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  47363. if (!texture.isCube) {
  47364. // Only supports cube Textures currently.
  47365. return null;
  47366. }
  47367. var size = texture.getSize().width;
  47368. var right = texture.readPixels(0);
  47369. var left = texture.readPixels(1);
  47370. var up;
  47371. var down;
  47372. if (texture.isRenderTarget) {
  47373. up = texture.readPixels(3);
  47374. down = texture.readPixels(2);
  47375. }
  47376. else {
  47377. up = texture.readPixels(2);
  47378. down = texture.readPixels(3);
  47379. }
  47380. var front = texture.readPixels(4);
  47381. var back = texture.readPixels(5);
  47382. var gammaSpace = texture.gammaSpace;
  47383. // Always read as RGBA.
  47384. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  47385. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47386. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47387. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47388. }
  47389. var cubeInfo = {
  47390. size: size,
  47391. right: right,
  47392. left: left,
  47393. up: up,
  47394. down: down,
  47395. front: front,
  47396. back: back,
  47397. format: format,
  47398. type: type,
  47399. gammaSpace: gammaSpace,
  47400. };
  47401. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  47402. };
  47403. /**
  47404. * Converts a cubemap to the according Spherical Polynomial data.
  47405. * This extracts the first 3 orders only as they are the only one used in the lighting.
  47406. *
  47407. * @param cubeInfo The Cube map to extract the information from.
  47408. * @return The Spherical Polynomial data.
  47409. */
  47410. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  47411. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  47412. var totalSolidAngle = 0.0;
  47413. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  47414. var du = 2.0 / cubeInfo.size;
  47415. var dv = du;
  47416. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  47417. var minUV = du * 0.5 - 1.0;
  47418. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  47419. var fileFace = this.FileFaces[faceIndex];
  47420. var dataArray = cubeInfo[fileFace.name];
  47421. var v = minUV;
  47422. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  47423. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  47424. // Because SP is still linear, so summation is fine in that basis.
  47425. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  47426. for (var y = 0; y < cubeInfo.size; y++) {
  47427. var u = minUV;
  47428. for (var x = 0; x < cubeInfo.size; x++) {
  47429. // World direction (not normalised)
  47430. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  47431. worldDirection.normalize();
  47432. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  47433. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  47434. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  47435. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  47436. // Handle Integer types.
  47437. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47438. r /= 255;
  47439. g /= 255;
  47440. b /= 255;
  47441. }
  47442. // Handle Gamma space textures.
  47443. if (cubeInfo.gammaSpace) {
  47444. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  47445. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  47446. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  47447. }
  47448. var color = new BABYLON.Color3(r, g, b);
  47449. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  47450. totalSolidAngle += deltaSolidAngle;
  47451. u += du;
  47452. }
  47453. v += dv;
  47454. }
  47455. }
  47456. // Solid angle for entire sphere is 4*pi
  47457. var sphereSolidAngle = 4.0 * Math.PI;
  47458. // Adjust the solid angle to allow for how many faces we processed.
  47459. var facesProcessed = 6.0;
  47460. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  47461. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  47462. // This is needed because the numerical integration over the cube uses a
  47463. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  47464. // and also to compensate for accumulative error due to float precision in the summation.
  47465. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  47466. sphericalHarmonics.scale(correctionFactor);
  47467. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  47468. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  47469. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  47470. };
  47471. CubeMapToSphericalPolynomialTools.FileFaces = [
  47472. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  47473. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  47474. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  47475. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  47476. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  47477. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  47478. ];
  47479. return CubeMapToSphericalPolynomialTools;
  47480. }());
  47481. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  47482. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47483. })(BABYLON || (BABYLON = {}));
  47484. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  47485. var BABYLON;
  47486. (function (BABYLON) {
  47487. var Internals;
  47488. (function (Internals) {
  47489. /**
  47490. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  47491. */
  47492. var PanoramaToCubeMapTools = (function () {
  47493. function PanoramaToCubeMapTools() {
  47494. }
  47495. /**
  47496. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  47497. *
  47498. * @param float32Array The source data.
  47499. * @param inputWidth The width of the input panorama.
  47500. * @param inputhHeight The height of the input panorama.
  47501. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  47502. * @return The cubemap data
  47503. */
  47504. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  47505. if (!float32Array) {
  47506. throw "ConvertPanoramaToCubemap: input cannot be null";
  47507. }
  47508. if (float32Array.length != inputWidth * inputHeight * 3) {
  47509. throw "ConvertPanoramaToCubemap: input size is wrong";
  47510. }
  47511. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  47512. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  47513. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  47514. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  47515. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  47516. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  47517. return {
  47518. front: textureFront,
  47519. back: textureBack,
  47520. left: textureLeft,
  47521. right: textureRight,
  47522. up: textureUp,
  47523. down: textureDown,
  47524. size: size,
  47525. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  47526. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  47527. gammaSpace: false,
  47528. };
  47529. };
  47530. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  47531. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  47532. var textureArray = new Float32Array(buffer);
  47533. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  47534. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  47535. var dy = 1 / texSize;
  47536. var fy = 0;
  47537. for (var y = 0; y < texSize; y++) {
  47538. var xv1 = faceData[0];
  47539. var xv2 = faceData[2];
  47540. for (var x = 0; x < texSize; x++) {
  47541. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  47542. v.normalize();
  47543. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  47544. // 3 channels per pixels
  47545. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  47546. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  47547. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  47548. xv1 = xv1.add(rotDX1);
  47549. xv2 = xv2.add(rotDX2);
  47550. }
  47551. fy += dy;
  47552. }
  47553. return textureArray;
  47554. };
  47555. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  47556. var theta = Math.atan2(vDir.z, vDir.x);
  47557. var phi = Math.acos(vDir.y);
  47558. while (theta < -Math.PI)
  47559. theta += 2 * Math.PI;
  47560. while (theta > Math.PI)
  47561. theta -= 2 * Math.PI;
  47562. var dx = theta / Math.PI;
  47563. var dy = phi / Math.PI;
  47564. // recenter.
  47565. dx = dx * 0.5 + 0.5;
  47566. var px = Math.round(dx * inputWidth);
  47567. if (px < 0)
  47568. px = 0;
  47569. else if (px >= inputWidth)
  47570. px = inputWidth - 1;
  47571. var py = Math.round(dy * inputHeight);
  47572. if (py < 0)
  47573. py = 0;
  47574. else if (py >= inputHeight)
  47575. py = inputHeight - 1;
  47576. var inputY = (inputHeight - py - 1);
  47577. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  47578. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  47579. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  47580. return {
  47581. r: r,
  47582. g: g,
  47583. b: b
  47584. };
  47585. };
  47586. PanoramaToCubeMapTools.FACE_FRONT = [
  47587. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  47588. new BABYLON.Vector3(1.0, -1.0, -1.0),
  47589. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  47590. new BABYLON.Vector3(1.0, 1.0, -1.0)
  47591. ];
  47592. PanoramaToCubeMapTools.FACE_BACK = [
  47593. new BABYLON.Vector3(1.0, -1.0, 1.0),
  47594. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  47595. new BABYLON.Vector3(1.0, 1.0, 1.0),
  47596. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  47597. ];
  47598. PanoramaToCubeMapTools.FACE_RIGHT = [
  47599. new BABYLON.Vector3(1.0, -1.0, -1.0),
  47600. new BABYLON.Vector3(1.0, -1.0, 1.0),
  47601. new BABYLON.Vector3(1.0, 1.0, -1.0),
  47602. new BABYLON.Vector3(1.0, 1.0, 1.0)
  47603. ];
  47604. PanoramaToCubeMapTools.FACE_LEFT = [
  47605. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  47606. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  47607. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  47608. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  47609. ];
  47610. PanoramaToCubeMapTools.FACE_DOWN = [
  47611. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  47612. new BABYLON.Vector3(1.0, 1.0, -1.0),
  47613. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  47614. new BABYLON.Vector3(1.0, 1.0, 1.0)
  47615. ];
  47616. PanoramaToCubeMapTools.FACE_UP = [
  47617. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  47618. new BABYLON.Vector3(1.0, -1.0, 1.0),
  47619. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  47620. new BABYLON.Vector3(1.0, -1.0, -1.0)
  47621. ];
  47622. return PanoramaToCubeMapTools;
  47623. }());
  47624. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  47625. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47626. })(BABYLON || (BABYLON = {}));
  47627. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  47628. var BABYLON;
  47629. (function (BABYLON) {
  47630. var Internals;
  47631. (function (Internals) {
  47632. ;
  47633. /**
  47634. * This groups tools to convert HDR texture to native colors array.
  47635. */
  47636. var HDRTools = (function () {
  47637. function HDRTools() {
  47638. }
  47639. HDRTools.Ldexp = function (mantissa, exponent) {
  47640. if (exponent > 1023) {
  47641. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  47642. }
  47643. if (exponent < -1074) {
  47644. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  47645. }
  47646. return mantissa * Math.pow(2, exponent);
  47647. };
  47648. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  47649. if (exponent > 0) {
  47650. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  47651. float32array[index + 0] = red * exponent;
  47652. float32array[index + 1] = green * exponent;
  47653. float32array[index + 2] = blue * exponent;
  47654. }
  47655. else {
  47656. float32array[index + 0] = 0;
  47657. float32array[index + 1] = 0;
  47658. float32array[index + 2] = 0;
  47659. }
  47660. };
  47661. HDRTools.readStringLine = function (uint8array, startIndex) {
  47662. var line = "";
  47663. var character = "";
  47664. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  47665. character = String.fromCharCode(uint8array[i]);
  47666. if (character == "\n") {
  47667. break;
  47668. }
  47669. line += character;
  47670. }
  47671. return line;
  47672. };
  47673. /**
  47674. * Reads header information from an RGBE texture stored in a native array.
  47675. * More information on this format are available here:
  47676. * https://en.wikipedia.org/wiki/RGBE_image_format
  47677. *
  47678. * @param uint8array The binary file stored in native array.
  47679. * @return The header information.
  47680. */
  47681. HDRTools.RGBE_ReadHeader = function (uint8array) {
  47682. var height = 0;
  47683. var width = 0;
  47684. var line = this.readStringLine(uint8array, 0);
  47685. if (line[0] != '#' || line[1] != '?') {
  47686. throw "Bad HDR Format.";
  47687. }
  47688. var endOfHeader = false;
  47689. var findFormat = false;
  47690. var lineIndex = 0;
  47691. do {
  47692. lineIndex += (line.length + 1);
  47693. line = this.readStringLine(uint8array, lineIndex);
  47694. if (line == "FORMAT=32-bit_rle_rgbe") {
  47695. findFormat = true;
  47696. }
  47697. else if (line.length == 0) {
  47698. endOfHeader = true;
  47699. }
  47700. } while (!endOfHeader);
  47701. if (!findFormat) {
  47702. throw "HDR Bad header format, unsupported FORMAT";
  47703. }
  47704. lineIndex += (line.length + 1);
  47705. line = this.readStringLine(uint8array, lineIndex);
  47706. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  47707. var match = sizeRegexp.exec(line);
  47708. // TODO. Support +Y and -X if needed.
  47709. if (match.length < 3) {
  47710. throw "HDR Bad header format, no size";
  47711. }
  47712. width = parseInt(match[2]);
  47713. height = parseInt(match[1]);
  47714. if (width < 8 || width > 0x7fff) {
  47715. throw "HDR Bad header format, unsupported size";
  47716. }
  47717. lineIndex += (line.length + 1);
  47718. return {
  47719. height: height,
  47720. width: width,
  47721. dataPosition: lineIndex
  47722. };
  47723. };
  47724. /**
  47725. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  47726. * This RGBE texture needs to store the information as a panorama.
  47727. *
  47728. * More information on this format are available here:
  47729. * https://en.wikipedia.org/wiki/RGBE_image_format
  47730. *
  47731. * @param buffer The binary file stored in an array buffer.
  47732. * @param size The expected size of the extracted cubemap.
  47733. * @return The Cube Map information.
  47734. */
  47735. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  47736. var uint8array = new Uint8Array(buffer);
  47737. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  47738. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  47739. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  47740. return cubeMapData;
  47741. };
  47742. /**
  47743. * Returns the pixels data extracted from an RGBE texture.
  47744. * This pixels will be stored left to right up to down in the R G B order in one array.
  47745. *
  47746. * More information on this format are available here:
  47747. * https://en.wikipedia.org/wiki/RGBE_image_format
  47748. *
  47749. * @param uint8array The binary file stored in an array buffer.
  47750. * @param hdrInfo The header information of the file.
  47751. * @return The pixels data in RGB right to left up to down order.
  47752. */
  47753. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  47754. // Keep for multi format supports.
  47755. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  47756. };
  47757. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  47758. var num_scanlines = hdrInfo.height;
  47759. var scanline_width = hdrInfo.width;
  47760. var a, b, c, d, count;
  47761. var dataIndex = hdrInfo.dataPosition;
  47762. var index = 0, endIndex = 0, i = 0;
  47763. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  47764. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  47765. // 3 channels of 4 bytes per pixel in float.
  47766. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  47767. var resultArray = new Float32Array(resultBuffer);
  47768. // read in each successive scanline
  47769. while (num_scanlines > 0) {
  47770. a = uint8array[dataIndex++];
  47771. b = uint8array[dataIndex++];
  47772. c = uint8array[dataIndex++];
  47773. d = uint8array[dataIndex++];
  47774. if (a != 2 || b != 2 || (c & 0x80)) {
  47775. // this file is not run length encoded
  47776. throw "HDR Bad header format, not RLE";
  47777. }
  47778. if (((c << 8) | d) != scanline_width) {
  47779. throw "HDR Bad header format, wrong scan line width";
  47780. }
  47781. index = 0;
  47782. // read each of the four channels for the scanline into the buffer
  47783. for (i = 0; i < 4; i++) {
  47784. endIndex = (i + 1) * scanline_width;
  47785. while (index < endIndex) {
  47786. a = uint8array[dataIndex++];
  47787. b = uint8array[dataIndex++];
  47788. if (a > 128) {
  47789. // a run of the same value
  47790. count = a - 128;
  47791. if ((count == 0) || (count > endIndex - index)) {
  47792. throw "HDR Bad Format, bad scanline data (run)";
  47793. }
  47794. while (count-- > 0) {
  47795. scanLineArray[index++] = b;
  47796. }
  47797. }
  47798. else {
  47799. // a non-run
  47800. count = a;
  47801. if ((count == 0) || (count > endIndex - index)) {
  47802. throw "HDR Bad Format, bad scanline data (non-run)";
  47803. }
  47804. scanLineArray[index++] = b;
  47805. if (--count > 0) {
  47806. for (var j = 0; j < count; j++) {
  47807. scanLineArray[index++] = uint8array[dataIndex++];
  47808. }
  47809. }
  47810. }
  47811. }
  47812. }
  47813. // now convert data from buffer into floats
  47814. for (i = 0; i < scanline_width; i++) {
  47815. a = scanLineArray[i];
  47816. b = scanLineArray[i + scanline_width];
  47817. c = scanLineArray[i + 2 * scanline_width];
  47818. d = scanLineArray[i + 3 * scanline_width];
  47819. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  47820. }
  47821. num_scanlines--;
  47822. }
  47823. return resultArray;
  47824. };
  47825. return HDRTools;
  47826. }());
  47827. Internals.HDRTools = HDRTools;
  47828. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47829. })(BABYLON || (BABYLON = {}));
  47830. //# sourceMappingURL=babylon.hdr.js.map
  47831. var BABYLON;
  47832. (function (BABYLON) {
  47833. /**
  47834. * This represents a texture coming from an HDR input.
  47835. *
  47836. * The only supported format is currently panorama picture stored in RGBE format.
  47837. * Example of such files can be found on HDRLib: http://hdrlib.com/
  47838. */
  47839. var HDRCubeTexture = (function (_super) {
  47840. __extends(HDRCubeTexture, _super);
  47841. /**
  47842. * Instantiates an HDRTexture from the following parameters.
  47843. *
  47844. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  47845. * @param scene The scene the texture will be used in
  47846. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  47847. * @param noMipmap Forces to not generate the mipmap if true
  47848. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  47849. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  47850. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  47851. */
  47852. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  47853. if (noMipmap === void 0) { noMipmap = false; }
  47854. if (generateHarmonics === void 0) { generateHarmonics = true; }
  47855. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  47856. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  47857. if (onLoad === void 0) { onLoad = null; }
  47858. if (onError === void 0) { onError = null; }
  47859. var _this = _super.call(this, scene) || this;
  47860. _this._useInGammaSpace = false;
  47861. _this._generateHarmonics = true;
  47862. _this._isBABYLONPreprocessed = false;
  47863. _this._onLoad = null;
  47864. _this._onError = null;
  47865. /**
  47866. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  47867. */
  47868. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  47869. /**
  47870. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  47871. * This is usefull at run time to apply the good shader.
  47872. */
  47873. _this.isPMREM = false;
  47874. _this._isBlocking = true;
  47875. if (!url) {
  47876. return _this;
  47877. }
  47878. _this.name = url;
  47879. _this.url = url;
  47880. _this.hasAlpha = false;
  47881. _this.isCube = true;
  47882. _this._textureMatrix = BABYLON.Matrix.Identity();
  47883. _this._onLoad = onLoad;
  47884. _this._onError = onError;
  47885. _this.gammaSpace = false;
  47886. if (size) {
  47887. _this._isBABYLONPreprocessed = false;
  47888. _this._noMipmap = noMipmap;
  47889. _this._size = size;
  47890. _this._useInGammaSpace = useInGammaSpace;
  47891. _this._usePMREMGenerator = usePMREMGenerator &&
  47892. scene.getEngine().getCaps().textureLOD &&
  47893. _this.getScene().getEngine().getCaps().textureFloat &&
  47894. !_this._useInGammaSpace;
  47895. }
  47896. else {
  47897. _this._isBABYLONPreprocessed = true;
  47898. _this._noMipmap = false;
  47899. _this._useInGammaSpace = false;
  47900. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  47901. _this.getScene().getEngine().getCaps().textureFloat &&
  47902. !_this._useInGammaSpace;
  47903. }
  47904. _this.isPMREM = _this._usePMREMGenerator;
  47905. _this._texture = _this._getFromCache(url, _this._noMipmap);
  47906. if (!_this._texture) {
  47907. if (!scene.useDelayedTextureLoading) {
  47908. _this.loadTexture();
  47909. }
  47910. else {
  47911. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  47912. }
  47913. }
  47914. return _this;
  47915. }
  47916. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  47917. /**
  47918. * Gets wether or not the texture is blocking during loading.
  47919. */
  47920. get: function () {
  47921. return this._isBlocking;
  47922. },
  47923. /**
  47924. * Sets wether or not the texture is blocking during loading.
  47925. */
  47926. set: function (value) {
  47927. this._isBlocking = value;
  47928. },
  47929. enumerable: true,
  47930. configurable: true
  47931. });
  47932. /**
  47933. * Occurs when the file is a preprocessed .babylon.hdr file.
  47934. */
  47935. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  47936. var _this = this;
  47937. var mipLevels = 0;
  47938. var floatArrayView = null;
  47939. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  47940. var mips = [];
  47941. var startIndex = 30;
  47942. for (var level = 0; level < mipLevels; level++) {
  47943. mips.push([]);
  47944. // Fill each pixel of the mip level.
  47945. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  47946. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  47947. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  47948. mips[level].push(faceData);
  47949. startIndex += faceSize;
  47950. }
  47951. }
  47952. return mips;
  47953. } : null;
  47954. var callback = function (buffer) {
  47955. // Create Native Array Views
  47956. var intArrayView = new Int32Array(buffer);
  47957. floatArrayView = new Float32Array(buffer);
  47958. // Fill header.
  47959. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  47960. _this._size = intArrayView[1]; // CubeMap max mip face size.
  47961. // Update Texture Information.
  47962. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  47963. // Fill polynomial information.
  47964. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  47965. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  47966. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  47967. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  47968. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  47969. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  47970. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  47971. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  47972. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  47973. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  47974. _this.sphericalPolynomial = sphericalPolynomial;
  47975. // Fill pixel data.
  47976. mipLevels = intArrayView[29]; // Number of mip levels.
  47977. var startIndex = 30;
  47978. var data = [];
  47979. var faceSize = Math.pow(_this._size, 2) * 3;
  47980. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  47981. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  47982. startIndex += faceSize;
  47983. }
  47984. var results = [];
  47985. var byteArray = null;
  47986. // Push each faces.
  47987. for (var k = 0; k < 6; k++) {
  47988. var dataFace = null;
  47989. // To be deprecated.
  47990. if (version === 1) {
  47991. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  47992. dataFace = data[j];
  47993. }
  47994. // If special cases.
  47995. if (!mipmapGenerator) {
  47996. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  47997. // 3 channels of 1 bytes per pixel in bytes.
  47998. var byteBuffer = new ArrayBuffer(faceSize);
  47999. byteArray = new Uint8Array(byteBuffer);
  48000. }
  48001. for (var i = 0; i < _this._size * _this._size; i++) {
  48002. // Put in gamma space if requested.
  48003. if (_this._useInGammaSpace) {
  48004. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48005. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48006. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48007. }
  48008. // Convert to int texture for fallback.
  48009. if (byteArray) {
  48010. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48011. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48012. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48013. // May use luminance instead if the result is not accurate.
  48014. var max = Math.max(Math.max(r, g), b);
  48015. if (max > 255) {
  48016. var scale = 255 / max;
  48017. r *= scale;
  48018. g *= scale;
  48019. b *= scale;
  48020. }
  48021. byteArray[(i * 3) + 0] = r;
  48022. byteArray[(i * 3) + 1] = g;
  48023. byteArray[(i * 3) + 2] = b;
  48024. }
  48025. }
  48026. }
  48027. // Fill the array accordingly.
  48028. if (byteArray) {
  48029. results.push(byteArray);
  48030. }
  48031. else {
  48032. results.push(dataFace);
  48033. }
  48034. }
  48035. return results;
  48036. };
  48037. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  48038. };
  48039. /**
  48040. * Occurs when the file is raw .hdr file.
  48041. */
  48042. HDRCubeTexture.prototype.loadHDRTexture = function () {
  48043. var _this = this;
  48044. var callback = function (buffer) {
  48045. // Extract the raw linear data.
  48046. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  48047. // Generate harmonics if needed.
  48048. if (_this._generateHarmonics) {
  48049. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  48050. _this.sphericalPolynomial = sphericalPolynomial;
  48051. }
  48052. var results = [];
  48053. var byteArray = null;
  48054. // Push each faces.
  48055. for (var j = 0; j < 6; j++) {
  48056. // Create uintarray fallback.
  48057. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  48058. // 3 channels of 1 bytes per pixel in bytes.
  48059. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  48060. byteArray = new Uint8Array(byteBuffer);
  48061. }
  48062. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  48063. // If special cases.
  48064. if (_this._useInGammaSpace || byteArray) {
  48065. for (var i = 0; i < _this._size * _this._size; i++) {
  48066. // Put in gamma space if requested.
  48067. if (_this._useInGammaSpace) {
  48068. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48069. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48070. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48071. }
  48072. // Convert to int texture for fallback.
  48073. if (byteArray) {
  48074. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48075. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48076. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48077. // May use luminance instead if the result is not accurate.
  48078. var max = Math.max(Math.max(r, g), b);
  48079. if (max > 255) {
  48080. var scale = 255 / max;
  48081. r *= scale;
  48082. g *= scale;
  48083. b *= scale;
  48084. }
  48085. byteArray[(i * 3) + 0] = r;
  48086. byteArray[(i * 3) + 1] = g;
  48087. byteArray[(i * 3) + 2] = b;
  48088. }
  48089. }
  48090. }
  48091. if (byteArray) {
  48092. results.push(byteArray);
  48093. }
  48094. else {
  48095. results.push(dataFace);
  48096. }
  48097. }
  48098. return results;
  48099. };
  48100. var mipmapGenerator = null;
  48101. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  48102. // if (!this._noMipmap &&
  48103. // this._usePMREMGenerator) {
  48104. // mipmapGenerator = (data: ArrayBufferView[]) => {
  48105. // // Custom setup of the generator matching with the PBR shader values.
  48106. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  48107. // this._size,
  48108. // this._size,
  48109. // 0,
  48110. // 3,
  48111. // this.getScene().getEngine().getCaps().textureFloat,
  48112. // 2048,
  48113. // 0.25,
  48114. // false,
  48115. // true);
  48116. // return generator.filterCubeMap();
  48117. // };
  48118. // }
  48119. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  48120. };
  48121. /**
  48122. * Starts the loading process of the texture.
  48123. */
  48124. HDRCubeTexture.prototype.loadTexture = function () {
  48125. if (this._isBABYLONPreprocessed) {
  48126. this.loadBabylonTexture();
  48127. }
  48128. else {
  48129. this.loadHDRTexture();
  48130. }
  48131. };
  48132. HDRCubeTexture.prototype.clone = function () {
  48133. var size = this._isBABYLONPreprocessed ? null : this._size;
  48134. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  48135. // Base texture
  48136. newTexture.level = this.level;
  48137. newTexture.wrapU = this.wrapU;
  48138. newTexture.wrapV = this.wrapV;
  48139. newTexture.coordinatesIndex = this.coordinatesIndex;
  48140. newTexture.coordinatesMode = this.coordinatesMode;
  48141. return newTexture;
  48142. };
  48143. // Methods
  48144. HDRCubeTexture.prototype.delayLoad = function () {
  48145. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  48146. return;
  48147. }
  48148. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  48149. this._texture = this._getFromCache(this.url, this._noMipmap);
  48150. if (!this._texture) {
  48151. this.loadTexture();
  48152. }
  48153. };
  48154. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  48155. return this._textureMatrix;
  48156. };
  48157. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  48158. this._textureMatrix = value;
  48159. };
  48160. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  48161. var texture = null;
  48162. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  48163. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  48164. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  48165. texture.name = parsedTexture.name;
  48166. texture.hasAlpha = parsedTexture.hasAlpha;
  48167. texture.level = parsedTexture.level;
  48168. texture.coordinatesMode = parsedTexture.coordinatesMode;
  48169. texture.isBlocking = parsedTexture.isBlocking;
  48170. }
  48171. return texture;
  48172. };
  48173. HDRCubeTexture.prototype.serialize = function () {
  48174. if (!this.name) {
  48175. return null;
  48176. }
  48177. var serializationObject = {};
  48178. serializationObject.name = this.name;
  48179. serializationObject.hasAlpha = this.hasAlpha;
  48180. serializationObject.isCube = true;
  48181. serializationObject.level = this.level;
  48182. serializationObject.size = this._size;
  48183. serializationObject.coordinatesMode = this.coordinatesMode;
  48184. serializationObject.useInGammaSpace = this._useInGammaSpace;
  48185. serializationObject.generateHarmonics = this._generateHarmonics;
  48186. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  48187. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  48188. serializationObject.customType = "BABYLON.HDRCubeTexture";
  48189. serializationObject.noMipmap = this._noMipmap;
  48190. serializationObject.isBlocking = this._isBlocking;
  48191. return serializationObject;
  48192. };
  48193. /**
  48194. * Saves as a file the data contained in the texture in a binary format.
  48195. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  48196. * as the spherical used in the lighting.
  48197. * @param url The HDR file url.
  48198. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  48199. * @param onError Method called if any error happens during download.
  48200. * @return The packed binary data.
  48201. */
  48202. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  48203. if (onError === void 0) { onError = null; }
  48204. var callback = function (buffer) {
  48205. var data = new Blob([buffer], { type: 'application/octet-stream' });
  48206. // Returns a URL you can use as a href.
  48207. var objUrl = window.URL.createObjectURL(data);
  48208. // Simulates a link to it and click to dowload.
  48209. var a = document.createElement("a");
  48210. document.body.appendChild(a);
  48211. a.style.display = "none";
  48212. a.href = objUrl;
  48213. a.download = "envmap.babylon.hdr";
  48214. a.click();
  48215. };
  48216. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  48217. };
  48218. /**
  48219. * Serializes the data contained in the texture in a binary format.
  48220. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  48221. * as the spherical used in the lighting.
  48222. * @param url The HDR file url.
  48223. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  48224. * @param onError Method called if any error happens during download.
  48225. * @return The packed binary data.
  48226. */
  48227. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  48228. if (onError === void 0) { onError = null; }
  48229. // Needs the url tho create the texture.
  48230. if (!url) {
  48231. return null;
  48232. }
  48233. // Check Power of two size.
  48234. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  48235. return null;
  48236. }
  48237. // Coming Back in 3.1.
  48238. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  48239. return null;
  48240. };
  48241. HDRCubeTexture._facesMapping = [
  48242. "right",
  48243. "left",
  48244. "up",
  48245. "down",
  48246. "front",
  48247. "back"
  48248. ];
  48249. return HDRCubeTexture;
  48250. }(BABYLON.BaseTexture));
  48251. BABYLON.HDRCubeTexture = HDRCubeTexture;
  48252. })(BABYLON || (BABYLON = {}));
  48253. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  48254. var BABYLON;
  48255. (function (BABYLON) {
  48256. var DefaultLoadingScreen = (function () {
  48257. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  48258. if (_loadingText === void 0) { _loadingText = ""; }
  48259. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  48260. var _this = this;
  48261. this._renderingCanvas = _renderingCanvas;
  48262. this._loadingText = _loadingText;
  48263. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  48264. // Resize
  48265. this._resizeLoadingUI = function () {
  48266. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  48267. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  48268. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  48269. _this._loadingDiv.style.left = canvasRect.left + "px";
  48270. _this._loadingDiv.style.top = canvasRect.top + "px";
  48271. _this._loadingDiv.style.width = canvasRect.width + "px";
  48272. _this._loadingDiv.style.height = canvasRect.height + "px";
  48273. };
  48274. }
  48275. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  48276. if (this._loadingDiv) {
  48277. // Do not add a loading screen if there is already one
  48278. return;
  48279. }
  48280. this._loadingDiv = document.createElement("div");
  48281. this._loadingDiv.id = "babylonjsLoadingDiv";
  48282. this._loadingDiv.style.opacity = "0";
  48283. this._loadingDiv.style.transition = "opacity 1.5s ease";
  48284. // Loading text
  48285. this._loadingTextDiv = document.createElement("div");
  48286. this._loadingTextDiv.style.position = "absolute";
  48287. this._loadingTextDiv.style.left = "0";
  48288. this._loadingTextDiv.style.top = "50%";
  48289. this._loadingTextDiv.style.marginTop = "80px";
  48290. this._loadingTextDiv.style.width = "100%";
  48291. this._loadingTextDiv.style.height = "20px";
  48292. this._loadingTextDiv.style.fontFamily = "Arial";
  48293. this._loadingTextDiv.style.fontSize = "14px";
  48294. this._loadingTextDiv.style.color = "white";
  48295. this._loadingTextDiv.style.textAlign = "center";
  48296. this._loadingTextDiv.innerHTML = "Loading";
  48297. this._loadingDiv.appendChild(this._loadingTextDiv);
  48298. //set the predefined text
  48299. this._loadingTextDiv.innerHTML = this._loadingText;
  48300. // Generating keyframes
  48301. var style = document.createElement('style');
  48302. style.type = 'text/css';
  48303. var keyFrames = "@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }";
  48304. style.innerHTML = keyFrames;
  48305. document.getElementsByTagName('head')[0].appendChild(style);
  48306. // Loading img
  48307. var imgBack = new Image();
  48308. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  48309. imgBack.style.position = "absolute";
  48310. imgBack.style.left = "50%";
  48311. imgBack.style.top = "50%";
  48312. imgBack.style.marginLeft = "-60px";
  48313. imgBack.style.marginTop = "-60px";
  48314. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  48315. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  48316. imgBack.style.transformOrigin = "50% 50%";
  48317. imgBack.style.webkitTransformOrigin = "50% 50%";
  48318. this._loadingDiv.appendChild(imgBack);
  48319. this._resizeLoadingUI();
  48320. window.addEventListener("resize", this._resizeLoadingUI);
  48321. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48322. document.body.appendChild(this._loadingDiv);
  48323. this._loadingDiv.style.opacity = "1";
  48324. };
  48325. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  48326. var _this = this;
  48327. if (!this._loadingDiv) {
  48328. return;
  48329. }
  48330. var onTransitionEnd = function () {
  48331. if (!_this._loadingDiv) {
  48332. return;
  48333. }
  48334. document.body.removeChild(_this._loadingDiv);
  48335. window.removeEventListener("resize", _this._resizeLoadingUI);
  48336. _this._loadingDiv = null;
  48337. };
  48338. this._loadingDiv.style.opacity = "0";
  48339. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  48340. };
  48341. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  48342. set: function (text) {
  48343. this._loadingText = text;
  48344. if (this._loadingTextDiv) {
  48345. this._loadingTextDiv.innerHTML = this._loadingText;
  48346. }
  48347. },
  48348. enumerable: true,
  48349. configurable: true
  48350. });
  48351. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  48352. get: function () {
  48353. return this._loadingDivBackgroundColor;
  48354. },
  48355. set: function (color) {
  48356. this._loadingDivBackgroundColor = color;
  48357. if (!this._loadingDiv) {
  48358. return;
  48359. }
  48360. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48361. },
  48362. enumerable: true,
  48363. configurable: true
  48364. });
  48365. return DefaultLoadingScreen;
  48366. }());
  48367. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  48368. })(BABYLON || (BABYLON = {}));
  48369. //# sourceMappingURL=babylon.loadingScreen.js.map
  48370. var BABYLON;
  48371. (function (BABYLON) {
  48372. var SceneLoader = (function () {
  48373. function SceneLoader() {
  48374. }
  48375. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  48376. get: function () {
  48377. return 0;
  48378. },
  48379. enumerable: true,
  48380. configurable: true
  48381. });
  48382. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  48383. get: function () {
  48384. return 1;
  48385. },
  48386. enumerable: true,
  48387. configurable: true
  48388. });
  48389. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  48390. get: function () {
  48391. return 2;
  48392. },
  48393. enumerable: true,
  48394. configurable: true
  48395. });
  48396. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  48397. get: function () {
  48398. return 3;
  48399. },
  48400. enumerable: true,
  48401. configurable: true
  48402. });
  48403. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  48404. get: function () {
  48405. return SceneLoader._ForceFullSceneLoadingForIncremental;
  48406. },
  48407. set: function (value) {
  48408. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  48409. },
  48410. enumerable: true,
  48411. configurable: true
  48412. });
  48413. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  48414. get: function () {
  48415. return SceneLoader._ShowLoadingScreen;
  48416. },
  48417. set: function (value) {
  48418. SceneLoader._ShowLoadingScreen = value;
  48419. },
  48420. enumerable: true,
  48421. configurable: true
  48422. });
  48423. Object.defineProperty(SceneLoader, "loggingLevel", {
  48424. get: function () {
  48425. return SceneLoader._loggingLevel;
  48426. },
  48427. set: function (value) {
  48428. SceneLoader._loggingLevel = value;
  48429. },
  48430. enumerable: true,
  48431. configurable: true
  48432. });
  48433. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  48434. get: function () {
  48435. return SceneLoader._CleanBoneMatrixWeights;
  48436. },
  48437. set: function (value) {
  48438. SceneLoader._CleanBoneMatrixWeights = value;
  48439. },
  48440. enumerable: true,
  48441. configurable: true
  48442. });
  48443. SceneLoader._getDefaultPlugin = function () {
  48444. return SceneLoader._registeredPlugins[".babylon"];
  48445. };
  48446. SceneLoader._getPluginForExtension = function (extension) {
  48447. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  48448. if (registeredPlugin) {
  48449. return registeredPlugin;
  48450. }
  48451. return SceneLoader._getDefaultPlugin();
  48452. };
  48453. SceneLoader._getPluginForDirectLoad = function (data) {
  48454. for (var extension in SceneLoader._registeredPlugins) {
  48455. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  48456. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  48457. return SceneLoader._registeredPlugins[extension];
  48458. }
  48459. }
  48460. return SceneLoader._getDefaultPlugin();
  48461. };
  48462. SceneLoader._getPluginForFilename = function (sceneFilename) {
  48463. if (sceneFilename.name) {
  48464. sceneFilename = sceneFilename.name;
  48465. }
  48466. var dotPosition = sceneFilename.lastIndexOf(".");
  48467. var queryStringPosition = sceneFilename.indexOf("?");
  48468. if (queryStringPosition === -1) {
  48469. queryStringPosition = sceneFilename.length;
  48470. }
  48471. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  48472. return SceneLoader._getPluginForExtension(extension);
  48473. };
  48474. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  48475. SceneLoader._getDirectLoad = function (sceneFilename) {
  48476. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  48477. return sceneFilename.substr(5);
  48478. }
  48479. return null;
  48480. };
  48481. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48482. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  48483. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  48484. var plugin = registeredPlugin.plugin;
  48485. var useArrayBuffer = registeredPlugin.isBinary;
  48486. var database;
  48487. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  48488. var dataCallback = function (data) {
  48489. if (scene.isDisposed) {
  48490. onError("Scene has been disposed");
  48491. return;
  48492. }
  48493. scene.database = database;
  48494. try {
  48495. onSuccess(plugin, data);
  48496. }
  48497. catch (e) {
  48498. onError(null, e);
  48499. }
  48500. };
  48501. var manifestChecked = function (success) {
  48502. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  48503. onError(request.status + " " + request.statusText);
  48504. });
  48505. };
  48506. if (directLoad) {
  48507. dataCallback(directLoad);
  48508. return;
  48509. }
  48510. if (rootUrl.indexOf("file:") === -1) {
  48511. if (scene.getEngine().enableOfflineSupport) {
  48512. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  48513. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  48514. }
  48515. else {
  48516. manifestChecked(true);
  48517. }
  48518. }
  48519. else {
  48520. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  48521. }
  48522. };
  48523. // Public functions
  48524. SceneLoader.GetPluginForExtension = function (extension) {
  48525. return SceneLoader._getPluginForExtension(extension).plugin;
  48526. };
  48527. SceneLoader.RegisterPlugin = function (plugin) {
  48528. if (typeof plugin.extensions === "string") {
  48529. var extension = plugin.extensions;
  48530. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48531. plugin: plugin,
  48532. isBinary: false
  48533. };
  48534. }
  48535. else {
  48536. var extensions = plugin.extensions;
  48537. Object.keys(extensions).forEach(function (extension) {
  48538. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48539. plugin: plugin,
  48540. isBinary: extensions[extension].isBinary
  48541. };
  48542. });
  48543. }
  48544. };
  48545. /**
  48546. * Import meshes into a scene
  48547. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  48548. * @param rootUrl a string that defines the root url for scene and resources
  48549. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48550. * @param scene the instance of BABYLON.Scene to append to
  48551. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  48552. * @param onProgress a callback with a progress event for each file being loaded
  48553. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48554. */
  48555. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48556. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48557. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48558. return;
  48559. }
  48560. var loadingToken = {};
  48561. scene._addPendingData(loadingToken);
  48562. var errorHandler = function (message, exception) {
  48563. if (onError) {
  48564. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  48565. }
  48566. scene._removePendingData(loadingToken);
  48567. };
  48568. var progressHandler = function (event) {
  48569. if (onProgress) {
  48570. onProgress(event);
  48571. }
  48572. };
  48573. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48574. if (plugin.importMesh) {
  48575. var syncedPlugin = plugin;
  48576. var meshes = [];
  48577. var particleSystems = [];
  48578. var skeletons = [];
  48579. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  48580. return;
  48581. }
  48582. if (onSuccess) {
  48583. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48584. onSuccess(meshes, particleSystems, skeletons);
  48585. scene._removePendingData(loadingToken);
  48586. }
  48587. }
  48588. else {
  48589. var asyncedPlugin = plugin;
  48590. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  48591. if (onSuccess) {
  48592. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48593. onSuccess(meshes, particleSystems, skeletons);
  48594. scene._removePendingData(loadingToken);
  48595. }
  48596. }, progressHandler, errorHandler);
  48597. }
  48598. }, progressHandler, errorHandler);
  48599. };
  48600. /**
  48601. * Load a scene
  48602. * @param rootUrl a string that defines the root url for scene and resources
  48603. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48604. * @param engine is the instance of BABYLON.Engine to use to create the scene
  48605. * @param onSuccess a callback with the scene when import succeeds
  48606. * @param onProgress a callback with a progress event for each file being loaded
  48607. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48608. */
  48609. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  48610. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  48611. };
  48612. /**
  48613. * Append a scene
  48614. * @param rootUrl a string that defines the root url for scene and resources
  48615. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48616. * @param scene is the instance of BABYLON.Scene to append to
  48617. * @param onSuccess a callback with the scene when import succeeds
  48618. * @param onProgress a callback with a progress event for each file being loaded
  48619. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48620. */
  48621. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48622. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48623. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48624. return;
  48625. }
  48626. if (SceneLoader.ShowLoadingScreen) {
  48627. scene.getEngine().displayLoadingUI();
  48628. }
  48629. var loadingToken = {};
  48630. scene._addPendingData(loadingToken);
  48631. var errorHandler = function (message, exception) {
  48632. if (onError) {
  48633. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  48634. }
  48635. scene._removePendingData(loadingToken);
  48636. scene.getEngine().hideLoadingUI();
  48637. };
  48638. var progressHandler = function (event) {
  48639. if (onProgress) {
  48640. onProgress(event);
  48641. }
  48642. };
  48643. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48644. if (plugin.load) {
  48645. var syncedPlugin = plugin;
  48646. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  48647. return;
  48648. }
  48649. if (onSuccess) {
  48650. onSuccess(scene);
  48651. }
  48652. scene.loadingPluginName = plugin.name;
  48653. scene._removePendingData(loadingToken);
  48654. }
  48655. else {
  48656. var asyncedPlugin = plugin;
  48657. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  48658. if (onSuccess) {
  48659. onSuccess(scene);
  48660. }
  48661. scene.loadingPluginName = plugin.name;
  48662. scene._removePendingData(loadingToken);
  48663. }, progressHandler, errorHandler);
  48664. }
  48665. if (SceneLoader.ShowLoadingScreen) {
  48666. scene.executeWhenReady(function () {
  48667. scene.getEngine().hideLoadingUI();
  48668. });
  48669. }
  48670. }, progressHandler, errorHandler);
  48671. };
  48672. // Flags
  48673. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  48674. SceneLoader._ShowLoadingScreen = true;
  48675. SceneLoader._CleanBoneMatrixWeights = false;
  48676. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  48677. // Members
  48678. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  48679. SceneLoader._registeredPlugins = {};
  48680. return SceneLoader;
  48681. }());
  48682. BABYLON.SceneLoader = SceneLoader;
  48683. ;
  48684. })(BABYLON || (BABYLON = {}));
  48685. //# sourceMappingURL=babylon.sceneLoader.js.map
  48686. var BABYLON;
  48687. (function (BABYLON) {
  48688. var Internals;
  48689. (function (Internals) {
  48690. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  48691. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  48692. var parsedMaterial = parsedData.materials[index];
  48693. if (parsedMaterial.id === id) {
  48694. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  48695. }
  48696. }
  48697. return null;
  48698. };
  48699. var isDescendantOf = function (mesh, names, hierarchyIds) {
  48700. for (var i in names) {
  48701. if (mesh.name === names[i]) {
  48702. hierarchyIds.push(mesh.id);
  48703. return true;
  48704. }
  48705. }
  48706. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  48707. hierarchyIds.push(mesh.id);
  48708. return true;
  48709. }
  48710. return false;
  48711. };
  48712. var logOperation = function (operation, producer) {
  48713. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  48714. };
  48715. BABYLON.SceneLoader.RegisterPlugin({
  48716. name: "babylon.js",
  48717. extensions: ".babylon",
  48718. canDirectLoad: function (data) {
  48719. if (data.indexOf("babylon") !== -1) {
  48720. return true;
  48721. }
  48722. return false;
  48723. },
  48724. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  48725. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48726. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48727. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48728. // and avoid problems with multiple concurrent .babylon loads.
  48729. var log = "importMesh has failed JSON parse";
  48730. try {
  48731. var parsedData = JSON.parse(data);
  48732. log = "";
  48733. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48734. if (!meshesNames) {
  48735. meshesNames = null;
  48736. }
  48737. else if (!Array.isArray(meshesNames)) {
  48738. meshesNames = [meshesNames];
  48739. }
  48740. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  48741. var loadedSkeletonsIds = [];
  48742. var loadedMaterialsIds = [];
  48743. var hierarchyIds = [];
  48744. var index;
  48745. var cache;
  48746. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  48747. var parsedMesh = parsedData.meshes[index];
  48748. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  48749. if (meshesNames !== null) {
  48750. // Remove found mesh name from list.
  48751. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  48752. }
  48753. //Geometry?
  48754. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  48755. //does the file contain geometries?
  48756. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  48757. //find the correct geometry and add it to the scene
  48758. var found = false;
  48759. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  48760. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  48761. return;
  48762. }
  48763. else {
  48764. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  48765. if (parsedGeometryData.id === parsedMesh.geometryId) {
  48766. switch (geometryType) {
  48767. case "boxes":
  48768. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  48769. break;
  48770. case "spheres":
  48771. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  48772. break;
  48773. case "cylinders":
  48774. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  48775. break;
  48776. case "toruses":
  48777. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  48778. break;
  48779. case "grounds":
  48780. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  48781. break;
  48782. case "planes":
  48783. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  48784. break;
  48785. case "torusKnots":
  48786. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  48787. break;
  48788. case "vertexData":
  48789. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  48790. break;
  48791. }
  48792. found = true;
  48793. }
  48794. });
  48795. }
  48796. });
  48797. if (found === false) {
  48798. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  48799. }
  48800. }
  48801. }
  48802. // Material ?
  48803. if (parsedMesh.materialId) {
  48804. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  48805. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  48806. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  48807. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  48808. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  48809. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  48810. var subMatId = parsedMultiMaterial.materials[matIndex];
  48811. loadedMaterialsIds.push(subMatId);
  48812. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  48813. log += "\n\tMaterial " + mat.toString(fullDetails);
  48814. }
  48815. loadedMaterialsIds.push(parsedMultiMaterial.id);
  48816. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  48817. materialFound = true;
  48818. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  48819. break;
  48820. }
  48821. }
  48822. }
  48823. if (materialFound === false) {
  48824. loadedMaterialsIds.push(parsedMesh.materialId);
  48825. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  48826. if (!mat) {
  48827. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  48828. }
  48829. else {
  48830. log += "\n\tMaterial " + mat.toString(fullDetails);
  48831. }
  48832. }
  48833. }
  48834. // Skeleton ?
  48835. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  48836. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  48837. if (skeletonAlreadyLoaded === false) {
  48838. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  48839. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  48840. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  48841. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  48842. skeletons.push(skeleton);
  48843. loadedSkeletonsIds.push(parsedSkeleton.id);
  48844. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  48845. }
  48846. }
  48847. }
  48848. }
  48849. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  48850. meshes.push(mesh);
  48851. log += "\n\tMesh " + mesh.toString(fullDetails);
  48852. }
  48853. }
  48854. // Connecting parents
  48855. var currentMesh;
  48856. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48857. currentMesh = scene.meshes[index];
  48858. if (currentMesh._waitingParentId) {
  48859. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  48860. currentMesh._waitingParentId = undefined;
  48861. }
  48862. }
  48863. // freeze and compute world matrix application
  48864. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48865. currentMesh = scene.meshes[index];
  48866. if (currentMesh._waitingFreezeWorldMatrix) {
  48867. currentMesh.freezeWorldMatrix();
  48868. currentMesh._waitingFreezeWorldMatrix = undefined;
  48869. }
  48870. else {
  48871. currentMesh.computeWorldMatrix(true);
  48872. }
  48873. }
  48874. }
  48875. // Particles
  48876. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  48877. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48878. var parsedParticleSystem = parsedData.particleSystems[index];
  48879. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  48880. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  48881. }
  48882. }
  48883. }
  48884. return true;
  48885. }
  48886. catch (err) {
  48887. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  48888. log = null;
  48889. throw err;
  48890. }
  48891. finally {
  48892. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48893. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48894. }
  48895. }
  48896. },
  48897. load: function (scene, data, rootUrl) {
  48898. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48899. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48900. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48901. // and avoid problems with multiple concurrent .babylon loads.
  48902. var log = "importScene has failed JSON parse";
  48903. try {
  48904. var parsedData = JSON.parse(data);
  48905. log = "";
  48906. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48907. // Scene
  48908. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  48909. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  48910. }
  48911. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  48912. scene.autoClear = parsedData.autoClear;
  48913. }
  48914. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  48915. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  48916. }
  48917. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  48918. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  48919. }
  48920. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  48921. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  48922. }
  48923. // Fog
  48924. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  48925. scene.fogMode = parsedData.fogMode;
  48926. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  48927. scene.fogStart = parsedData.fogStart;
  48928. scene.fogEnd = parsedData.fogEnd;
  48929. scene.fogDensity = parsedData.fogDensity;
  48930. log += "\tFog mode for scene: ";
  48931. switch (scene.fogMode) {
  48932. // getters not compiling, so using hardcoded
  48933. case 1:
  48934. log += "exp\n";
  48935. break;
  48936. case 2:
  48937. log += "exp2\n";
  48938. break;
  48939. case 3:
  48940. log += "linear\n";
  48941. break;
  48942. }
  48943. }
  48944. //Physics
  48945. if (parsedData.physicsEnabled) {
  48946. var physicsPlugin;
  48947. if (parsedData.physicsEngine === "cannon") {
  48948. physicsPlugin = new BABYLON.CannonJSPlugin();
  48949. }
  48950. else if (parsedData.physicsEngine === "oimo") {
  48951. physicsPlugin = new BABYLON.OimoJSPlugin();
  48952. }
  48953. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  48954. //else - default engine, which is currently oimo
  48955. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  48956. scene.enablePhysics(physicsGravity, physicsPlugin);
  48957. }
  48958. // Metadata
  48959. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  48960. scene.metadata = parsedData.metadata;
  48961. }
  48962. //collisions, if defined. otherwise, default is true
  48963. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  48964. scene.collisionsEnabled = parsedData.collisionsEnabled;
  48965. }
  48966. scene.workerCollisions = !!parsedData.workerCollisions;
  48967. var index;
  48968. var cache;
  48969. // Lights
  48970. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  48971. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  48972. var parsedLight = parsedData.lights[index];
  48973. var light = BABYLON.Light.Parse(parsedLight, scene);
  48974. log += (index === 0 ? "\n\tLights:" : "");
  48975. log += "\n\t\t" + light.toString(fullDetails);
  48976. }
  48977. }
  48978. // Animations
  48979. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  48980. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  48981. var parsedAnimation = parsedData.animations[index];
  48982. var animation = BABYLON.Animation.Parse(parsedAnimation);
  48983. scene.animations.push(animation);
  48984. log += (index === 0 ? "\n\tAnimations:" : "");
  48985. log += "\n\t\t" + animation.toString(fullDetails);
  48986. }
  48987. }
  48988. if (parsedData.autoAnimate) {
  48989. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  48990. }
  48991. // Materials
  48992. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  48993. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  48994. var parsedMaterial = parsedData.materials[index];
  48995. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  48996. log += (index === 0 ? "\n\tMaterials:" : "");
  48997. log += "\n\t\t" + mat.toString(fullDetails);
  48998. }
  48999. }
  49000. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49001. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  49002. var parsedMultiMaterial = parsedData.multiMaterials[index];
  49003. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49004. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  49005. log += "\n\t\t" + mmat.toString(fullDetails);
  49006. }
  49007. }
  49008. // Morph targets
  49009. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  49010. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  49011. var managerData = _a[_i];
  49012. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  49013. }
  49014. }
  49015. // Skeletons
  49016. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49017. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  49018. var parsedSkeleton = parsedData.skeletons[index];
  49019. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49020. log += (index === 0 ? "\n\tSkeletons:" : "");
  49021. log += "\n\t\t" + skeleton.toString(fullDetails);
  49022. }
  49023. }
  49024. // Geometries
  49025. var geometries = parsedData.geometries;
  49026. if (geometries !== undefined && geometries !== null) {
  49027. // Boxes
  49028. var boxes = geometries.boxes;
  49029. if (boxes !== undefined && boxes !== null) {
  49030. for (index = 0, cache = boxes.length; index < cache; index++) {
  49031. var parsedBox = boxes[index];
  49032. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  49033. }
  49034. }
  49035. // Spheres
  49036. var spheres = geometries.spheres;
  49037. if (spheres !== undefined && spheres !== null) {
  49038. for (index = 0, cache = spheres.length; index < cache; index++) {
  49039. var parsedSphere = spheres[index];
  49040. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  49041. }
  49042. }
  49043. // Cylinders
  49044. var cylinders = geometries.cylinders;
  49045. if (cylinders !== undefined && cylinders !== null) {
  49046. for (index = 0, cache = cylinders.length; index < cache; index++) {
  49047. var parsedCylinder = cylinders[index];
  49048. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  49049. }
  49050. }
  49051. // Toruses
  49052. var toruses = geometries.toruses;
  49053. if (toruses !== undefined && toruses !== null) {
  49054. for (index = 0, cache = toruses.length; index < cache; index++) {
  49055. var parsedTorus = toruses[index];
  49056. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  49057. }
  49058. }
  49059. // Grounds
  49060. var grounds = geometries.grounds;
  49061. if (grounds !== undefined && grounds !== null) {
  49062. for (index = 0, cache = grounds.length; index < cache; index++) {
  49063. var parsedGround = grounds[index];
  49064. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  49065. }
  49066. }
  49067. // Planes
  49068. var planes = geometries.planes;
  49069. if (planes !== undefined && planes !== null) {
  49070. for (index = 0, cache = planes.length; index < cache; index++) {
  49071. var parsedPlane = planes[index];
  49072. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  49073. }
  49074. }
  49075. // TorusKnots
  49076. var torusKnots = geometries.torusKnots;
  49077. if (torusKnots !== undefined && torusKnots !== null) {
  49078. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  49079. var parsedTorusKnot = torusKnots[index];
  49080. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  49081. }
  49082. }
  49083. // VertexData
  49084. var vertexData = geometries.vertexData;
  49085. if (vertexData !== undefined && vertexData !== null) {
  49086. for (index = 0, cache = vertexData.length; index < cache; index++) {
  49087. var parsedVertexData = vertexData[index];
  49088. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  49089. }
  49090. }
  49091. }
  49092. // Meshes
  49093. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49094. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49095. var parsedMesh = parsedData.meshes[index];
  49096. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49097. log += (index === 0 ? "\n\tMeshes:" : "");
  49098. log += "\n\t\t" + mesh.toString(fullDetails);
  49099. }
  49100. }
  49101. // Cameras
  49102. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  49103. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  49104. var parsedCamera = parsedData.cameras[index];
  49105. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  49106. log += (index === 0 ? "\n\tCameras:" : "");
  49107. log += "\n\t\t" + camera.toString(fullDetails);
  49108. }
  49109. }
  49110. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  49111. scene.setActiveCameraByID(parsedData.activeCameraID);
  49112. }
  49113. // Browsing all the graph to connect the dots
  49114. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  49115. var camera = scene.cameras[index];
  49116. if (camera._waitingParentId) {
  49117. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  49118. camera._waitingParentId = undefined;
  49119. }
  49120. }
  49121. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49122. var light = scene.lights[index];
  49123. if (light._waitingParentId) {
  49124. light.parent = scene.getLastEntryByID(light._waitingParentId);
  49125. light._waitingParentId = undefined;
  49126. }
  49127. }
  49128. // Sounds
  49129. var loadedSounds = [];
  49130. var loadedSound;
  49131. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  49132. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  49133. var parsedSound = parsedData.sounds[index];
  49134. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49135. if (!parsedSound.url)
  49136. parsedSound.url = parsedSound.name;
  49137. if (!loadedSounds[parsedSound.url]) {
  49138. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  49139. loadedSounds[parsedSound.url] = loadedSound;
  49140. }
  49141. else {
  49142. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  49143. }
  49144. }
  49145. else {
  49146. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  49147. }
  49148. }
  49149. }
  49150. loadedSounds = [];
  49151. // Connect parents & children and parse actions
  49152. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49153. var mesh = scene.meshes[index];
  49154. if (mesh._waitingParentId) {
  49155. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  49156. mesh._waitingParentId = undefined;
  49157. }
  49158. if (mesh._waitingActions) {
  49159. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  49160. mesh._waitingActions = undefined;
  49161. }
  49162. }
  49163. // freeze world matrix application
  49164. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49165. var currentMesh = scene.meshes[index];
  49166. if (currentMesh._waitingFreezeWorldMatrix) {
  49167. currentMesh.freezeWorldMatrix();
  49168. currentMesh._waitingFreezeWorldMatrix = undefined;
  49169. }
  49170. else {
  49171. currentMesh.computeWorldMatrix(true);
  49172. }
  49173. }
  49174. // Particles Systems
  49175. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49176. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49177. var parsedParticleSystem = parsedData.particleSystems[index];
  49178. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  49179. }
  49180. }
  49181. // Lens flares
  49182. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  49183. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  49184. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  49185. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  49186. }
  49187. }
  49188. // Shadows
  49189. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  49190. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  49191. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  49192. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  49193. }
  49194. }
  49195. // Lights exclusions / inclusions
  49196. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49197. var light = scene.lights[index];
  49198. // Excluded check
  49199. if (light._excludedMeshesIds.length > 0) {
  49200. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  49201. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  49202. if (excludedMesh) {
  49203. light.excludedMeshes.push(excludedMesh);
  49204. }
  49205. }
  49206. light._excludedMeshesIds = [];
  49207. }
  49208. // Included check
  49209. if (light._includedOnlyMeshesIds.length > 0) {
  49210. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  49211. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  49212. if (includedOnlyMesh) {
  49213. light.includedOnlyMeshes.push(includedOnlyMesh);
  49214. }
  49215. }
  49216. light._includedOnlyMeshesIds = [];
  49217. }
  49218. }
  49219. // Actions (scene)
  49220. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  49221. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  49222. }
  49223. // Finish
  49224. return true;
  49225. }
  49226. catch (err) {
  49227. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  49228. log = null;
  49229. throw err;
  49230. }
  49231. finally {
  49232. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49233. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49234. }
  49235. }
  49236. }
  49237. });
  49238. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49239. })(BABYLON || (BABYLON = {}));
  49240. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  49241. var BABYLON;
  49242. (function (BABYLON) {
  49243. var FilesInput = (function () {
  49244. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  49245. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  49246. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  49247. this._engine = p_engine;
  49248. this._canvas = p_canvas;
  49249. this._currentScene = p_scene;
  49250. this._sceneLoadedCallback = p_sceneLoadedCallback;
  49251. this._progressCallback = p_progressCallback;
  49252. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  49253. this._textureLoadingCallback = p_textureLoadingCallback;
  49254. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  49255. }
  49256. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  49257. var _this = this;
  49258. if (p_elementToMonitor) {
  49259. this._elementToMonitor = p_elementToMonitor;
  49260. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  49261. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  49262. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  49263. }
  49264. };
  49265. FilesInput.prototype.renderFunction = function () {
  49266. if (this._additionnalRenderLoopLogicCallback) {
  49267. this._additionnalRenderLoopLogicCallback();
  49268. }
  49269. if (this._currentScene) {
  49270. if (this._textureLoadingCallback) {
  49271. var remaining = this._currentScene.getWaitingItemsCount();
  49272. if (remaining > 0) {
  49273. this._textureLoadingCallback(remaining);
  49274. }
  49275. }
  49276. this._currentScene.render();
  49277. }
  49278. };
  49279. FilesInput.prototype.drag = function (e) {
  49280. e.stopPropagation();
  49281. e.preventDefault();
  49282. };
  49283. FilesInput.prototype.drop = function (eventDrop) {
  49284. eventDrop.stopPropagation();
  49285. eventDrop.preventDefault();
  49286. this.loadFiles(eventDrop);
  49287. };
  49288. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  49289. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  49290. reader.readEntries(function (fileEntries) {
  49291. var remaining = fileEntries.length;
  49292. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  49293. var fileEntry = fileEntries_1[_i];
  49294. if (fileEntry.isFile) {
  49295. fileEntry.file(function (file) {
  49296. file.correctName = relativePath + file.name;
  49297. files.push(file);
  49298. remaining--;
  49299. if (remaining === 0) {
  49300. callback();
  49301. }
  49302. });
  49303. }
  49304. else {
  49305. remaining--;
  49306. if (remaining === 0) {
  49307. callback();
  49308. }
  49309. }
  49310. }
  49311. });
  49312. };
  49313. FilesInput.prototype._processFiles = function (files) {
  49314. for (var i = 0; i < files.length; i++) {
  49315. var name = files[i].correctName.toLowerCase();
  49316. var extension = name.split('.').pop();
  49317. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  49318. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  49319. this._sceneFileToLoad = files[i];
  49320. }
  49321. else {
  49322. FilesInput.FilesToLoad[name] = files[i];
  49323. }
  49324. }
  49325. this.reload();
  49326. };
  49327. FilesInput.prototype.loadFiles = function (event) {
  49328. var _this = this;
  49329. if (this._startingProcessingFilesCallback)
  49330. this._startingProcessingFilesCallback();
  49331. // Handling data transfer via drag'n'drop
  49332. if (event && event.dataTransfer && event.dataTransfer.files) {
  49333. this._filesToLoad = event.dataTransfer.files;
  49334. }
  49335. // Handling files from input files
  49336. if (event && event.target && event.target.files) {
  49337. this._filesToLoad = event.target.files;
  49338. }
  49339. if (this._filesToLoad && this._filesToLoad.length > 0) {
  49340. var files_1 = [];
  49341. var folders = [];
  49342. for (var i = 0; i < this._filesToLoad.length; i++) {
  49343. var fileToLoad = this._filesToLoad[i];
  49344. var name_1 = fileToLoad.name.toLowerCase();
  49345. var type = fileToLoad.type;
  49346. var entry = void 0;
  49347. fileToLoad.correctName = name_1;
  49348. if (event.dataTransfer && event.dataTransfer.items) {
  49349. var item = event.dataTransfer.items[i];
  49350. if (item.getAsEntry) {
  49351. entry = item.getAsEntry();
  49352. }
  49353. else if (item.webkitGetAsEntry) {
  49354. entry = item.webkitGetAsEntry();
  49355. }
  49356. }
  49357. if (!entry) {
  49358. files_1.push(fileToLoad);
  49359. }
  49360. else {
  49361. if (entry.isDirectory) {
  49362. folders.push(entry);
  49363. }
  49364. else {
  49365. files_1.push(fileToLoad);
  49366. }
  49367. }
  49368. }
  49369. if (folders.length === 0) {
  49370. this._processFiles(files_1);
  49371. }
  49372. else {
  49373. var remaining = folders.length;
  49374. // Extract folder content
  49375. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  49376. var folder = folders_1[_i];
  49377. this._handleFolderDrop(folder, files_1, function () {
  49378. remaining--;
  49379. if (remaining === 0) {
  49380. _this._processFiles(files_1);
  49381. }
  49382. });
  49383. }
  49384. }
  49385. }
  49386. };
  49387. FilesInput.prototype.reload = function () {
  49388. var _this = this;
  49389. var that = this;
  49390. // If a ".babylon" file has been provided
  49391. if (this._sceneFileToLoad) {
  49392. if (this._currentScene) {
  49393. if (BABYLON.Tools.errorsCount > 0) {
  49394. BABYLON.Tools.ClearLogCache();
  49395. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  49396. }
  49397. this._engine.stopRenderLoop();
  49398. this._currentScene.dispose();
  49399. }
  49400. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  49401. that._currentScene = newScene;
  49402. // Wait for textures and shaders to be ready
  49403. that._currentScene.executeWhenReady(function () {
  49404. if (that._sceneLoadedCallback) {
  49405. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  49406. }
  49407. that._engine.runRenderLoop(function () { that.renderFunction(); });
  49408. });
  49409. }, function (progress) {
  49410. if (_this._progressCallback) {
  49411. _this._progressCallback(progress);
  49412. }
  49413. });
  49414. }
  49415. else {
  49416. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  49417. }
  49418. };
  49419. FilesInput.FilesToLoad = new Array();
  49420. return FilesInput;
  49421. }());
  49422. BABYLON.FilesInput = FilesInput;
  49423. })(BABYLON || (BABYLON = {}));
  49424. //# sourceMappingURL=babylon.filesInput.js.map
  49425. var BABYLON;
  49426. (function (BABYLON) {
  49427. var FramingBehavior = (function () {
  49428. function FramingBehavior() {
  49429. this._mode = FramingBehavior.IgnoreBoundsSizeMode;
  49430. this._radiusOffset = 0;
  49431. this._elevation = 0.3;
  49432. this._positionY = 0;
  49433. this._defaultElevation = 0.3;
  49434. this._elevationReturnTime = 1500;
  49435. this._elevationReturnWaitTime = 1000;
  49436. this._zoomStopsAnimation = false;
  49437. this._framingTime = 1500;
  49438. this._isPointerDown = false;
  49439. this._lastFrameTime = null;
  49440. this._lastInteractionTime = -Infinity;
  49441. // Framing control
  49442. this._animatables = new Array();
  49443. this._betaIsAnimating = false;
  49444. this._lastFrameRadius = 0;
  49445. }
  49446. Object.defineProperty(FramingBehavior.prototype, "name", {
  49447. get: function () {
  49448. return "Framing";
  49449. },
  49450. enumerable: true,
  49451. configurable: true
  49452. });
  49453. Object.defineProperty(FramingBehavior.prototype, "mode", {
  49454. /**
  49455. * Gets current mode used by the behavior.
  49456. */
  49457. get: function () {
  49458. return this._mode;
  49459. },
  49460. /**
  49461. * Sets the current mode used by the behavior
  49462. */
  49463. set: function (mode) {
  49464. this._mode = mode;
  49465. },
  49466. enumerable: true,
  49467. configurable: true
  49468. });
  49469. Object.defineProperty(FramingBehavior.prototype, "radiusOffset", {
  49470. /**
  49471. * Gets the radius of the camera relative to the target's bounding box.
  49472. */
  49473. get: function () {
  49474. return this._radiusOffset;
  49475. },
  49476. /**
  49477. * Sets the radius of the camera relative to the target's bounding box.
  49478. */
  49479. set: function (radius) {
  49480. this._radiusOffset = radius;
  49481. },
  49482. enumerable: true,
  49483. configurable: true
  49484. });
  49485. Object.defineProperty(FramingBehavior.prototype, "elevation", {
  49486. /**
  49487. * Gets the elevation of the camera from the target, in radians.
  49488. */
  49489. get: function () {
  49490. return this._elevation;
  49491. },
  49492. /**
  49493. * Sets the elevation of the camera from the target, in radians.
  49494. */
  49495. set: function (elevation) {
  49496. this._elevation = elevation;
  49497. },
  49498. enumerable: true,
  49499. configurable: true
  49500. });
  49501. Object.defineProperty(FramingBehavior.prototype, "positionY", {
  49502. /**
  49503. * Gets the Y offset of the primary model from the camera's focus.
  49504. */
  49505. get: function () {
  49506. return this._positionY;
  49507. },
  49508. /**
  49509. * Sets the Y offset of the primary model from the camera's focus.
  49510. */
  49511. set: function (positionY) {
  49512. this._positionY = positionY;
  49513. },
  49514. enumerable: true,
  49515. configurable: true
  49516. });
  49517. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  49518. /**
  49519. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  49520. * behaviour is triggered, in radians.
  49521. */
  49522. get: function () {
  49523. return this._defaultElevation;
  49524. },
  49525. /**
  49526. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  49527. * behaviour is triggered, in radians.
  49528. */
  49529. set: function (elevation) {
  49530. this._defaultElevation = elevation;
  49531. },
  49532. enumerable: true,
  49533. configurable: true
  49534. });
  49535. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  49536. /**
  49537. * Gets the time (in milliseconds) taken to return to the default beta position.
  49538. * Negative value indicates camera should not return to default.
  49539. */
  49540. get: function () {
  49541. return this._elevationReturnTime;
  49542. },
  49543. /**
  49544. * Sets the time (in milliseconds) taken to return to the default beta position.
  49545. * Negative value indicates camera should not return to default.
  49546. */
  49547. set: function (speed) {
  49548. this._elevationReturnTime = speed;
  49549. },
  49550. enumerable: true,
  49551. configurable: true
  49552. });
  49553. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  49554. /**
  49555. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  49556. */
  49557. get: function () {
  49558. return this._elevationReturnWaitTime;
  49559. },
  49560. /**
  49561. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  49562. */
  49563. set: function (time) {
  49564. this._elevationReturnWaitTime = time;
  49565. },
  49566. enumerable: true,
  49567. configurable: true
  49568. });
  49569. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  49570. /**
  49571. * Gets the flag that indicates if user zooming should stop model animation.
  49572. */
  49573. get: function () {
  49574. return this._zoomStopsAnimation;
  49575. },
  49576. /**
  49577. * Sets the flag that indicates if user zooming should stop model animation.
  49578. */
  49579. set: function (flag) {
  49580. this._zoomStopsAnimation = flag;
  49581. },
  49582. enumerable: true,
  49583. configurable: true
  49584. });
  49585. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  49586. /**
  49587. * Gets the transition time when framing the model, in milliseconds
  49588. */
  49589. get: function () {
  49590. return this._framingTime;
  49591. },
  49592. /**
  49593. * Sets the transition time when framing the model, in milliseconds
  49594. */
  49595. set: function (time) {
  49596. this._framingTime = time;
  49597. },
  49598. enumerable: true,
  49599. configurable: true
  49600. });
  49601. FramingBehavior.prototype.attach = function (camera) {
  49602. var _this = this;
  49603. this._attachedCamera = camera;
  49604. var scene = this._attachedCamera.getScene();
  49605. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  49606. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  49607. _this._isPointerDown = true;
  49608. return;
  49609. }
  49610. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  49611. _this._isPointerDown = false;
  49612. }
  49613. });
  49614. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  49615. if (mesh) {
  49616. _this.zoomOnMesh(mesh);
  49617. }
  49618. });
  49619. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  49620. // Stop the animation if there is user interaction and the animation should stop for this interaction
  49621. _this._applyUserInteraction();
  49622. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  49623. // back to the default position after a given timeout
  49624. _this._maintainCameraAboveGround();
  49625. });
  49626. };
  49627. FramingBehavior.prototype.detach = function (camera) {
  49628. var scene = this._attachedCamera.getScene();
  49629. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  49630. camera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  49631. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  49632. };
  49633. /**
  49634. * Targets the given mesh and updates zoom level accordingly.
  49635. * @param mesh The mesh to target.
  49636. * @param radius Optional. If a cached radius position already exists, overrides default.
  49637. * @param applyToLowerLimit Optional. Indicates if the calculated target radius should be applied to the
  49638. * camera's lower radius limit too.
  49639. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  49640. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  49641. */
  49642. FramingBehavior.prototype.zoomOnMesh = function (mesh, radius, applyToLowerLimit, framingPositionY, focusOnOriginXZ) {
  49643. if (applyToLowerLimit === void 0) { applyToLowerLimit = false; }
  49644. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = true; }
  49645. if (framingPositionY == null) {
  49646. framingPositionY = this._positionY;
  49647. }
  49648. // sets the radius and lower radius bounds
  49649. if (radius == null) {
  49650. // Small delta ensures camera is not always at lower zoom limit.
  49651. var delta = 0.1;
  49652. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  49653. var position = this._calculateLowerRadiusFromModelBoundingSphere(mesh, this.radiusOffset);
  49654. this._attachedCamera.lowerRadiusLimit = position - delta;
  49655. radius = position;
  49656. }
  49657. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  49658. radius = this._calculateLowerRadiusFromModelBoundingSphere(mesh, this.radiusOffset);
  49659. }
  49660. }
  49661. var zoomTarget;
  49662. var zoomTargetY;
  49663. mesh.computeWorldMatrix(true);
  49664. var modelWorldPosition = new BABYLON.Vector3(0, 0, 0);
  49665. var modelWorldScale = new BABYLON.Vector3(0, 0, 0);
  49666. mesh.getWorldMatrix().decompose(modelWorldScale, new BABYLON.Quaternion(), modelWorldPosition);
  49667. //find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  49668. var bottom = modelWorldPosition.y + mesh.getBoundingInfo().minimum.y;
  49669. var top = modelWorldPosition.y + mesh.getBoundingInfo().maximum.y;
  49670. zoomTargetY = bottom + (top - bottom) * framingPositionY;
  49671. if (applyToLowerLimit) {
  49672. this._attachedCamera.lowerRadiusLimit = radius;
  49673. }
  49674. if (!this._radiusTransition) {
  49675. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  49676. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  49677. }
  49678. // transition to new radius
  49679. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime));
  49680. if (focusOnOriginXZ) {
  49681. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  49682. }
  49683. else {
  49684. zoomTarget = new BABYLON.Vector3(modelWorldPosition.x, zoomTargetY, modelWorldPosition.z);
  49685. }
  49686. // if (!this._vectorTransition) {
  49687. // FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  49688. // this._vectorTransition = Animation.CreateAnimation("target", Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  49689. // }
  49690. // this._animatables.push(Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(),
  49691. // 60, this._vectorTransition, this._framingTime));
  49692. };
  49693. /**
  49694. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  49695. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  49696. * frustum width.
  49697. * @param framingRadius An additional factor to add to the return camera radius.
  49698. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  49699. * to fully enclose the mesh in the viewing frustum.
  49700. */
  49701. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (mesh, framingRadius) {
  49702. var boxVectorGlobalDiagonal = mesh.getBoundingInfo().diagonalLength;
  49703. var frustumSlope = this._getFrustumSlope();
  49704. // Formula for setting distance
  49705. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  49706. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  49707. // Horizon distance
  49708. var radius = radiusWithoutFraming * framingRadius;
  49709. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  49710. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  49711. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  49712. var camera = this._attachedCamera;
  49713. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  49714. // Don't exceed the requested limit
  49715. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  49716. }
  49717. // Don't exceed the upper radius limit
  49718. if (camera.upperRadiusLimit) {
  49719. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  49720. }
  49721. return distance;
  49722. };
  49723. /**
  49724. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  49725. * is automatically returned to its default position (expected to be above ground plane).
  49726. */
  49727. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  49728. var _this = this;
  49729. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  49730. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  49731. var limitBeta = Math.PI * 0.5;
  49732. // Bring the camera back up if below the ground plane
  49733. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  49734. this._betaIsAnimating = true;
  49735. //Transition to new position
  49736. this.stopAllAnimations();
  49737. if (!this._betaTransition) {
  49738. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  49739. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  49740. }
  49741. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  49742. _this._clearAnimationLocks();
  49743. _this.stopAllAnimations();
  49744. }));
  49745. }
  49746. };
  49747. /**
  49748. * Returns the frustum slope based on the canvas ratio and camera FOV
  49749. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  49750. */
  49751. FramingBehavior.prototype._getFrustumSlope = function () {
  49752. // Calculate the viewport ratio
  49753. // Aspect Ratio is Height/Width.
  49754. var camera = this._attachedCamera;
  49755. var engine = camera.getScene().getEngine();
  49756. var aspectRatio = engine.getAspectRatio(camera);
  49757. // Camera FOV is the vertical field of view (top-bottom) in radians.
  49758. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  49759. var frustumSlopeY = Math.tan(camera.fov / 2);
  49760. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  49761. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  49762. // along the forward vector.
  49763. var frustumSlopeX = frustumSlopeY / aspectRatio;
  49764. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  49765. };
  49766. /**
  49767. * Returns true if user is scrolling.
  49768. * @return true if user is scrolling.
  49769. */
  49770. FramingBehavior.prototype._userIsZooming = function () {
  49771. return this._attachedCamera.inertialRadiusOffset !== 0;
  49772. };
  49773. /**
  49774. * Indicates if default model animation (rotation) should stop for the current user interaction.
  49775. *
  49776. * @return True if the model animation (rotation) should stop when given the current user interaction.
  49777. */
  49778. FramingBehavior.prototype._shouldAnimationStopForInteraction = function () {
  49779. var zoomHasHitLimit = false;
  49780. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  49781. zoomHasHitLimit = true;
  49782. }
  49783. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  49784. this._lastFrameRadius = this._attachedCamera.radius;
  49785. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  49786. };
  49787. /**
  49788. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  49789. */
  49790. FramingBehavior.prototype._clearAnimationLocks = function () {
  49791. this._betaIsAnimating = false;
  49792. };
  49793. /**
  49794. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  49795. */
  49796. FramingBehavior.prototype._applyUserInteraction = function () {
  49797. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  49798. this._lastInteractionTime = BABYLON.Tools.Now;
  49799. this.stopAllAnimations();
  49800. this._clearAnimationLocks();
  49801. }
  49802. };
  49803. /**
  49804. * Stops and removes all animations that have been applied to the camera
  49805. */
  49806. FramingBehavior.prototype.stopAllAnimations = function () {
  49807. this._attachedCamera.animations = [];
  49808. while (this._animatables.length) {
  49809. this._animatables[0].onAnimationEnd = null;
  49810. this._animatables[0].stop();
  49811. this._animatables.shift();
  49812. }
  49813. };
  49814. // Tools
  49815. FramingBehavior.prototype._userIsMoving = function () {
  49816. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  49817. this._attachedCamera.inertialBetaOffset !== 0 ||
  49818. this._attachedCamera.inertialRadiusOffset !== 0 ||
  49819. this._attachedCamera.inertialPanningX !== 0 ||
  49820. this._attachedCamera.inertialPanningY !== 0 ||
  49821. this._isPointerDown;
  49822. };
  49823. /**
  49824. * The easing function used by animations
  49825. */
  49826. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  49827. /**
  49828. * The easing mode used by animations
  49829. */
  49830. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  49831. // Statics
  49832. /**
  49833. * The camera can move all the way towards the model.
  49834. */
  49835. FramingBehavior.IgnoreBoundsSizeMode = 0;
  49836. /**
  49837. * The camera is not allowed to zoom closer to the model than the point at which the adjusted bounding sphere touches the frustum sides
  49838. */
  49839. FramingBehavior.FitFrustumSidesMode = 0;
  49840. return FramingBehavior;
  49841. }());
  49842. BABYLON.FramingBehavior = FramingBehavior;
  49843. })(BABYLON || (BABYLON = {}));
  49844. //# sourceMappingURL=babylon.framingBehavior.js.map
  49845. var BABYLON;
  49846. (function (BABYLON) {
  49847. /**
  49848. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  49849. */
  49850. var BouncingBehavior = (function () {
  49851. function BouncingBehavior() {
  49852. /**
  49853. * The duration of the animation, in milliseconds
  49854. */
  49855. this.transitionDuration = 450;
  49856. /**
  49857. * Length of the distance animated by the transition when lower radius is reached
  49858. */
  49859. this.lowerRadiusTransitionRange = 2;
  49860. /**
  49861. * Length of the distance animated by the transition when upper radius is reached
  49862. */
  49863. this.upperRadiusTransitionRange = -2;
  49864. // Animations
  49865. this._radiusIsAnimating = false;
  49866. this._radiusBounceTransition = null;
  49867. this._animatables = new Array();
  49868. }
  49869. Object.defineProperty(BouncingBehavior.prototype, "name", {
  49870. get: function () {
  49871. return "Bouncing";
  49872. },
  49873. enumerable: true,
  49874. configurable: true
  49875. });
  49876. BouncingBehavior.prototype.attach = function (camera) {
  49877. var _this = this;
  49878. this._attachedCamera = camera;
  49879. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  49880. // Add the bounce animation to the lower radius limit
  49881. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  49882. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  49883. }
  49884. // Add the bounce animation to the upper radius limit
  49885. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  49886. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  49887. }
  49888. });
  49889. };
  49890. BouncingBehavior.prototype.detach = function (camera) {
  49891. camera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  49892. };
  49893. /**
  49894. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  49895. * @param radiusLimit The limit to check against.
  49896. * @return Bool to indicate if at limit.
  49897. */
  49898. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  49899. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  49900. return true;
  49901. }
  49902. return false;
  49903. };
  49904. /**
  49905. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  49906. * @param radiusDelta The delta by which to animate to. Can be negative.
  49907. */
  49908. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  49909. var _this = this;
  49910. if (!this._radiusBounceTransition) {
  49911. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  49912. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  49913. }
  49914. // Prevent zoom until bounce has completed
  49915. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  49916. this._attachedCamera.wheelPrecision = Infinity;
  49917. this._attachedCamera.inertialRadiusOffset = 0;
  49918. // Animate to the radius limit
  49919. this.stopAllAnimations();
  49920. this._radiusIsAnimating = true;
  49921. this._animatables.push(BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); }));
  49922. };
  49923. /**
  49924. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  49925. */
  49926. BouncingBehavior.prototype._clearAnimationLocks = function () {
  49927. this._radiusIsAnimating = false;
  49928. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  49929. };
  49930. /**
  49931. * Stops and removes all animations that have been applied to the camera
  49932. */
  49933. BouncingBehavior.prototype.stopAllAnimations = function () {
  49934. this._attachedCamera.animations = [];
  49935. while (this._animatables.length) {
  49936. this._animatables[0].onAnimationEnd = null;
  49937. this._animatables[0].stop();
  49938. this._animatables.shift();
  49939. }
  49940. };
  49941. /**
  49942. * The easing function used by animations
  49943. */
  49944. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  49945. /**
  49946. * The easing mode used by animations
  49947. */
  49948. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  49949. return BouncingBehavior;
  49950. }());
  49951. BABYLON.BouncingBehavior = BouncingBehavior;
  49952. })(BABYLON || (BABYLON = {}));
  49953. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  49954. var BABYLON;
  49955. (function (BABYLON) {
  49956. var AutoRotationBehavior = (function () {
  49957. function AutoRotationBehavior() {
  49958. this._zoomStopsAnimation = false;
  49959. this._idleRotationSpeed = 0.05;
  49960. this._idleRotationWaitTime = 2000;
  49961. this._idleRotationSpinupTime = 2000;
  49962. this._isPointerDown = false;
  49963. this._lastFrameTime = null;
  49964. this._lastInteractionTime = -Infinity;
  49965. this._lastFrameRadius = 0;
  49966. }
  49967. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  49968. get: function () {
  49969. return "AutoRotation";
  49970. },
  49971. enumerable: true,
  49972. configurable: true
  49973. });
  49974. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  49975. /**
  49976. * Gets the flag that indicates if user zooming should stop animation.
  49977. */
  49978. get: function () {
  49979. return this._zoomStopsAnimation;
  49980. },
  49981. /**
  49982. * Sets the flag that indicates if user zooming should stop animation.
  49983. */
  49984. set: function (flag) {
  49985. this._zoomStopsAnimation = flag;
  49986. },
  49987. enumerable: true,
  49988. configurable: true
  49989. });
  49990. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  49991. /**
  49992. * Gets the default speed at which the camera rotates around the model.
  49993. */
  49994. get: function () {
  49995. return this._idleRotationSpeed;
  49996. },
  49997. /**
  49998. * Sets the default speed at which the camera rotates around the model.
  49999. */
  50000. set: function (speed) {
  50001. this._idleRotationSpeed = speed;
  50002. },
  50003. enumerable: true,
  50004. configurable: true
  50005. });
  50006. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  50007. /**
  50008. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  50009. */
  50010. get: function () {
  50011. return this._idleRotationWaitTime;
  50012. },
  50013. /**
  50014. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  50015. */
  50016. set: function (time) {
  50017. this._idleRotationWaitTime = time;
  50018. },
  50019. enumerable: true,
  50020. configurable: true
  50021. });
  50022. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  50023. /**
  50024. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50025. */
  50026. get: function () {
  50027. return this._idleRotationSpinupTime;
  50028. },
  50029. /**
  50030. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50031. */
  50032. set: function (time) {
  50033. this._idleRotationSpinupTime = time;
  50034. },
  50035. enumerable: true,
  50036. configurable: true
  50037. });
  50038. AutoRotationBehavior.prototype.attach = function (camera) {
  50039. var _this = this;
  50040. this._attachedCamera = camera;
  50041. var scene = this._attachedCamera.getScene();
  50042. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  50043. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50044. _this._isPointerDown = true;
  50045. return;
  50046. }
  50047. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  50048. _this._isPointerDown = false;
  50049. }
  50050. });
  50051. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50052. var now = BABYLON.Tools.Now;
  50053. var dt = 16;
  50054. if (_this._lastFrameTime != null) {
  50055. dt = now - _this._lastFrameTime;
  50056. }
  50057. _this._lastFrameTime = now;
  50058. // Stop the animation if there is user interaction and the animation should stop for this interaction
  50059. _this._applyUserInteraction();
  50060. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  50061. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  50062. var cameraRotationSpeed = _this._idleRotationSpeed * scale;
  50063. // Step camera rotation by rotation speed
  50064. _this._attachedCamera.alpha -= cameraRotationSpeed * (dt / 1000);
  50065. });
  50066. };
  50067. AutoRotationBehavior.prototype.detach = function (camera) {
  50068. var scene = this._attachedCamera.getScene();
  50069. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  50070. camera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50071. };
  50072. /**
  50073. * Returns true if user is scrolling.
  50074. * @return true if user is scrolling.
  50075. */
  50076. AutoRotationBehavior.prototype._userIsZooming = function () {
  50077. return this._attachedCamera.inertialRadiusOffset !== 0;
  50078. };
  50079. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  50080. var zoomHasHitLimit = false;
  50081. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  50082. zoomHasHitLimit = true;
  50083. }
  50084. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  50085. this._lastFrameRadius = this._attachedCamera.radius;
  50086. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  50087. };
  50088. /**
  50089. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  50090. */
  50091. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  50092. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  50093. this._lastInteractionTime = BABYLON.Tools.Now;
  50094. }
  50095. };
  50096. // Tools
  50097. AutoRotationBehavior.prototype._userIsMoving = function () {
  50098. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  50099. this._attachedCamera.inertialBetaOffset !== 0 ||
  50100. this._attachedCamera.inertialRadiusOffset !== 0 ||
  50101. this._attachedCamera.inertialPanningX !== 0 ||
  50102. this._attachedCamera.inertialPanningY !== 0 ||
  50103. this._isPointerDown;
  50104. };
  50105. return AutoRotationBehavior;
  50106. }());
  50107. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  50108. })(BABYLON || (BABYLON = {}));
  50109. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  50110. var BABYLON;
  50111. (function (BABYLON) {
  50112. var MorphTarget = (function () {
  50113. function MorphTarget(name, influence) {
  50114. if (influence === void 0) { influence = 0; }
  50115. this.name = name;
  50116. this.animations = new Array();
  50117. this.onInfluenceChanged = new BABYLON.Observable();
  50118. this.influence = influence;
  50119. }
  50120. Object.defineProperty(MorphTarget.prototype, "influence", {
  50121. get: function () {
  50122. return this._influence;
  50123. },
  50124. set: function (influence) {
  50125. if (this._influence === influence) {
  50126. return;
  50127. }
  50128. var previous = this._influence;
  50129. this._influence = influence;
  50130. if (this.onInfluenceChanged.hasObservers) {
  50131. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  50132. }
  50133. },
  50134. enumerable: true,
  50135. configurable: true
  50136. });
  50137. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  50138. get: function () {
  50139. return this._normals !== undefined;
  50140. },
  50141. enumerable: true,
  50142. configurable: true
  50143. });
  50144. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  50145. get: function () {
  50146. return this._tangents !== undefined;
  50147. },
  50148. enumerable: true,
  50149. configurable: true
  50150. });
  50151. MorphTarget.prototype.setPositions = function (data) {
  50152. this._positions = new Float32Array(data);
  50153. };
  50154. MorphTarget.prototype.getPositions = function () {
  50155. return this._positions;
  50156. };
  50157. MorphTarget.prototype.setNormals = function (data) {
  50158. this._normals = new Float32Array(data);
  50159. };
  50160. MorphTarget.prototype.getNormals = function () {
  50161. return this._normals;
  50162. };
  50163. MorphTarget.prototype.setTangents = function (data) {
  50164. this._tangents = new Float32Array(data);
  50165. };
  50166. MorphTarget.prototype.getTangents = function () {
  50167. return this._tangents;
  50168. };
  50169. /**
  50170. * Serializes the current target into a Serialization object.
  50171. * Returns the serialized object.
  50172. */
  50173. MorphTarget.prototype.serialize = function () {
  50174. var serializationObject = {};
  50175. serializationObject.name = this.name;
  50176. serializationObject.influence = this.influence;
  50177. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  50178. if (this.hasNormals) {
  50179. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  50180. }
  50181. if (this.hasTangents) {
  50182. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  50183. }
  50184. return serializationObject;
  50185. };
  50186. // Statics
  50187. MorphTarget.Parse = function (serializationObject) {
  50188. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  50189. result.setPositions(serializationObject.positions);
  50190. if (serializationObject.normals) {
  50191. result.setNormals(serializationObject.normals);
  50192. }
  50193. if (serializationObject.tangents) {
  50194. result.setTangents(serializationObject.tangents);
  50195. }
  50196. return result;
  50197. };
  50198. MorphTarget.FromMesh = function (mesh, name, influence) {
  50199. if (!name) {
  50200. name = mesh.name;
  50201. }
  50202. var result = new MorphTarget(name, influence);
  50203. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  50204. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50205. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  50206. }
  50207. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  50208. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  50209. }
  50210. return result;
  50211. };
  50212. return MorphTarget;
  50213. }());
  50214. BABYLON.MorphTarget = MorphTarget;
  50215. })(BABYLON || (BABYLON = {}));
  50216. //# sourceMappingURL=babylon.morphTarget.js.map
  50217. var BABYLON;
  50218. (function (BABYLON) {
  50219. var MorphTargetManager = (function () {
  50220. function MorphTargetManager(scene) {
  50221. this._targets = new Array();
  50222. this._targetObservable = new Array();
  50223. this._activeTargets = new BABYLON.SmartArray(16);
  50224. this._supportsNormals = false;
  50225. this._supportsTangents = false;
  50226. this._vertexCount = 0;
  50227. this._uniqueId = 0;
  50228. this._tempInfluences = new Array();
  50229. if (!scene) {
  50230. scene = BABYLON.Engine.LastCreatedScene;
  50231. }
  50232. this._scene = scene;
  50233. this._scene.morphTargetManagers.push(this);
  50234. this._uniqueId = scene.getUniqueId();
  50235. }
  50236. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  50237. get: function () {
  50238. return this._uniqueId;
  50239. },
  50240. enumerable: true,
  50241. configurable: true
  50242. });
  50243. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  50244. get: function () {
  50245. return this._vertexCount;
  50246. },
  50247. enumerable: true,
  50248. configurable: true
  50249. });
  50250. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  50251. get: function () {
  50252. return this._supportsNormals;
  50253. },
  50254. enumerable: true,
  50255. configurable: true
  50256. });
  50257. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  50258. get: function () {
  50259. return this._supportsTangents;
  50260. },
  50261. enumerable: true,
  50262. configurable: true
  50263. });
  50264. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  50265. get: function () {
  50266. return this._targets.length;
  50267. },
  50268. enumerable: true,
  50269. configurable: true
  50270. });
  50271. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  50272. get: function () {
  50273. return this._activeTargets.length;
  50274. },
  50275. enumerable: true,
  50276. configurable: true
  50277. });
  50278. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  50279. get: function () {
  50280. return this._influences;
  50281. },
  50282. enumerable: true,
  50283. configurable: true
  50284. });
  50285. MorphTargetManager.prototype.getActiveTarget = function (index) {
  50286. return this._activeTargets.data[index];
  50287. };
  50288. MorphTargetManager.prototype.getTarget = function (index) {
  50289. return this._targets[index];
  50290. };
  50291. MorphTargetManager.prototype.addTarget = function (target) {
  50292. var _this = this;
  50293. if (this._vertexCount) {
  50294. if (this._vertexCount !== target.getPositions().length / 3) {
  50295. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  50296. return;
  50297. }
  50298. }
  50299. this._targets.push(target);
  50300. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  50301. _this._syncActiveTargets(needUpdate);
  50302. }));
  50303. this._syncActiveTargets(true);
  50304. };
  50305. MorphTargetManager.prototype.removeTarget = function (target) {
  50306. var index = this._targets.indexOf(target);
  50307. if (index >= 0) {
  50308. this._targets.splice(index, 1);
  50309. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  50310. this._vertexCount = 0;
  50311. this._syncActiveTargets(true);
  50312. }
  50313. };
  50314. /**
  50315. * Serializes the current manager into a Serialization object.
  50316. * Returns the serialized object.
  50317. */
  50318. MorphTargetManager.prototype.serialize = function () {
  50319. var serializationObject = {};
  50320. serializationObject.id = this.uniqueId;
  50321. serializationObject.targets = [];
  50322. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  50323. var target = _a[_i];
  50324. serializationObject.targets.push(target.serialize());
  50325. }
  50326. return serializationObject;
  50327. };
  50328. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  50329. this._syncActiveTargets(needUpdate);
  50330. };
  50331. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  50332. var influenceCount = 0;
  50333. this._activeTargets.reset();
  50334. this._supportsNormals = true;
  50335. this._supportsTangents = true;
  50336. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  50337. var target = _a[_i];
  50338. if (target.influence > 0) {
  50339. this._activeTargets.push(target);
  50340. this._tempInfluences[influenceCount++] = target.influence;
  50341. this._supportsNormals = this._supportsNormals && target.hasNormals;
  50342. this._supportsTangents = this._supportsTangents && target.hasTangents;
  50343. if (this._vertexCount === 0) {
  50344. this._vertexCount = target.getPositions().length / 3;
  50345. }
  50346. }
  50347. }
  50348. if (!this._influences || this._influences.length !== influenceCount) {
  50349. this._influences = new Float32Array(influenceCount);
  50350. }
  50351. for (var index = 0; index < influenceCount; index++) {
  50352. this._influences[index] = this._tempInfluences[index];
  50353. }
  50354. if (needUpdate) {
  50355. // Flag meshes as dirty to resync with the active targets
  50356. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  50357. var mesh = _c[_b];
  50358. if (mesh.morphTargetManager === this) {
  50359. mesh._syncGeometryWithMorphTargetManager();
  50360. }
  50361. }
  50362. }
  50363. };
  50364. // Statics
  50365. MorphTargetManager.Parse = function (serializationObject, scene) {
  50366. var result = new MorphTargetManager(scene);
  50367. result._uniqueId = serializationObject.id;
  50368. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  50369. var targetData = _a[_i];
  50370. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  50371. }
  50372. return result;
  50373. };
  50374. return MorphTargetManager;
  50375. }());
  50376. BABYLON.MorphTargetManager = MorphTargetManager;
  50377. })(BABYLON || (BABYLON = {}));
  50378. //# sourceMappingURL=babylon.morphTargetManager.js.map
  50379. BABYLON.Effect.ShadersStore={"postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\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 MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \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#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \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#if defined(OPACITY) && OPACITYDIRECTUV == 0 \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#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \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#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \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) && REFLECTIVITYDIRECTUV == 0 \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#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \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#if defined(BUMP) && BUMPDIRECTUV == 0 \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) || defined(FORCENORMALFORWARD)\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 vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\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 ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nfloat comp=sign(dot(normalW,faceNormal));\nnormalW*=-comp;\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\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#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && !defined(USESPHERICALINFRAGMENT)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\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#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\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#if defined(OPACITY) && OPACITYDIRECTUV == 0\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#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\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#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\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) && SPECULARDIRECTUV == 0\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#if defined(BUMP) && BUMPDIRECTUV == 0\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#if defined(BUMP) || !defined(NORMAL)\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#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\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)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\ngl_FragColor=color;\n}"};
  50380. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangentUpdated.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangentUpdated.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \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\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\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;\nuniform vec4 vNormalReoderParams;\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 REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\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 vec4 vNormalReoderParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\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.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#ifdef COLORGRADING\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\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>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\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;\nmap.x=vNormalReoderParams.x+vNormalReoderParams.y*map.x;\nmap.y=vNormalReoderParams.z+vNormalReoderParams.w*map.y;\nmap=map*255./127.-128./127.;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\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\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec4 vNormalReoderParams;\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; \nvec4 vNormalReoderParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  50381. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  50382. var BABYLON;
  50383. (function (BABYLON) {
  50384. var GridMaterialDefines = (function (_super) {
  50385. __extends(GridMaterialDefines, _super);
  50386. function GridMaterialDefines() {
  50387. var _this = _super.call(this) || this;
  50388. _this.TRANSPARENT = false;
  50389. _this.FOG = false;
  50390. _this.PREMULTIPLYALPHA = false;
  50391. _this.rebuild();
  50392. return _this;
  50393. }
  50394. return GridMaterialDefines;
  50395. }(BABYLON.MaterialDefines));
  50396. /**
  50397. * The grid materials allows you to wrap any shape with a grid.
  50398. * Colors are customizable.
  50399. */
  50400. var GridMaterial = (function (_super) {
  50401. __extends(GridMaterial, _super);
  50402. /**
  50403. * constructor
  50404. * @param name The name given to the material in order to identify it afterwards.
  50405. * @param scene The scene the material is used in.
  50406. */
  50407. function GridMaterial(name, scene) {
  50408. var _this = _super.call(this, name, scene) || this;
  50409. /**
  50410. * Main color of the grid (e.g. between lines)
  50411. */
  50412. _this.mainColor = BABYLON.Color3.Black();
  50413. /**
  50414. * Color of the grid lines.
  50415. */
  50416. _this.lineColor = BABYLON.Color3.Teal();
  50417. /**
  50418. * The scale of the grid compared to unit.
  50419. */
  50420. _this.gridRatio = 1.0;
  50421. /**
  50422. * The frequency of thicker lines.
  50423. */
  50424. _this.majorUnitFrequency = 10;
  50425. /**
  50426. * The visibility of minor units in the grid.
  50427. */
  50428. _this.minorUnitVisibility = 0.33;
  50429. /**
  50430. * The grid opacity outside of the lines.
  50431. */
  50432. _this.opacity = 1.0;
  50433. /**
  50434. * Determine RBG output is premultiplied by alpha value.
  50435. */
  50436. _this.preMultiplyAlpha = false;
  50437. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  50438. return _this;
  50439. }
  50440. /**
  50441. * Returns wehter or not the grid requires alpha blending.
  50442. */
  50443. GridMaterial.prototype.needAlphaBlending = function () {
  50444. return this.opacity < 1.0;
  50445. };
  50446. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  50447. if (this.isFrozen) {
  50448. if (this._wasPreviouslyReady && subMesh.effect) {
  50449. return true;
  50450. }
  50451. }
  50452. if (!subMesh._materialDefines) {
  50453. subMesh._materialDefines = new GridMaterialDefines();
  50454. }
  50455. var defines = subMesh._materialDefines;
  50456. var scene = this.getScene();
  50457. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  50458. if (this._renderId === scene.getRenderId()) {
  50459. return true;
  50460. }
  50461. }
  50462. var engine = scene.getEngine();
  50463. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  50464. defines.TRANSPARENT = !defines.TRANSPARENT;
  50465. defines.markAsUnprocessed();
  50466. }
  50467. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  50468. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  50469. defines.markAsUnprocessed();
  50470. }
  50471. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  50472. // Get correct effect
  50473. if (defines.isDirty) {
  50474. defines.markAsProcessed();
  50475. scene.resetCachedMaterial();
  50476. // Attributes
  50477. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  50478. // Defines
  50479. var join = defines.toString();
  50480. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  50481. }
  50482. if (!subMesh.effect.isReady()) {
  50483. return false;
  50484. }
  50485. this._renderId = scene.getRenderId();
  50486. this._wasPreviouslyReady = true;
  50487. return true;
  50488. };
  50489. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  50490. var scene = this.getScene();
  50491. var defines = subMesh._materialDefines;
  50492. if (!defines) {
  50493. return;
  50494. }
  50495. var effect = subMesh.effect;
  50496. this._activeEffect = effect;
  50497. // Matrices
  50498. this.bindOnlyWorldMatrix(world);
  50499. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  50500. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  50501. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  50502. // Uniforms
  50503. if (this._mustRebind(scene, effect)) {
  50504. this._activeEffect.setColor3("mainColor", this.mainColor);
  50505. this._activeEffect.setColor3("lineColor", this.lineColor);
  50506. this._gridControl.x = this.gridRatio;
  50507. this._gridControl.y = Math.round(this.majorUnitFrequency);
  50508. this._gridControl.z = this.minorUnitVisibility;
  50509. this._gridControl.w = this.opacity;
  50510. this._activeEffect.setVector4("gridControl", this._gridControl);
  50511. }
  50512. // Fog
  50513. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  50514. this._afterBind(mesh, this._activeEffect);
  50515. };
  50516. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  50517. _super.prototype.dispose.call(this, forceDisposeEffect);
  50518. };
  50519. GridMaterial.prototype.clone = function (name) {
  50520. var _this = this;
  50521. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  50522. };
  50523. GridMaterial.prototype.serialize = function () {
  50524. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  50525. serializationObject.customType = "BABYLON.GridMaterial";
  50526. return serializationObject;
  50527. };
  50528. GridMaterial.prototype.getClassName = function () {
  50529. return "GridMaterial";
  50530. };
  50531. GridMaterial.Parse = function (source, scene, rootUrl) {
  50532. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  50533. };
  50534. __decorate([
  50535. BABYLON.serializeAsColor3()
  50536. ], GridMaterial.prototype, "mainColor", void 0);
  50537. __decorate([
  50538. BABYLON.serializeAsColor3()
  50539. ], GridMaterial.prototype, "lineColor", void 0);
  50540. __decorate([
  50541. BABYLON.serialize()
  50542. ], GridMaterial.prototype, "gridRatio", void 0);
  50543. __decorate([
  50544. BABYLON.serialize()
  50545. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  50546. __decorate([
  50547. BABYLON.serialize()
  50548. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  50549. __decorate([
  50550. BABYLON.serialize()
  50551. ], GridMaterial.prototype, "opacity", void 0);
  50552. __decorate([
  50553. BABYLON.serialize()
  50554. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  50555. return GridMaterial;
  50556. }(BABYLON.PushMaterial));
  50557. BABYLON.GridMaterial = GridMaterial;
  50558. })(BABYLON || (BABYLON = {}));
  50559. //# sourceMappingURL=babylon.gridmaterial.js.map
  50560. BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}";
  50561. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=vPosition/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  50562. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  50563. var BABYLON;
  50564. (function (BABYLON) {
  50565. var GLTFLoaderCoordinateSystemMode;
  50566. (function (GLTFLoaderCoordinateSystemMode) {
  50567. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  50568. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  50569. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  50570. // The glTF right-handed data is not transformed in any form and is loaded directly.
  50571. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  50572. // Sets the useRightHandedSystem flag on the scene.
  50573. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  50574. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  50575. var GLTFFileLoader = (function () {
  50576. function GLTFFileLoader() {
  50577. // V2 options
  50578. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  50579. this.name = "gltf";
  50580. this.extensions = {
  50581. ".gltf": { isBinary: false },
  50582. ".glb": { isBinary: true }
  50583. };
  50584. }
  50585. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  50586. var loaderData = GLTFFileLoader._parse(data, onError);
  50587. if (!loaderData) {
  50588. return;
  50589. }
  50590. var loader = this._getLoader(loaderData, onError);
  50591. if (!loader) {
  50592. return;
  50593. }
  50594. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  50595. };
  50596. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  50597. var loaderData = GLTFFileLoader._parse(data, onError);
  50598. if (!loaderData) {
  50599. return;
  50600. }
  50601. var loader = this._getLoader(loaderData, onError);
  50602. if (!loader) {
  50603. return;
  50604. }
  50605. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  50606. };
  50607. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  50608. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  50609. };
  50610. GLTFFileLoader._parse = function (data, onError) {
  50611. if (data instanceof ArrayBuffer) {
  50612. return GLTFFileLoader._parseBinary(data, onError);
  50613. }
  50614. try {
  50615. return {
  50616. json: JSON.parse(data),
  50617. bin: null
  50618. };
  50619. }
  50620. catch (e) {
  50621. onError(e.message);
  50622. return null;
  50623. }
  50624. };
  50625. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  50626. var loaderVersion = { major: 2, minor: 0 };
  50627. var asset = loaderData.json.asset || {};
  50628. var version = GLTFFileLoader._parseVersion(asset.version);
  50629. if (!version) {
  50630. onError("Invalid version: " + asset.version);
  50631. return null;
  50632. }
  50633. if (asset.minVersion !== undefined) {
  50634. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  50635. if (!minVersion) {
  50636. onError("Invalid minimum version: " + asset.minVersion);
  50637. return null;
  50638. }
  50639. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  50640. onError("Incompatible minimum version: " + asset.minVersion);
  50641. return null;
  50642. }
  50643. }
  50644. var createLoaders = {
  50645. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  50646. 2: GLTFFileLoader.CreateGLTFLoaderV2
  50647. };
  50648. var createLoader = createLoaders[version.major];
  50649. if (!createLoader) {
  50650. onError("Unsupported version: " + asset.version);
  50651. return null;
  50652. }
  50653. return createLoader(this);
  50654. };
  50655. GLTFFileLoader._parseBinary = function (data, onError) {
  50656. var Binary = {
  50657. Magic: 0x46546C67
  50658. };
  50659. var binaryReader = new BinaryReader(data);
  50660. var magic = binaryReader.readUint32();
  50661. if (magic !== Binary.Magic) {
  50662. onError("Unexpected magic: " + magic);
  50663. return null;
  50664. }
  50665. var version = binaryReader.readUint32();
  50666. switch (version) {
  50667. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  50668. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  50669. }
  50670. onError("Unsupported version: " + version);
  50671. return null;
  50672. };
  50673. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  50674. var ContentFormat = {
  50675. JSON: 0
  50676. };
  50677. var length = binaryReader.readUint32();
  50678. if (length != binaryReader.getLength()) {
  50679. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  50680. return null;
  50681. }
  50682. var contentLength = binaryReader.readUint32();
  50683. var contentFormat = binaryReader.readUint32();
  50684. var content;
  50685. switch (contentFormat) {
  50686. case ContentFormat.JSON:
  50687. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  50688. break;
  50689. default:
  50690. onError("Unexpected content format: " + contentFormat);
  50691. return null;
  50692. }
  50693. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  50694. var body = binaryReader.readUint8Array(bytesRemaining);
  50695. return {
  50696. json: content,
  50697. bin: body
  50698. };
  50699. };
  50700. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  50701. var ChunkFormat = {
  50702. JSON: 0x4E4F534A,
  50703. BIN: 0x004E4942
  50704. };
  50705. var length = binaryReader.readUint32();
  50706. if (length !== binaryReader.getLength()) {
  50707. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  50708. return null;
  50709. }
  50710. // JSON chunk
  50711. var chunkLength = binaryReader.readUint32();
  50712. var chunkFormat = binaryReader.readUint32();
  50713. if (chunkFormat !== ChunkFormat.JSON) {
  50714. onError("First chunk format is not JSON");
  50715. return null;
  50716. }
  50717. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  50718. // Look for BIN chunk
  50719. var bin = null;
  50720. while (binaryReader.getPosition() < binaryReader.getLength()) {
  50721. chunkLength = binaryReader.readUint32();
  50722. chunkFormat = binaryReader.readUint32();
  50723. switch (chunkFormat) {
  50724. case ChunkFormat.JSON:
  50725. onError("Unexpected JSON chunk");
  50726. return null;
  50727. case ChunkFormat.BIN:
  50728. bin = binaryReader.readUint8Array(chunkLength);
  50729. break;
  50730. default:
  50731. // ignore unrecognized chunkFormat
  50732. binaryReader.skipBytes(chunkLength);
  50733. break;
  50734. }
  50735. }
  50736. return {
  50737. json: json,
  50738. bin: bin
  50739. };
  50740. };
  50741. GLTFFileLoader._parseVersion = function (version) {
  50742. if (!version) {
  50743. return null;
  50744. }
  50745. var parts = version.split(".");
  50746. if (parts.length != 2) {
  50747. return null;
  50748. }
  50749. var major = +parts[0];
  50750. if (isNaN(major)) {
  50751. return null;
  50752. }
  50753. var minor = +parts[1];
  50754. if (isNaN(minor)) {
  50755. return null;
  50756. }
  50757. return {
  50758. major: major,
  50759. minor: minor
  50760. };
  50761. };
  50762. GLTFFileLoader._compareVersion = function (a, b) {
  50763. if (a.major > b.major)
  50764. return 1;
  50765. if (a.major < b.major)
  50766. return -1;
  50767. if (a.minor > b.minor)
  50768. return 1;
  50769. if (a.minor < b.minor)
  50770. return -1;
  50771. return 0;
  50772. };
  50773. GLTFFileLoader._decodeBufferToText = function (view) {
  50774. var result = "";
  50775. var length = view.byteLength;
  50776. for (var i = 0; i < length; ++i) {
  50777. result += String.fromCharCode(view[i]);
  50778. }
  50779. return result;
  50780. };
  50781. // V1 options
  50782. GLTFFileLoader.HomogeneousCoordinates = false;
  50783. GLTFFileLoader.IncrementalLoading = true;
  50784. return GLTFFileLoader;
  50785. }());
  50786. BABYLON.GLTFFileLoader = GLTFFileLoader;
  50787. var BinaryReader = (function () {
  50788. function BinaryReader(arrayBuffer) {
  50789. this._arrayBuffer = arrayBuffer;
  50790. this._dataView = new DataView(arrayBuffer);
  50791. this._byteOffset = 0;
  50792. }
  50793. BinaryReader.prototype.getPosition = function () {
  50794. return this._byteOffset;
  50795. };
  50796. BinaryReader.prototype.getLength = function () {
  50797. return this._arrayBuffer.byteLength;
  50798. };
  50799. BinaryReader.prototype.readUint32 = function () {
  50800. var value = this._dataView.getUint32(this._byteOffset, true);
  50801. this._byteOffset += 4;
  50802. return value;
  50803. };
  50804. BinaryReader.prototype.readUint8Array = function (length) {
  50805. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  50806. this._byteOffset += length;
  50807. return value;
  50808. };
  50809. BinaryReader.prototype.skipBytes = function (length) {
  50810. this._byteOffset += length;
  50811. };
  50812. return BinaryReader;
  50813. }());
  50814. if (BABYLON.SceneLoader) {
  50815. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  50816. }
  50817. })(BABYLON || (BABYLON = {}));
  50818. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  50819. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  50820. var BABYLON;
  50821. (function (BABYLON) {
  50822. var GLTF1;
  50823. (function (GLTF1) {
  50824. /**
  50825. * Enums
  50826. */
  50827. var EComponentType;
  50828. (function (EComponentType) {
  50829. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  50830. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  50831. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  50832. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  50833. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  50834. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  50835. var EShaderType;
  50836. (function (EShaderType) {
  50837. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  50838. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  50839. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  50840. var EParameterType;
  50841. (function (EParameterType) {
  50842. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  50843. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  50844. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  50845. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  50846. EParameterType[EParameterType["INT"] = 5124] = "INT";
  50847. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  50848. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  50849. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  50850. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  50851. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  50852. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  50853. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  50854. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  50855. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  50856. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  50857. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  50858. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  50859. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  50860. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  50861. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  50862. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  50863. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  50864. var ETextureWrapMode;
  50865. (function (ETextureWrapMode) {
  50866. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  50867. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  50868. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  50869. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  50870. var ETextureFilterType;
  50871. (function (ETextureFilterType) {
  50872. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  50873. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  50874. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  50875. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  50876. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  50877. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  50878. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  50879. var ETextureFormat;
  50880. (function (ETextureFormat) {
  50881. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  50882. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  50883. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  50884. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  50885. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  50886. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  50887. var ECullingType;
  50888. (function (ECullingType) {
  50889. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  50890. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  50891. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  50892. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  50893. var EBlendingFunction;
  50894. (function (EBlendingFunction) {
  50895. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  50896. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  50897. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  50898. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  50899. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  50900. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  50901. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  50902. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  50903. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  50904. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  50905. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  50906. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  50907. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  50908. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  50909. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  50910. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  50911. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  50912. })(BABYLON || (BABYLON = {}));
  50913. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  50914. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  50915. var BABYLON;
  50916. (function (BABYLON) {
  50917. var GLTF1;
  50918. (function (GLTF1) {
  50919. /**
  50920. * Tokenizer. Used for shaders compatibility
  50921. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  50922. */
  50923. var ETokenType;
  50924. (function (ETokenType) {
  50925. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  50926. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  50927. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  50928. })(ETokenType || (ETokenType = {}));
  50929. var Tokenizer = (function () {
  50930. function Tokenizer(toParse) {
  50931. this._pos = 0;
  50932. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  50933. this._toParse = toParse;
  50934. this._maxPos = toParse.length;
  50935. }
  50936. Tokenizer.prototype.getNextToken = function () {
  50937. if (this.isEnd())
  50938. return ETokenType.END_OF_INPUT;
  50939. this.currentString = this.read();
  50940. this.currentToken = ETokenType.UNKNOWN;
  50941. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  50942. this.currentToken = ETokenType.IDENTIFIER;
  50943. this.currentIdentifier = this.currentString;
  50944. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  50945. this.currentIdentifier += this.currentString;
  50946. this.forward();
  50947. }
  50948. }
  50949. return this.currentToken;
  50950. };
  50951. Tokenizer.prototype.peek = function () {
  50952. return this._toParse[this._pos];
  50953. };
  50954. Tokenizer.prototype.read = function () {
  50955. return this._toParse[this._pos++];
  50956. };
  50957. Tokenizer.prototype.forward = function () {
  50958. this._pos++;
  50959. };
  50960. Tokenizer.prototype.isEnd = function () {
  50961. return this._pos >= this._maxPos;
  50962. };
  50963. return Tokenizer;
  50964. }());
  50965. /**
  50966. * Values
  50967. */
  50968. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  50969. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  50970. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  50971. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  50972. /**
  50973. * Parse
  50974. */
  50975. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  50976. for (var buf in parsedBuffers) {
  50977. var parsedBuffer = parsedBuffers[buf];
  50978. gltfRuntime.buffers[buf] = parsedBuffer;
  50979. gltfRuntime.buffersCount++;
  50980. }
  50981. };
  50982. var parseShaders = function (parsedShaders, gltfRuntime) {
  50983. for (var sha in parsedShaders) {
  50984. var parsedShader = parsedShaders[sha];
  50985. gltfRuntime.shaders[sha] = parsedShader;
  50986. gltfRuntime.shaderscount++;
  50987. }
  50988. };
  50989. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  50990. for (var object in parsedObjects) {
  50991. var parsedObject = parsedObjects[object];
  50992. gltfRuntime[runtimeProperty][object] = parsedObject;
  50993. }
  50994. };
  50995. /**
  50996. * Utils
  50997. */
  50998. var normalizeUVs = function (buffer) {
  50999. if (!buffer) {
  51000. return;
  51001. }
  51002. for (var i = 0; i < buffer.length / 2; i++) {
  51003. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  51004. }
  51005. };
  51006. var replaceInString = function (str, searchValue, replaceValue) {
  51007. while (str.indexOf(searchValue) !== -1) {
  51008. str = str.replace(searchValue, replaceValue);
  51009. }
  51010. return str;
  51011. };
  51012. var getAttribute = function (attributeParameter) {
  51013. if (attributeParameter.semantic === "NORMAL") {
  51014. return "normal";
  51015. }
  51016. else if (attributeParameter.semantic === "POSITION") {
  51017. return "position";
  51018. }
  51019. else if (attributeParameter.semantic === "JOINT") {
  51020. return "matricesIndices";
  51021. }
  51022. else if (attributeParameter.semantic === "WEIGHT") {
  51023. return "matricesWeights";
  51024. }
  51025. else if (attributeParameter.semantic === "COLOR") {
  51026. return "color";
  51027. }
  51028. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  51029. var channel = Number(attributeParameter.semantic.split("_")[1]);
  51030. return "uv" + (channel === 0 ? "" : channel + 1);
  51031. }
  51032. };
  51033. /**
  51034. * Returns the animation path (glTF -> Babylon)
  51035. */
  51036. var getAnimationPath = function (path) {
  51037. var index = glTFAnimationPaths.indexOf(path);
  51038. if (index !== -1) {
  51039. return babylonAnimationPaths[index];
  51040. }
  51041. return path;
  51042. };
  51043. /**
  51044. * Loads and creates animations
  51045. */
  51046. var loadAnimations = function (gltfRuntime) {
  51047. for (var anim in gltfRuntime.animations) {
  51048. var animation = gltfRuntime.animations[anim];
  51049. var lastAnimation = null;
  51050. for (var i = 0; i < animation.channels.length; i++) {
  51051. // Get parameters and load buffers
  51052. var channel = animation.channels[i];
  51053. var sampler = animation.samplers[channel.sampler];
  51054. if (!sampler) {
  51055. continue;
  51056. }
  51057. var inputData = null;
  51058. var outputData = null;
  51059. if (animation.parameters) {
  51060. inputData = animation.parameters[sampler.input];
  51061. outputData = animation.parameters[sampler.output];
  51062. }
  51063. else {
  51064. inputData = sampler.input;
  51065. outputData = sampler.output;
  51066. }
  51067. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  51068. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  51069. var targetID = channel.target.id;
  51070. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  51071. if (targetNode === null) {
  51072. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  51073. }
  51074. if (targetNode === null) {
  51075. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  51076. continue;
  51077. }
  51078. var isBone = targetNode instanceof BABYLON.Bone;
  51079. // Get target path (position, rotation or scaling)
  51080. var targetPath = channel.target.path;
  51081. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  51082. if (targetPathIndex !== -1) {
  51083. targetPath = babylonAnimationPaths[targetPathIndex];
  51084. }
  51085. // Determine animation type
  51086. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  51087. if (!isBone) {
  51088. if (targetPath === "rotationQuaternion") {
  51089. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  51090. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  51091. }
  51092. else {
  51093. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  51094. }
  51095. }
  51096. // Create animation and key frames
  51097. var babylonAnimation = null;
  51098. var keys = [];
  51099. var arrayOffset = 0;
  51100. var modifyKey = false;
  51101. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  51102. babylonAnimation = lastAnimation;
  51103. modifyKey = true;
  51104. }
  51105. if (!modifyKey) {
  51106. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51107. }
  51108. // For each frame
  51109. for (var j = 0; j < bufferInput.length; j++) {
  51110. var value = null;
  51111. if (targetPath === "rotationQuaternion") {
  51112. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  51113. arrayOffset += 4;
  51114. }
  51115. else {
  51116. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  51117. arrayOffset += 3;
  51118. }
  51119. if (isBone) {
  51120. var bone = targetNode;
  51121. var translation = BABYLON.Vector3.Zero();
  51122. var rotationQuaternion = new BABYLON.Quaternion();
  51123. var scaling = BABYLON.Vector3.Zero();
  51124. // Warning on decompose
  51125. var mat = bone.getBaseMatrix();
  51126. if (modifyKey) {
  51127. mat = lastAnimation.getKeys()[j].value;
  51128. }
  51129. mat.decompose(scaling, rotationQuaternion, translation);
  51130. if (targetPath === "position") {
  51131. translation = value;
  51132. }
  51133. else if (targetPath === "rotationQuaternion") {
  51134. rotationQuaternion = value;
  51135. }
  51136. else {
  51137. scaling = value;
  51138. }
  51139. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  51140. }
  51141. if (!modifyKey) {
  51142. keys.push({
  51143. frame: bufferInput[j],
  51144. value: value
  51145. });
  51146. }
  51147. else {
  51148. lastAnimation.getKeys()[j].value = value;
  51149. }
  51150. }
  51151. // Finish
  51152. if (!modifyKey) {
  51153. babylonAnimation.setKeys(keys);
  51154. targetNode.animations.push(babylonAnimation);
  51155. }
  51156. lastAnimation = babylonAnimation;
  51157. gltfRuntime.scene.stopAnimation(targetNode);
  51158. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  51159. }
  51160. }
  51161. };
  51162. /**
  51163. * Returns the bones transformation matrix
  51164. */
  51165. var configureBoneTransformation = function (node) {
  51166. var mat = null;
  51167. if (node.translation || node.rotation || node.scale) {
  51168. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  51169. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  51170. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  51171. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  51172. }
  51173. else {
  51174. mat = BABYLON.Matrix.FromArray(node.matrix);
  51175. }
  51176. return mat;
  51177. };
  51178. /**
  51179. * Returns the parent bone
  51180. */
  51181. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  51182. // Try to find
  51183. for (var i = 0; i < newSkeleton.bones.length; i++) {
  51184. if (newSkeleton.bones[i].name === jointName) {
  51185. return newSkeleton.bones[i];
  51186. }
  51187. }
  51188. // Not found, search in gltf nodes
  51189. var nodes = gltfRuntime.nodes;
  51190. for (var nde in nodes) {
  51191. var node = nodes[nde];
  51192. if (!node.jointName) {
  51193. continue;
  51194. }
  51195. var children = node.children;
  51196. for (var i = 0; i < children.length; i++) {
  51197. var child = gltfRuntime.nodes[children[i]];
  51198. if (!child.jointName) {
  51199. continue;
  51200. }
  51201. if (child.jointName === jointName) {
  51202. var mat = configureBoneTransformation(node);
  51203. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  51204. bone.id = nde;
  51205. return bone;
  51206. }
  51207. }
  51208. }
  51209. return null;
  51210. };
  51211. /**
  51212. * Returns the appropriate root node
  51213. */
  51214. var getNodeToRoot = function (nodesToRoot, id) {
  51215. for (var i = 0; i < nodesToRoot.length; i++) {
  51216. var nodeToRoot = nodesToRoot[i];
  51217. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  51218. var child = nodeToRoot.node.children[j];
  51219. if (child === id) {
  51220. return nodeToRoot.bone;
  51221. }
  51222. }
  51223. }
  51224. return null;
  51225. };
  51226. /**
  51227. * Returns the node with the joint name
  51228. */
  51229. var getJointNode = function (gltfRuntime, jointName) {
  51230. var nodes = gltfRuntime.nodes;
  51231. var node = nodes[jointName];
  51232. if (node) {
  51233. return {
  51234. node: node,
  51235. id: jointName
  51236. };
  51237. }
  51238. for (var nde in nodes) {
  51239. node = nodes[nde];
  51240. if (node.jointName === jointName) {
  51241. return {
  51242. node: node,
  51243. id: nde
  51244. };
  51245. }
  51246. }
  51247. return null;
  51248. };
  51249. /**
  51250. * Checks if a nodes is in joints
  51251. */
  51252. var nodeIsInJoints = function (skins, id) {
  51253. for (var i = 0; i < skins.jointNames.length; i++) {
  51254. if (skins.jointNames[i] === id) {
  51255. return true;
  51256. }
  51257. }
  51258. return false;
  51259. };
  51260. /**
  51261. * Fills the nodes to root for bones and builds hierarchy
  51262. */
  51263. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  51264. // Creates nodes for root
  51265. for (var nde in gltfRuntime.nodes) {
  51266. var node = gltfRuntime.nodes[nde];
  51267. var id = nde;
  51268. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  51269. continue;
  51270. }
  51271. // Create node to root bone
  51272. var mat = configureBoneTransformation(node);
  51273. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  51274. bone.id = id;
  51275. nodesToRoot.push({ bone: bone, node: node, id: id });
  51276. }
  51277. // Parenting
  51278. for (var i = 0; i < nodesToRoot.length; i++) {
  51279. var nodeToRoot = nodesToRoot[i];
  51280. var children = nodeToRoot.node.children;
  51281. for (var j = 0; j < children.length; j++) {
  51282. var child = null;
  51283. for (var k = 0; k < nodesToRoot.length; k++) {
  51284. if (nodesToRoot[k].id === children[j]) {
  51285. child = nodesToRoot[k];
  51286. break;
  51287. }
  51288. }
  51289. if (child) {
  51290. child.bone._parent = nodeToRoot.bone;
  51291. nodeToRoot.bone.children.push(child.bone);
  51292. }
  51293. }
  51294. }
  51295. };
  51296. var printMat = function (m) {
  51297. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  51298. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  51299. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  51300. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  51301. };
  51302. /**
  51303. * Imports a skeleton
  51304. */
  51305. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  51306. if (!newSkeleton) {
  51307. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  51308. }
  51309. if (!skins.babylonSkeleton) {
  51310. return newSkeleton;
  51311. }
  51312. // Matrices
  51313. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  51314. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  51315. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  51316. // Find the root bones
  51317. var nodesToRoot = [];
  51318. var nodesToRootToAdd = [];
  51319. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  51320. newSkeleton.bones = [];
  51321. // Joints
  51322. for (var i = 0; i < skins.jointNames.length; i++) {
  51323. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  51324. var node = jointNode.node;
  51325. if (!node) {
  51326. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  51327. continue;
  51328. }
  51329. var id = jointNode.id;
  51330. // Optimize, if the bone already exists...
  51331. var existingBone = gltfRuntime.scene.getBoneByID(id);
  51332. if (existingBone) {
  51333. newSkeleton.bones.push(existingBone);
  51334. continue;
  51335. }
  51336. // Search for parent bone
  51337. var foundBone = false;
  51338. var parentBone = null;
  51339. for (var j = 0; j < i; j++) {
  51340. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  51341. if (!joint) {
  51342. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  51343. continue;
  51344. }
  51345. var children = joint.children;
  51346. if (!children) {
  51347. continue;
  51348. }
  51349. foundBone = false;
  51350. for (var k = 0; k < children.length; k++) {
  51351. if (children[k] === id) {
  51352. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  51353. foundBone = true;
  51354. break;
  51355. }
  51356. }
  51357. if (foundBone) {
  51358. break;
  51359. }
  51360. }
  51361. // Create bone
  51362. var mat = configureBoneTransformation(node);
  51363. if (!parentBone && nodesToRoot.length > 0) {
  51364. parentBone = getNodeToRoot(nodesToRoot, id);
  51365. if (parentBone) {
  51366. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  51367. nodesToRootToAdd.push(parentBone);
  51368. }
  51369. }
  51370. }
  51371. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  51372. bone.id = id;
  51373. }
  51374. // Polish
  51375. var bones = newSkeleton.bones;
  51376. newSkeleton.bones = [];
  51377. for (var i = 0; i < skins.jointNames.length; i++) {
  51378. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  51379. if (!jointNode) {
  51380. continue;
  51381. }
  51382. for (var j = 0; j < bones.length; j++) {
  51383. if (bones[j].id === jointNode.id) {
  51384. newSkeleton.bones.push(bones[j]);
  51385. break;
  51386. }
  51387. }
  51388. }
  51389. newSkeleton.prepare();
  51390. // Finish
  51391. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  51392. newSkeleton.bones.push(nodesToRootToAdd[i]);
  51393. }
  51394. return newSkeleton;
  51395. };
  51396. /**
  51397. * Imports a mesh and its geometries
  51398. */
  51399. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  51400. if (!newMesh) {
  51401. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  51402. newMesh.id = id;
  51403. }
  51404. if (!node.babylonNode) {
  51405. return newMesh;
  51406. }
  51407. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  51408. if (!newMesh.material) {
  51409. newMesh.material = multiMat;
  51410. }
  51411. var vertexData = new BABYLON.VertexData();
  51412. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  51413. var verticesStarts = [];
  51414. var verticesCounts = [];
  51415. var indexStarts = [];
  51416. var indexCounts = [];
  51417. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  51418. var meshID = meshes[meshIndex];
  51419. var mesh = gltfRuntime.meshes[meshID];
  51420. if (!mesh) {
  51421. continue;
  51422. }
  51423. // Positions, normals and UVs
  51424. for (var i = 0; i < mesh.primitives.length; i++) {
  51425. // Temporary vertex data
  51426. var tempVertexData = new BABYLON.VertexData();
  51427. var primitive = mesh.primitives[i];
  51428. if (primitive.mode !== 4) {
  51429. // continue;
  51430. }
  51431. var attributes = primitive.attributes;
  51432. var accessor = null;
  51433. var buffer = null;
  51434. // Set positions, normal and uvs
  51435. for (var semantic in attributes) {
  51436. // Link accessor and buffer view
  51437. accessor = gltfRuntime.accessors[attributes[semantic]];
  51438. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  51439. if (semantic === "NORMAL") {
  51440. tempVertexData.normals = new Float32Array(buffer.length);
  51441. tempVertexData.normals.set(buffer);
  51442. }
  51443. else if (semantic === "POSITION") {
  51444. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  51445. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  51446. for (var j = 0; j < buffer.length; j += 4) {
  51447. tempVertexData.positions[j] = buffer[j];
  51448. tempVertexData.positions[j + 1] = buffer[j + 1];
  51449. tempVertexData.positions[j + 2] = buffer[j + 2];
  51450. }
  51451. }
  51452. else {
  51453. tempVertexData.positions = new Float32Array(buffer.length);
  51454. tempVertexData.positions.set(buffer);
  51455. }
  51456. verticesCounts.push(tempVertexData.positions.length);
  51457. }
  51458. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  51459. var channel = Number(semantic.split("_")[1]);
  51460. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  51461. var uvs = new Float32Array(buffer.length);
  51462. uvs.set(buffer);
  51463. normalizeUVs(uvs);
  51464. tempVertexData.set(uvs, uvKind);
  51465. }
  51466. else if (semantic === "JOINT") {
  51467. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  51468. tempVertexData.matricesIndices.set(buffer);
  51469. }
  51470. else if (semantic === "WEIGHT") {
  51471. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  51472. tempVertexData.matricesWeights.set(buffer);
  51473. }
  51474. else if (semantic === "COLOR") {
  51475. tempVertexData.colors = new Float32Array(buffer.length);
  51476. tempVertexData.colors.set(buffer);
  51477. }
  51478. }
  51479. // Indices
  51480. accessor = gltfRuntime.accessors[primitive.indices];
  51481. if (accessor) {
  51482. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  51483. tempVertexData.indices = new Int32Array(buffer.length);
  51484. tempVertexData.indices.set(buffer);
  51485. indexCounts.push(tempVertexData.indices.length);
  51486. }
  51487. else {
  51488. // Set indices on the fly
  51489. var indices = [];
  51490. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  51491. indices.push(j);
  51492. }
  51493. tempVertexData.indices = new Int32Array(indices);
  51494. indexCounts.push(tempVertexData.indices.length);
  51495. }
  51496. vertexData.merge(tempVertexData);
  51497. tempVertexData = undefined;
  51498. // Sub material
  51499. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  51500. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  51501. // Update vertices start and index start
  51502. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  51503. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  51504. }
  51505. }
  51506. // Apply geometry
  51507. geometry.setAllVerticesData(vertexData, false);
  51508. newMesh.computeWorldMatrix(true);
  51509. // Apply submeshes
  51510. newMesh.subMeshes = [];
  51511. var index = 0;
  51512. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  51513. var meshID = meshes[meshIndex];
  51514. var mesh = gltfRuntime.meshes[meshID];
  51515. if (!mesh) {
  51516. continue;
  51517. }
  51518. for (var i = 0; i < mesh.primitives.length; i++) {
  51519. if (mesh.primitives[i].mode !== 4) {
  51520. //continue;
  51521. }
  51522. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  51523. index++;
  51524. }
  51525. }
  51526. // Finish
  51527. return newMesh;
  51528. };
  51529. /**
  51530. * Configure node transformation from position, rotation and scaling
  51531. */
  51532. var configureNode = function (newNode, position, rotation, scaling) {
  51533. if (newNode.position) {
  51534. newNode.position = position;
  51535. }
  51536. if (newNode.rotationQuaternion || newNode.rotation) {
  51537. newNode.rotationQuaternion = rotation;
  51538. }
  51539. if (newNode.scaling) {
  51540. newNode.scaling = scaling;
  51541. }
  51542. };
  51543. /**
  51544. * Configures node from transformation matrix
  51545. */
  51546. var configureNodeFromMatrix = function (newNode, node, parent) {
  51547. if (node.matrix) {
  51548. var position = new BABYLON.Vector3(0, 0, 0);
  51549. var rotation = new BABYLON.Quaternion();
  51550. var scaling = new BABYLON.Vector3(0, 0, 0);
  51551. var mat = BABYLON.Matrix.FromArray(node.matrix);
  51552. mat.decompose(scaling, rotation, position);
  51553. configureNode(newNode, position, rotation, scaling);
  51554. }
  51555. else {
  51556. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  51557. }
  51558. newNode.computeWorldMatrix(true);
  51559. };
  51560. /**
  51561. * Imports a node
  51562. */
  51563. var importNode = function (gltfRuntime, node, id, parent) {
  51564. var lastNode = null;
  51565. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  51566. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  51567. return null;
  51568. }
  51569. }
  51570. // Meshes
  51571. if (node.skin) {
  51572. if (node.meshes) {
  51573. var skin = gltfRuntime.skins[node.skin];
  51574. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  51575. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  51576. if (newMesh.skeleton === null) {
  51577. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  51578. if (!skin.babylonSkeleton) {
  51579. skin.babylonSkeleton = newMesh.skeleton;
  51580. }
  51581. }
  51582. lastNode = newMesh;
  51583. }
  51584. }
  51585. else if (node.meshes) {
  51586. /**
  51587. * Improve meshes property
  51588. */
  51589. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  51590. lastNode = newMesh;
  51591. }
  51592. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  51593. var light = gltfRuntime.lights[node.light];
  51594. if (light) {
  51595. if (light.type === "ambient") {
  51596. var ambienLight = light[light.type];
  51597. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  51598. hemiLight.name = node.name;
  51599. if (ambienLight.color) {
  51600. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  51601. }
  51602. lastNode = hemiLight;
  51603. }
  51604. else if (light.type === "directional") {
  51605. var directionalLight = light[light.type];
  51606. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  51607. dirLight.name = node.name;
  51608. if (directionalLight.color) {
  51609. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  51610. }
  51611. lastNode = dirLight;
  51612. }
  51613. else if (light.type === "point") {
  51614. var pointLight = light[light.type];
  51615. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  51616. ptLight.name = node.name;
  51617. if (pointLight.color) {
  51618. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  51619. }
  51620. lastNode = ptLight;
  51621. }
  51622. else if (light.type === "spot") {
  51623. var spotLight = light[light.type];
  51624. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  51625. spLight.name = node.name;
  51626. if (spotLight.color) {
  51627. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  51628. }
  51629. if (spotLight.fallOfAngle) {
  51630. spLight.angle = spotLight.fallOfAngle;
  51631. }
  51632. if (spotLight.fallOffExponent) {
  51633. spLight.exponent = spotLight.fallOffExponent;
  51634. }
  51635. lastNode = spLight;
  51636. }
  51637. }
  51638. }
  51639. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  51640. var camera = gltfRuntime.cameras[node.camera];
  51641. if (camera) {
  51642. if (camera.type === "orthographic") {
  51643. var orthographicCamera = camera[camera.type];
  51644. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  51645. orthoCamera.name = node.name;
  51646. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  51647. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  51648. lastNode = orthoCamera;
  51649. }
  51650. else if (camera.type === "perspective") {
  51651. var perspectiveCamera = camera[camera.type];
  51652. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  51653. persCamera.name = node.name;
  51654. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  51655. if (!perspectiveCamera.aspectRatio) {
  51656. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  51657. }
  51658. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  51659. persCamera.maxZ = perspectiveCamera.zfar;
  51660. persCamera.minZ = perspectiveCamera.znear;
  51661. }
  51662. lastNode = persCamera;
  51663. }
  51664. }
  51665. }
  51666. // Empty node
  51667. if (!node.jointName) {
  51668. if (node.babylonNode) {
  51669. return node.babylonNode;
  51670. }
  51671. else if (lastNode === null) {
  51672. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  51673. node.babylonNode = dummy;
  51674. lastNode = dummy;
  51675. }
  51676. }
  51677. if (lastNode !== null) {
  51678. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  51679. configureNodeFromMatrix(lastNode, node, parent);
  51680. }
  51681. else {
  51682. var translation = node.translation || [0, 0, 0];
  51683. var rotation = node.rotation || [0, 0, 0, 1];
  51684. var scale = node.scale || [1, 1, 1];
  51685. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  51686. }
  51687. lastNode.updateCache(true);
  51688. node.babylonNode = lastNode;
  51689. }
  51690. return lastNode;
  51691. };
  51692. /**
  51693. * Traverses nodes and creates them
  51694. */
  51695. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  51696. var node = gltfRuntime.nodes[id];
  51697. var newNode = null;
  51698. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  51699. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  51700. meshIncluded = true;
  51701. }
  51702. else {
  51703. meshIncluded = false;
  51704. }
  51705. }
  51706. else {
  51707. meshIncluded = true;
  51708. }
  51709. if (!node.jointName && meshIncluded) {
  51710. newNode = importNode(gltfRuntime, node, id, parent);
  51711. if (newNode !== null) {
  51712. newNode.id = id;
  51713. newNode.parent = parent;
  51714. }
  51715. }
  51716. if (node.children) {
  51717. for (var i = 0; i < node.children.length; i++) {
  51718. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  51719. }
  51720. }
  51721. };
  51722. /**
  51723. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  51724. */
  51725. var postLoad = function (gltfRuntime) {
  51726. // Nodes
  51727. var currentScene = gltfRuntime.currentScene;
  51728. if (currentScene) {
  51729. for (var i = 0; i < currentScene.nodes.length; i++) {
  51730. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  51731. }
  51732. }
  51733. else {
  51734. for (var thing in gltfRuntime.scenes) {
  51735. currentScene = gltfRuntime.scenes[thing];
  51736. for (var i = 0; i < currentScene.nodes.length; i++) {
  51737. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  51738. }
  51739. }
  51740. }
  51741. // Set animations
  51742. loadAnimations(gltfRuntime);
  51743. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  51744. var skeleton = gltfRuntime.scene.skeletons[i];
  51745. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  51746. }
  51747. };
  51748. /**
  51749. * onBind shaderrs callback to set uniforms and matrices
  51750. */
  51751. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  51752. var materialValues = material.values || technique.parameters;
  51753. for (var unif in unTreatedUniforms) {
  51754. var uniform = unTreatedUniforms[unif];
  51755. var type = uniform.type;
  51756. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  51757. if (uniform.semantic && !uniform.source && !uniform.node) {
  51758. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  51759. }
  51760. else if (uniform.semantic && (uniform.source || uniform.node)) {
  51761. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  51762. if (source === null) {
  51763. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  51764. }
  51765. if (source === null) {
  51766. continue;
  51767. }
  51768. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  51769. }
  51770. }
  51771. else {
  51772. var value = materialValues[technique.uniforms[unif]];
  51773. if (!value) {
  51774. continue;
  51775. }
  51776. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  51777. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  51778. if (texture === null || texture === undefined) {
  51779. continue;
  51780. }
  51781. shaderMaterial.getEffect().setTexture(unif, texture);
  51782. }
  51783. else {
  51784. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  51785. }
  51786. }
  51787. }
  51788. onSuccess(shaderMaterial);
  51789. };
  51790. /**
  51791. * Prepare uniforms to send the only one time
  51792. * Loads the appropriate textures
  51793. */
  51794. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  51795. var materialValues = material.values || technique.parameters;
  51796. var techniqueUniforms = technique.uniforms;
  51797. /**
  51798. * Prepare values here (not matrices)
  51799. */
  51800. for (var unif in unTreatedUniforms) {
  51801. var uniform = unTreatedUniforms[unif];
  51802. var type = uniform.type;
  51803. var value = materialValues[techniqueUniforms[unif]];
  51804. if (value === undefined) {
  51805. // In case the value is the same for all materials
  51806. value = uniform.value;
  51807. }
  51808. if (!value) {
  51809. continue;
  51810. }
  51811. var onLoadTexture = function (uniformName) {
  51812. return function (texture) {
  51813. if (uniform.value) {
  51814. // Static uniform
  51815. shaderMaterial.setTexture(uniformName, texture);
  51816. delete unTreatedUniforms[uniformName];
  51817. }
  51818. };
  51819. };
  51820. // Texture (sampler2D)
  51821. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  51822. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  51823. }
  51824. else {
  51825. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  51826. // Static uniform
  51827. delete unTreatedUniforms[unif];
  51828. }
  51829. }
  51830. }
  51831. };
  51832. /**
  51833. * Shader compilation failed
  51834. */
  51835. var onShaderCompileError = function (program, shaderMaterial, onError) {
  51836. return function (effect, error) {
  51837. shaderMaterial.dispose(true);
  51838. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  51839. };
  51840. };
  51841. /**
  51842. * Shader compilation success
  51843. */
  51844. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  51845. return function (_) {
  51846. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  51847. shaderMaterial.onBind = function (mesh) {
  51848. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  51849. };
  51850. };
  51851. };
  51852. /**
  51853. * Returns the appropriate uniform if already handled by babylon
  51854. */
  51855. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  51856. for (var unif in technique.uniforms) {
  51857. var uniform = technique.uniforms[unif];
  51858. var uniformParameter = technique.parameters[uniform];
  51859. if (tokenizer.currentIdentifier === unif) {
  51860. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  51861. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  51862. if (transformIndex !== -1) {
  51863. delete unTreatedUniforms[unif];
  51864. return babylonTransforms[transformIndex];
  51865. }
  51866. }
  51867. }
  51868. }
  51869. return tokenizer.currentIdentifier;
  51870. };
  51871. /**
  51872. * All shaders loaded. Create materials one by one
  51873. */
  51874. var importMaterials = function (gltfRuntime) {
  51875. // Create materials
  51876. for (var mat in gltfRuntime.materials) {
  51877. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  51878. }
  51879. };
  51880. /**
  51881. * Implementation of the base glTF spec
  51882. */
  51883. var GLTFLoaderBase = (function () {
  51884. function GLTFLoaderBase() {
  51885. }
  51886. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  51887. var gltfRuntime = {
  51888. extensions: {},
  51889. accessors: {},
  51890. buffers: {},
  51891. bufferViews: {},
  51892. meshes: {},
  51893. lights: {},
  51894. cameras: {},
  51895. nodes: {},
  51896. images: {},
  51897. textures: {},
  51898. shaders: {},
  51899. programs: {},
  51900. samplers: {},
  51901. techniques: {},
  51902. materials: {},
  51903. animations: {},
  51904. skins: {},
  51905. extensionsUsed: [],
  51906. scenes: {},
  51907. buffersCount: 0,
  51908. shaderscount: 0,
  51909. scene: scene,
  51910. rootUrl: rootUrl,
  51911. loadedBufferCount: 0,
  51912. loadedBufferViews: {},
  51913. loadedShaderCount: 0,
  51914. importOnlyMeshes: false,
  51915. dummyNodes: []
  51916. };
  51917. // Parse
  51918. if (parsedData.extensions) {
  51919. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  51920. }
  51921. if (parsedData.extensionsUsed) {
  51922. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  51923. }
  51924. if (parsedData.buffers) {
  51925. parseBuffers(parsedData.buffers, gltfRuntime);
  51926. }
  51927. if (parsedData.bufferViews) {
  51928. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  51929. }
  51930. if (parsedData.accessors) {
  51931. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  51932. }
  51933. if (parsedData.meshes) {
  51934. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  51935. }
  51936. if (parsedData.lights) {
  51937. parseObject(parsedData.lights, "lights", gltfRuntime);
  51938. }
  51939. if (parsedData.cameras) {
  51940. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  51941. }
  51942. if (parsedData.nodes) {
  51943. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  51944. }
  51945. if (parsedData.images) {
  51946. parseObject(parsedData.images, "images", gltfRuntime);
  51947. }
  51948. if (parsedData.textures) {
  51949. parseObject(parsedData.textures, "textures", gltfRuntime);
  51950. }
  51951. if (parsedData.shaders) {
  51952. parseShaders(parsedData.shaders, gltfRuntime);
  51953. }
  51954. if (parsedData.programs) {
  51955. parseObject(parsedData.programs, "programs", gltfRuntime);
  51956. }
  51957. if (parsedData.samplers) {
  51958. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  51959. }
  51960. if (parsedData.techniques) {
  51961. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  51962. }
  51963. if (parsedData.materials) {
  51964. parseObject(parsedData.materials, "materials", gltfRuntime);
  51965. }
  51966. if (parsedData.animations) {
  51967. parseObject(parsedData.animations, "animations", gltfRuntime);
  51968. }
  51969. if (parsedData.skins) {
  51970. parseObject(parsedData.skins, "skins", gltfRuntime);
  51971. }
  51972. if (parsedData.scenes) {
  51973. gltfRuntime.scenes = parsedData.scenes;
  51974. }
  51975. if (parsedData.scene && parsedData.scenes) {
  51976. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  51977. }
  51978. return gltfRuntime;
  51979. };
  51980. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  51981. var buffer = gltfRuntime.buffers[id];
  51982. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  51983. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  51984. }
  51985. else {
  51986. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  51987. onError(request.status + " " + request.statusText);
  51988. });
  51989. }
  51990. };
  51991. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  51992. var texture = gltfRuntime.textures[id];
  51993. if (!texture || !texture.source) {
  51994. onError(null);
  51995. return;
  51996. }
  51997. if (texture.babylonTexture) {
  51998. onSuccess(null);
  51999. return;
  52000. }
  52001. var source = gltfRuntime.images[texture.source];
  52002. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  52003. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  52004. }
  52005. else {
  52006. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  52007. onError(request.status + " " + request.statusText);
  52008. });
  52009. }
  52010. };
  52011. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  52012. var texture = gltfRuntime.textures[id];
  52013. if (texture.babylonTexture) {
  52014. onSuccess(texture.babylonTexture);
  52015. return;
  52016. }
  52017. var sampler = gltfRuntime.samplers[texture.sampler];
  52018. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  52019. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  52020. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  52021. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  52022. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  52023. var blob = new Blob([buffer]);
  52024. var blobURL = URL.createObjectURL(blob);
  52025. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  52026. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  52027. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  52028. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  52029. newTexture.name = id;
  52030. texture.babylonTexture = newTexture;
  52031. onSuccess(newTexture);
  52032. };
  52033. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  52034. var shader = gltfRuntime.shaders[id];
  52035. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  52036. var shaderString = atob(shader.uri.split(",")[1]);
  52037. onSuccess(shaderString);
  52038. }
  52039. else {
  52040. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  52041. onError(request.status + " " + request.statusText);
  52042. });
  52043. }
  52044. };
  52045. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  52046. var material = gltfRuntime.materials[id];
  52047. var technique = gltfRuntime.techniques[material.technique];
  52048. if (!technique) {
  52049. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  52050. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  52051. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  52052. onSuccess(defaultMaterial);
  52053. return;
  52054. }
  52055. var program = gltfRuntime.programs[technique.program];
  52056. var states = technique.states;
  52057. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  52058. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  52059. var newVertexShader = "";
  52060. var newPixelShader = "";
  52061. var vertexTokenizer = new Tokenizer(vertexShader);
  52062. var pixelTokenizer = new Tokenizer(pixelShader);
  52063. var unTreatedUniforms = {};
  52064. var uniforms = [];
  52065. var attributes = [];
  52066. var samplers = [];
  52067. // Fill uniform, sampler2D and attributes
  52068. for (var unif in technique.uniforms) {
  52069. var uniform = technique.uniforms[unif];
  52070. var uniformParameter = technique.parameters[uniform];
  52071. unTreatedUniforms[unif] = uniformParameter;
  52072. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  52073. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  52074. if (transformIndex !== -1) {
  52075. uniforms.push(babylonTransforms[transformIndex]);
  52076. delete unTreatedUniforms[unif];
  52077. }
  52078. else {
  52079. uniforms.push(unif);
  52080. }
  52081. }
  52082. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  52083. samplers.push(unif);
  52084. }
  52085. else {
  52086. uniforms.push(unif);
  52087. }
  52088. }
  52089. for (var attr in technique.attributes) {
  52090. var attribute = technique.attributes[attr];
  52091. var attributeParameter = technique.parameters[attribute];
  52092. if (attributeParameter.semantic) {
  52093. attributes.push(getAttribute(attributeParameter));
  52094. }
  52095. }
  52096. // Configure vertex shader
  52097. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  52098. var tokenType = vertexTokenizer.currentToken;
  52099. if (tokenType !== ETokenType.IDENTIFIER) {
  52100. newVertexShader += vertexTokenizer.currentString;
  52101. continue;
  52102. }
  52103. var foundAttribute = false;
  52104. for (var attr in technique.attributes) {
  52105. var attribute = technique.attributes[attr];
  52106. var attributeParameter = technique.parameters[attribute];
  52107. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  52108. newVertexShader += getAttribute(attributeParameter);
  52109. foundAttribute = true;
  52110. break;
  52111. }
  52112. }
  52113. if (foundAttribute) {
  52114. continue;
  52115. }
  52116. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  52117. }
  52118. // Configure pixel shader
  52119. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  52120. var tokenType = pixelTokenizer.currentToken;
  52121. if (tokenType !== ETokenType.IDENTIFIER) {
  52122. newPixelShader += pixelTokenizer.currentString;
  52123. continue;
  52124. }
  52125. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  52126. }
  52127. // Create shader material
  52128. var shaderPath = {
  52129. vertex: program.vertexShader + id,
  52130. fragment: program.fragmentShader + id
  52131. };
  52132. var options = {
  52133. attributes: attributes,
  52134. uniforms: uniforms,
  52135. samplers: samplers,
  52136. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  52137. };
  52138. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  52139. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  52140. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  52141. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  52142. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  52143. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  52144. if (states && states.functions) {
  52145. var functions = states.functions;
  52146. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  52147. shaderMaterial.backFaceCulling = false;
  52148. }
  52149. var blendFunc = functions.blendFuncSeparate;
  52150. if (blendFunc) {
  52151. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52152. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  52153. }
  52154. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52155. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  52156. }
  52157. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52158. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  52159. }
  52160. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52161. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  52162. }
  52163. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52164. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  52165. }
  52166. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52167. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  52168. }
  52169. }
  52170. }
  52171. };
  52172. return GLTFLoaderBase;
  52173. }());
  52174. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  52175. /**
  52176. * glTF V1 Loader
  52177. */
  52178. var GLTFLoader = (function () {
  52179. function GLTFLoader() {
  52180. }
  52181. GLTFLoader.RegisterExtension = function (extension) {
  52182. if (GLTFLoader.Extensions[extension.name]) {
  52183. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  52184. return;
  52185. }
  52186. GLTFLoader.Extensions[extension.name] = extension;
  52187. };
  52188. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  52189. var _this = this;
  52190. scene.useRightHandedSystem = true;
  52191. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  52192. gltfRuntime.importOnlyMeshes = true;
  52193. if (meshesNames === "") {
  52194. gltfRuntime.importMeshesNames = [];
  52195. }
  52196. else if (typeof meshesNames === "string") {
  52197. gltfRuntime.importMeshesNames = [meshesNames];
  52198. }
  52199. else if (meshesNames && !(meshesNames instanceof Array)) {
  52200. gltfRuntime.importMeshesNames = [meshesNames];
  52201. }
  52202. else {
  52203. gltfRuntime.importMeshesNames = [];
  52204. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  52205. }
  52206. // Create nodes
  52207. _this._createNodes(gltfRuntime);
  52208. var meshes = [];
  52209. var skeletons = [];
  52210. // Fill arrays of meshes and skeletons
  52211. for (var nde in gltfRuntime.nodes) {
  52212. var node = gltfRuntime.nodes[nde];
  52213. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  52214. meshes.push(node.babylonNode);
  52215. }
  52216. }
  52217. for (var skl in gltfRuntime.skins) {
  52218. var skin = gltfRuntime.skins[skl];
  52219. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  52220. skeletons.push(skin.babylonSkeleton);
  52221. }
  52222. }
  52223. // Load buffers, shaders, materials, etc.
  52224. _this._loadBuffersAsync(gltfRuntime, function () {
  52225. _this._loadShadersAsync(gltfRuntime, function () {
  52226. importMaterials(gltfRuntime);
  52227. postLoad(gltfRuntime);
  52228. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  52229. onSuccess(meshes, null, skeletons);
  52230. }
  52231. });
  52232. }, onProgress);
  52233. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  52234. onSuccess(meshes, null, skeletons);
  52235. }
  52236. }, onError);
  52237. return true;
  52238. };
  52239. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  52240. var _this = this;
  52241. scene.useRightHandedSystem = true;
  52242. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  52243. // Load runtime extensios
  52244. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  52245. // Create nodes
  52246. _this._createNodes(gltfRuntime);
  52247. // Load buffers, shaders, materials, etc.
  52248. _this._loadBuffersAsync(gltfRuntime, function () {
  52249. _this._loadShadersAsync(gltfRuntime, function () {
  52250. importMaterials(gltfRuntime);
  52251. postLoad(gltfRuntime);
  52252. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  52253. onSuccess();
  52254. }
  52255. });
  52256. });
  52257. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  52258. onSuccess();
  52259. }
  52260. }, onError);
  52261. }, onError);
  52262. };
  52263. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  52264. var hasShaders = false;
  52265. var processShader = function (sha, shader) {
  52266. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  52267. gltfRuntime.loadedShaderCount++;
  52268. if (shaderString) {
  52269. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  52270. }
  52271. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  52272. onload();
  52273. }
  52274. }, function () {
  52275. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  52276. });
  52277. };
  52278. for (var sha in gltfRuntime.shaders) {
  52279. hasShaders = true;
  52280. var shader = gltfRuntime.shaders[sha];
  52281. if (shader) {
  52282. processShader.bind(this, sha, shader)();
  52283. }
  52284. else {
  52285. BABYLON.Tools.Error("No shader named: " + sha);
  52286. }
  52287. }
  52288. if (!hasShaders) {
  52289. onload();
  52290. }
  52291. };
  52292. ;
  52293. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  52294. var hasBuffers = false;
  52295. var processBuffer = function (buf, buffer) {
  52296. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  52297. gltfRuntime.loadedBufferCount++;
  52298. if (bufferView) {
  52299. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  52300. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  52301. }
  52302. gltfRuntime.loadedBufferViews[buf] = bufferView;
  52303. }
  52304. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  52305. onLoad();
  52306. }
  52307. }, function () {
  52308. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  52309. });
  52310. };
  52311. for (var buf in gltfRuntime.buffers) {
  52312. hasBuffers = true;
  52313. var buffer = gltfRuntime.buffers[buf];
  52314. if (buffer) {
  52315. processBuffer.bind(this, buf, buffer)();
  52316. }
  52317. else {
  52318. BABYLON.Tools.Error("No buffer named: " + buf);
  52319. }
  52320. }
  52321. if (!hasBuffers) {
  52322. onLoad();
  52323. }
  52324. };
  52325. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  52326. var currentScene = gltfRuntime.currentScene;
  52327. if (currentScene) {
  52328. // Only one scene even if multiple scenes are defined
  52329. for (var i = 0; i < currentScene.nodes.length; i++) {
  52330. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52331. }
  52332. }
  52333. else {
  52334. // Load all scenes
  52335. for (var thing in gltfRuntime.scenes) {
  52336. currentScene = gltfRuntime.scenes[thing];
  52337. for (var i = 0; i < currentScene.nodes.length; i++) {
  52338. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52339. }
  52340. }
  52341. }
  52342. };
  52343. GLTFLoader.Extensions = {};
  52344. return GLTFLoader;
  52345. }());
  52346. GLTF1.GLTFLoader = GLTFLoader;
  52347. ;
  52348. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  52349. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  52350. })(BABYLON || (BABYLON = {}));
  52351. //# sourceMappingURL=babylon.glTFLoader.js.map
  52352. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  52353. var BABYLON;
  52354. (function (BABYLON) {
  52355. var GLTF1;
  52356. (function (GLTF1) {
  52357. /**
  52358. * Utils functions for GLTF
  52359. */
  52360. var GLTFUtils = (function () {
  52361. function GLTFUtils() {
  52362. }
  52363. /**
  52364. * Sets the given "parameter" matrix
  52365. * @param scene: the {BABYLON.Scene} object
  52366. * @param source: the source node where to pick the matrix
  52367. * @param parameter: the GLTF technique parameter
  52368. * @param uniformName: the name of the shader's uniform
  52369. * @param shaderMaterial: the shader material
  52370. */
  52371. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  52372. var mat = null;
  52373. if (parameter.semantic === "MODEL") {
  52374. mat = source.getWorldMatrix();
  52375. }
  52376. else if (parameter.semantic === "PROJECTION") {
  52377. mat = scene.getProjectionMatrix();
  52378. }
  52379. else if (parameter.semantic === "VIEW") {
  52380. mat = scene.getViewMatrix();
  52381. }
  52382. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  52383. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  52384. }
  52385. else if (parameter.semantic === "MODELVIEW") {
  52386. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  52387. }
  52388. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  52389. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  52390. }
  52391. else if (parameter.semantic === "MODELINVERSE") {
  52392. mat = source.getWorldMatrix().invert();
  52393. }
  52394. else if (parameter.semantic === "VIEWINVERSE") {
  52395. mat = scene.getViewMatrix().invert();
  52396. }
  52397. else if (parameter.semantic === "PROJECTIONINVERSE") {
  52398. mat = scene.getProjectionMatrix().invert();
  52399. }
  52400. else if (parameter.semantic === "MODELVIEWINVERSE") {
  52401. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  52402. }
  52403. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  52404. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  52405. }
  52406. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  52407. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  52408. }
  52409. else {
  52410. debugger;
  52411. }
  52412. switch (parameter.type) {
  52413. case GLTF1.EParameterType.FLOAT_MAT2:
  52414. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  52415. break;
  52416. case GLTF1.EParameterType.FLOAT_MAT3:
  52417. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  52418. break;
  52419. case GLTF1.EParameterType.FLOAT_MAT4:
  52420. shaderMaterial.setMatrix(uniformName, mat);
  52421. break;
  52422. default: break;
  52423. }
  52424. };
  52425. /**
  52426. * Sets the given "parameter" matrix
  52427. * @param shaderMaterial: the shader material
  52428. * @param uniform: the name of the shader's uniform
  52429. * @param value: the value of the uniform
  52430. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  52431. */
  52432. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  52433. switch (type) {
  52434. case GLTF1.EParameterType.FLOAT:
  52435. shaderMaterial.setFloat(uniform, value);
  52436. return true;
  52437. case GLTF1.EParameterType.FLOAT_VEC2:
  52438. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  52439. return true;
  52440. case GLTF1.EParameterType.FLOAT_VEC3:
  52441. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  52442. return true;
  52443. case GLTF1.EParameterType.FLOAT_VEC4:
  52444. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  52445. return true;
  52446. default: return false;
  52447. }
  52448. };
  52449. /**
  52450. * If the uri is a base64 string
  52451. * @param uri: the uri to test
  52452. */
  52453. GLTFUtils.IsBase64 = function (uri) {
  52454. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  52455. };
  52456. /**
  52457. * Decode the base64 uri
  52458. * @param uri: the uri to decode
  52459. */
  52460. GLTFUtils.DecodeBase64 = function (uri) {
  52461. var decodedString = atob(uri.split(",")[1]);
  52462. var bufferLength = decodedString.length;
  52463. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  52464. for (var i = 0; i < bufferLength; i++) {
  52465. bufferView[i] = decodedString.charCodeAt(i);
  52466. }
  52467. return bufferView.buffer;
  52468. };
  52469. /**
  52470. * Returns the wrap mode of the texture
  52471. * @param mode: the mode value
  52472. */
  52473. GLTFUtils.GetWrapMode = function (mode) {
  52474. switch (mode) {
  52475. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  52476. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  52477. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  52478. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  52479. }
  52480. };
  52481. /**
  52482. * Returns the byte stride giving an accessor
  52483. * @param accessor: the GLTF accessor objet
  52484. */
  52485. GLTFUtils.GetByteStrideFromType = function (accessor) {
  52486. // Needs this function since "byteStride" isn't requiered in glTF format
  52487. var type = accessor.type;
  52488. switch (type) {
  52489. case "VEC2": return 2;
  52490. case "VEC3": return 3;
  52491. case "VEC4": return 4;
  52492. case "MAT2": return 4;
  52493. case "MAT3": return 9;
  52494. case "MAT4": return 16;
  52495. default: return 1;
  52496. }
  52497. };
  52498. /**
  52499. * Returns the texture filter mode giving a mode value
  52500. * @param mode: the filter mode value
  52501. */
  52502. GLTFUtils.GetTextureFilterMode = function (mode) {
  52503. switch (mode) {
  52504. case GLTF1.ETextureFilterType.LINEAR:
  52505. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  52506. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  52507. case GLTF1.ETextureFilterType.NEAREST:
  52508. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  52509. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  52510. }
  52511. };
  52512. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  52513. var byteOffset = bufferView.byteOffset + byteOffset;
  52514. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  52515. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  52516. throw new Error("Buffer access is out of range");
  52517. }
  52518. var buffer = loadedBufferView.buffer;
  52519. byteOffset += loadedBufferView.byteOffset;
  52520. switch (componentType) {
  52521. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  52522. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  52523. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  52524. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  52525. default: return new Float32Array(buffer, byteOffset, byteLength);
  52526. }
  52527. };
  52528. /**
  52529. * Returns a buffer from its accessor
  52530. * @param gltfRuntime: the GLTF runtime
  52531. * @param accessor: the GLTF accessor
  52532. */
  52533. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  52534. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  52535. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  52536. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  52537. };
  52538. /**
  52539. * Decodes a buffer view into a string
  52540. * @param view: the buffer view
  52541. */
  52542. GLTFUtils.DecodeBufferToText = function (view) {
  52543. var result = "";
  52544. var length = view.byteLength;
  52545. for (var i = 0; i < length; ++i) {
  52546. result += String.fromCharCode(view[i]);
  52547. }
  52548. return result;
  52549. };
  52550. /**
  52551. * Returns the default material of gltf. Related to
  52552. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  52553. * @param scene: the Babylon.js scene
  52554. */
  52555. GLTFUtils.GetDefaultMaterial = function (scene) {
  52556. if (!GLTFUtils._DefaultMaterial) {
  52557. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  52558. "precision highp float;",
  52559. "",
  52560. "uniform mat4 worldView;",
  52561. "uniform mat4 projection;",
  52562. "",
  52563. "attribute vec3 position;",
  52564. "",
  52565. "void main(void)",
  52566. "{",
  52567. " gl_Position = projection * worldView * vec4(position, 1.0);",
  52568. "}"
  52569. ].join("\n");
  52570. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  52571. "precision highp float;",
  52572. "",
  52573. "uniform vec4 u_emission;",
  52574. "",
  52575. "void main(void)",
  52576. "{",
  52577. " gl_FragColor = u_emission;",
  52578. "}"
  52579. ].join("\n");
  52580. var shaderPath = {
  52581. vertex: "GLTFDefaultMaterial",
  52582. fragment: "GLTFDefaultMaterial"
  52583. };
  52584. var options = {
  52585. attributes: ["position"],
  52586. uniforms: ["worldView", "projection", "u_emission"],
  52587. samplers: [],
  52588. needAlphaBlending: false
  52589. };
  52590. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  52591. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  52592. }
  52593. return GLTFUtils._DefaultMaterial;
  52594. };
  52595. // The GLTF default material
  52596. GLTFUtils._DefaultMaterial = null;
  52597. return GLTFUtils;
  52598. }());
  52599. GLTF1.GLTFUtils = GLTFUtils;
  52600. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  52601. })(BABYLON || (BABYLON = {}));
  52602. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  52603. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  52604. var BABYLON;
  52605. (function (BABYLON) {
  52606. var GLTF1;
  52607. (function (GLTF1) {
  52608. var GLTFLoaderExtension = (function () {
  52609. function GLTFLoaderExtension(name) {
  52610. this._name = name;
  52611. }
  52612. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  52613. get: function () {
  52614. return this._name;
  52615. },
  52616. enumerable: true,
  52617. configurable: true
  52618. });
  52619. /**
  52620. * Defines an override for loading the runtime
  52621. * Return true to stop further extensions from loading the runtime
  52622. */
  52623. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  52624. return false;
  52625. };
  52626. /**
  52627. * Defines an onverride for creating gltf runtime
  52628. * Return true to stop further extensions from creating the runtime
  52629. */
  52630. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  52631. return false;
  52632. };
  52633. /**
  52634. * Defines an override for loading buffers
  52635. * Return true to stop further extensions from loading this buffer
  52636. */
  52637. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  52638. return false;
  52639. };
  52640. /**
  52641. * Defines an override for loading texture buffers
  52642. * Return true to stop further extensions from loading this texture data
  52643. */
  52644. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  52645. return false;
  52646. };
  52647. /**
  52648. * Defines an override for creating textures
  52649. * Return true to stop further extensions from loading this texture
  52650. */
  52651. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  52652. return false;
  52653. };
  52654. /**
  52655. * Defines an override for loading shader strings
  52656. * Return true to stop further extensions from loading this shader data
  52657. */
  52658. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  52659. return false;
  52660. };
  52661. /**
  52662. * Defines an override for loading materials
  52663. * Return true to stop further extensions from loading this material
  52664. */
  52665. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  52666. return false;
  52667. };
  52668. // ---------
  52669. // Utilities
  52670. // ---------
  52671. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  52672. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  52673. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  52674. }, function () {
  52675. setTimeout(function () {
  52676. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  52677. });
  52678. });
  52679. };
  52680. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  52681. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  52682. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  52683. }, function () {
  52684. setTimeout(function () {
  52685. onSuccess();
  52686. });
  52687. });
  52688. };
  52689. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  52690. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  52691. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  52692. }, function () {
  52693. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  52694. });
  52695. };
  52696. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  52697. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  52698. };
  52699. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  52700. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  52701. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  52702. }, function () {
  52703. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  52704. });
  52705. };
  52706. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  52707. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  52708. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  52709. }, function () {
  52710. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  52711. });
  52712. };
  52713. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  52714. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  52715. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  52716. }, function () {
  52717. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  52718. });
  52719. };
  52720. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  52721. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  52722. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  52723. }, function () {
  52724. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  52725. });
  52726. };
  52727. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  52728. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  52729. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  52730. if (func(loaderExtension)) {
  52731. return;
  52732. }
  52733. }
  52734. defaultFunc();
  52735. };
  52736. return GLTFLoaderExtension;
  52737. }());
  52738. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  52739. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  52740. })(BABYLON || (BABYLON = {}));
  52741. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  52742. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  52743. var BABYLON;
  52744. (function (BABYLON) {
  52745. var GLTF1;
  52746. (function (GLTF1) {
  52747. var BinaryExtensionBufferName = "binary_glTF";
  52748. var EContentFormat;
  52749. (function (EContentFormat) {
  52750. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  52751. })(EContentFormat || (EContentFormat = {}));
  52752. ;
  52753. ;
  52754. ;
  52755. var GLTFBinaryExtension = (function (_super) {
  52756. __extends(GLTFBinaryExtension, _super);
  52757. function GLTFBinaryExtension() {
  52758. return _super.call(this, "KHR_binary_glTF") || this;
  52759. }
  52760. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  52761. var extensionsUsed = data.json.extensionsUsed;
  52762. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  52763. return false;
  52764. }
  52765. this._bin = data.bin;
  52766. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  52767. return true;
  52768. };
  52769. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  52770. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  52771. return false;
  52772. }
  52773. if (id !== BinaryExtensionBufferName) {
  52774. return false;
  52775. }
  52776. onSuccess(this._bin);
  52777. return true;
  52778. };
  52779. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  52780. var texture = gltfRuntime.textures[id];
  52781. var source = gltfRuntime.images[texture.source];
  52782. if (!source.extensions || !(this.name in source.extensions)) {
  52783. return false;
  52784. }
  52785. var sourceExt = source.extensions[this.name];
  52786. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  52787. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  52788. onSuccess(buffer);
  52789. return true;
  52790. };
  52791. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  52792. var shader = gltfRuntime.shaders[id];
  52793. if (!shader.extensions || !(this.name in shader.extensions)) {
  52794. return false;
  52795. }
  52796. var binaryExtensionShader = shader.extensions[this.name];
  52797. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  52798. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  52799. setTimeout(function () {
  52800. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  52801. onSuccess(shaderString);
  52802. });
  52803. return true;
  52804. };
  52805. return GLTFBinaryExtension;
  52806. }(GLTF1.GLTFLoaderExtension));
  52807. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  52808. var BinaryReader = (function () {
  52809. function BinaryReader(arrayBuffer) {
  52810. this._arrayBuffer = arrayBuffer;
  52811. this._dataView = new DataView(arrayBuffer);
  52812. this._byteOffset = 0;
  52813. }
  52814. BinaryReader.prototype.getUint32 = function () {
  52815. var value = this._dataView.getUint32(this._byteOffset, true);
  52816. this._byteOffset += 4;
  52817. return value;
  52818. };
  52819. BinaryReader.prototype.getUint8Array = function (length) {
  52820. if (!length) {
  52821. length = this._arrayBuffer.byteLength - this._byteOffset;
  52822. }
  52823. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  52824. this._byteOffset += length;
  52825. return value;
  52826. };
  52827. return BinaryReader;
  52828. }());
  52829. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  52830. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  52831. })(BABYLON || (BABYLON = {}));
  52832. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  52833. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  52834. var BABYLON;
  52835. (function (BABYLON) {
  52836. var GLTF1;
  52837. (function (GLTF1) {
  52838. ;
  52839. ;
  52840. ;
  52841. var GLTFMaterialsCommonExtension = (function (_super) {
  52842. __extends(GLTFMaterialsCommonExtension, _super);
  52843. function GLTFMaterialsCommonExtension() {
  52844. return _super.call(this, "KHR_materials_common") || this;
  52845. }
  52846. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  52847. if (!gltfRuntime.extensions)
  52848. return false;
  52849. var extension = gltfRuntime.extensions[this.name];
  52850. if (!extension)
  52851. return false;
  52852. // Create lights
  52853. var lights = extension.lights;
  52854. if (lights) {
  52855. for (var thing in lights) {
  52856. var light = lights[thing];
  52857. switch (light.type) {
  52858. case "ambient":
  52859. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  52860. var ambient = light.ambient;
  52861. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  52862. break;
  52863. case "point":
  52864. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  52865. var point = light.point;
  52866. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  52867. break;
  52868. case "directional":
  52869. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  52870. var directional = light.directional;
  52871. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  52872. break;
  52873. case "spot":
  52874. var spot = light.spot;
  52875. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), light.spot.fallOffAngle || Math.PI, light.spot.fallOffExponent || 0.0, gltfRuntime.scene);
  52876. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  52877. break;
  52878. default:
  52879. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  52880. break;
  52881. }
  52882. }
  52883. }
  52884. return false;
  52885. };
  52886. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  52887. var material = gltfRuntime.materials[id];
  52888. if (!material || !material.extensions)
  52889. return false;
  52890. var extension = material.extensions[this.name];
  52891. if (!extension)
  52892. return false;
  52893. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  52894. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  52895. if (extension.technique === "CONSTANT") {
  52896. standardMaterial.disableLighting = true;
  52897. }
  52898. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  52899. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  52900. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  52901. // Ambient
  52902. if (typeof extension.values.ambient === "string") {
  52903. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  52904. }
  52905. else {
  52906. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  52907. }
  52908. // Diffuse
  52909. if (typeof extension.values.diffuse === "string") {
  52910. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  52911. }
  52912. else {
  52913. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  52914. }
  52915. // Emission
  52916. if (typeof extension.values.emission === "string") {
  52917. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  52918. }
  52919. else {
  52920. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  52921. }
  52922. // Specular
  52923. if (typeof extension.values.specular === "string") {
  52924. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  52925. }
  52926. else {
  52927. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  52928. }
  52929. return true;
  52930. };
  52931. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  52932. // Create buffer from texture url
  52933. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  52934. // Create texture from buffer
  52935. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  52936. }, onError);
  52937. };
  52938. return GLTFMaterialsCommonExtension;
  52939. }(GLTF1.GLTFLoaderExtension));
  52940. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  52941. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  52942. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  52943. })(BABYLON || (BABYLON = {}));
  52944. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  52945. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  52946. var BABYLON;
  52947. (function (BABYLON) {
  52948. var GLTF2;
  52949. (function (GLTF2) {
  52950. /**
  52951. * Enums
  52952. */
  52953. var EComponentType;
  52954. (function (EComponentType) {
  52955. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  52956. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  52957. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  52958. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  52959. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  52960. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  52961. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  52962. var EMeshPrimitiveMode;
  52963. (function (EMeshPrimitiveMode) {
  52964. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  52965. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  52966. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  52967. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  52968. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  52969. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  52970. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  52971. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  52972. var ETextureMagFilter;
  52973. (function (ETextureMagFilter) {
  52974. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  52975. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  52976. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  52977. var ETextureMinFilter;
  52978. (function (ETextureMinFilter) {
  52979. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  52980. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  52981. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  52982. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  52983. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  52984. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  52985. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  52986. var ETextureWrapMode;
  52987. (function (ETextureWrapMode) {
  52988. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  52989. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  52990. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  52991. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  52992. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  52993. })(BABYLON || (BABYLON = {}));
  52994. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  52995. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  52996. var BABYLON;
  52997. (function (BABYLON) {
  52998. var GLTF2;
  52999. (function (GLTF2) {
  53000. var GLTFLoader = (function () {
  53001. function GLTFLoader(parent) {
  53002. this._renderReady = false;
  53003. this._disposed = false;
  53004. this._objectURLs = new Array();
  53005. this._blockPendingTracking = false;
  53006. // Observable with boolean indicating success or error.
  53007. this._renderReadyObservable = new BABYLON.Observable();
  53008. // Count of pending work that needs to complete before the asset is rendered.
  53009. this._renderPendingCount = 0;
  53010. // Count of pending work that needs to complete before the loader is cleared.
  53011. this._loaderPendingCount = 0;
  53012. this._parent = parent;
  53013. }
  53014. GLTFLoader.RegisterExtension = function (extension) {
  53015. if (GLTFLoader.Extensions[extension.name]) {
  53016. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  53017. return;
  53018. }
  53019. GLTFLoader.Extensions[extension.name] = extension;
  53020. // Keep the order of registration so that extensions registered first are called first.
  53021. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  53022. };
  53023. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  53024. get: function () {
  53025. return this._gltf;
  53026. },
  53027. enumerable: true,
  53028. configurable: true
  53029. });
  53030. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  53031. get: function () {
  53032. return this._babylonScene;
  53033. },
  53034. enumerable: true,
  53035. configurable: true
  53036. });
  53037. GLTFLoader.prototype.executeWhenRenderReady = function (func) {
  53038. if (this._renderReady) {
  53039. func();
  53040. }
  53041. else {
  53042. this._renderReadyObservable.add(func);
  53043. }
  53044. };
  53045. GLTFLoader.prototype.dispose = function () {
  53046. if (this._disposed) {
  53047. return;
  53048. }
  53049. this._disposed = true;
  53050. // Revoke object urls created during load
  53051. this._objectURLs.forEach(function (url) { return URL.revokeObjectURL(url); });
  53052. this._objectURLs.length = 0;
  53053. this._gltf = undefined;
  53054. this._babylonScene = undefined;
  53055. this._rootUrl = undefined;
  53056. this._defaultMaterial = undefined;
  53057. this._successCallback = undefined;
  53058. this._errorCallback = undefined;
  53059. this._renderReady = false;
  53060. this._renderReadyObservable.clear();
  53061. this._renderPendingCount = 0;
  53062. this._loaderPendingCount = 0;
  53063. };
  53064. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53065. var _this = this;
  53066. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  53067. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  53068. }, onProgress, onError);
  53069. };
  53070. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  53071. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  53072. };
  53073. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53074. this._loadData(data);
  53075. this._babylonScene = scene;
  53076. this._rootUrl = rootUrl;
  53077. this._successCallback = onSuccess;
  53078. this._progressCallback = onProgress;
  53079. this._errorCallback = onError;
  53080. this.addPendingData(this);
  53081. this._loadScene(nodeNames);
  53082. this._loadAnimations();
  53083. this.removePendingData(this);
  53084. };
  53085. GLTFLoader.prototype._onError = function (message) {
  53086. this._errorCallback(message);
  53087. this.dispose();
  53088. };
  53089. GLTFLoader.prototype._onProgress = function (event) {
  53090. this._progressCallback(event);
  53091. };
  53092. GLTFLoader.prototype._onRenderReady = function () {
  53093. switch (this._parent.coordinateSystemMode) {
  53094. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  53095. if (!this._babylonScene.useRightHandedSystem) {
  53096. this._addRightHandToLeftHandRootTransform();
  53097. }
  53098. break;
  53099. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  53100. // do nothing
  53101. break;
  53102. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  53103. this._babylonScene.useRightHandedSystem = true;
  53104. break;
  53105. default:
  53106. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  53107. break;
  53108. }
  53109. this._showMeshes();
  53110. this._startAnimations();
  53111. this._successCallback();
  53112. this._renderReadyObservable.notifyObservers(this);
  53113. };
  53114. GLTFLoader.prototype._onLoaderComplete = function () {
  53115. if (this._parent.onComplete) {
  53116. this._parent.onComplete();
  53117. }
  53118. };
  53119. GLTFLoader.prototype._onLoaderFirstLODComplete = function () {
  53120. if (this._parent.onFirstLODComplete) {
  53121. this._parent.onFirstLODComplete();
  53122. }
  53123. };
  53124. GLTFLoader.prototype._loadData = function (data) {
  53125. this._gltf = data.json;
  53126. var binaryBuffer;
  53127. var buffers = this._gltf.buffers;
  53128. if (buffers.length > 0 && buffers[0].uri === undefined) {
  53129. binaryBuffer = buffers[0];
  53130. }
  53131. if (data.bin) {
  53132. if (binaryBuffer) {
  53133. if (binaryBuffer.byteLength != data.bin.byteLength) {
  53134. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  53135. }
  53136. }
  53137. else {
  53138. BABYLON.Tools.Warn("Unexpected BIN chunk");
  53139. }
  53140. binaryBuffer.loadedData = data.bin;
  53141. }
  53142. };
  53143. GLTFLoader.prototype._addRightHandToLeftHandRootTransform = function () {
  53144. var rootMesh = new BABYLON.Mesh("root", this._babylonScene);
  53145. rootMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  53146. rootMesh.rotation.y = Math.PI;
  53147. var nodes = this._gltf.nodes;
  53148. for (var i = 0; i < nodes.length; i++) {
  53149. var mesh = nodes[i].babylonMesh;
  53150. if (mesh && !mesh.parent) {
  53151. mesh.parent = rootMesh;
  53152. }
  53153. }
  53154. };
  53155. GLTFLoader.prototype._getMeshes = function () {
  53156. var meshes = [];
  53157. var nodes = this._gltf.nodes;
  53158. if (nodes) {
  53159. nodes.forEach(function (node) {
  53160. if (node.babylonMesh) {
  53161. meshes.push(node.babylonMesh);
  53162. }
  53163. });
  53164. }
  53165. return meshes;
  53166. };
  53167. GLTFLoader.prototype._getSkeletons = function () {
  53168. var skeletons = [];
  53169. var skins = this._gltf.skins;
  53170. if (skins) {
  53171. skins.forEach(function (skin) {
  53172. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  53173. skeletons.push(skin.babylonSkeleton);
  53174. }
  53175. });
  53176. }
  53177. return skeletons;
  53178. };
  53179. GLTFLoader.prototype._getAnimationTargets = function () {
  53180. var targets = [];
  53181. var animations = this._gltf.animations;
  53182. if (animations) {
  53183. animations.forEach(function (animation) {
  53184. targets.push.apply(targets, animation.targets);
  53185. });
  53186. }
  53187. return targets;
  53188. };
  53189. GLTFLoader.prototype._showMeshes = function () {
  53190. this._getMeshes().forEach(function (mesh) { return mesh.isVisible = true; });
  53191. };
  53192. GLTFLoader.prototype._startAnimations = function () {
  53193. var _this = this;
  53194. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  53195. };
  53196. GLTFLoader.prototype._loadScene = function (nodeNames) {
  53197. var _this = this;
  53198. var scene = this._gltf.scenes[this._gltf.scene || 0];
  53199. var nodeIndices = scene.nodes;
  53200. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  53201. node.index = index;
  53202. node.parent = parentNode;
  53203. return true;
  53204. });
  53205. var materials = this._gltf.materials;
  53206. if (materials) {
  53207. materials.forEach(function (material, index) { return material.index = index; });
  53208. }
  53209. if (nodeNames) {
  53210. if (!(nodeNames instanceof Array)) {
  53211. nodeNames = [nodeNames];
  53212. }
  53213. var filteredNodeIndices = new Array();
  53214. this._traverseNodes(nodeIndices, function (node) {
  53215. if (nodeNames.indexOf(node.name) === -1) {
  53216. return true;
  53217. }
  53218. filteredNodeIndices.push(node.index);
  53219. return false;
  53220. });
  53221. nodeIndices = filteredNodeIndices;
  53222. }
  53223. this._traverseNodes(nodeIndices, function (node) { return _this._loadSkin(node); });
  53224. this._traverseNodes(nodeIndices, function (node) { return _this._loadMesh(node); });
  53225. };
  53226. GLTFLoader.prototype._loadSkin = function (node) {
  53227. var _this = this;
  53228. if (node.skin !== undefined) {
  53229. var skin = this._gltf.skins[node.skin];
  53230. var skeletonId = "skeleton" + node.skin;
  53231. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  53232. skin.index = node.skin;
  53233. for (var i = 0; i < skin.joints.length; i++) {
  53234. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  53235. }
  53236. if (skin.skeleton === undefined) {
  53237. // TODO: handle when skeleton is not defined
  53238. throw new Error("Not implemented");
  53239. }
  53240. if (skin.inverseBindMatrices === undefined) {
  53241. // TODO: handle when inverse bind matrices are not defined
  53242. throw new Error("Not implemented");
  53243. }
  53244. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  53245. this._loadAccessorAsync(accessor, function (data) {
  53246. _this._traverseNode(skin.skeleton, function (node, index, parent) { return _this._updateBone(node, parent, skin, data); });
  53247. });
  53248. }
  53249. return true;
  53250. };
  53251. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  53252. var jointIndex = skin.joints.indexOf(node.index);
  53253. if (jointIndex === -1) {
  53254. this._createBone(node, skin);
  53255. }
  53256. var babylonBone = node.babylonSkinToBones[skin.index];
  53257. // TODO: explain the math
  53258. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  53259. matrix.invertToRef(matrix);
  53260. if (parentNode) {
  53261. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  53262. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  53263. }
  53264. babylonBone.updateMatrix(matrix);
  53265. return true;
  53266. };
  53267. GLTFLoader.prototype._createBone = function (node, skin) {
  53268. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  53269. node.babylonSkinToBones = node.babylonSkinToBones || {};
  53270. node.babylonSkinToBones[skin.index] = babylonBone;
  53271. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  53272. node.babylonAnimationTargets.push(babylonBone);
  53273. return babylonBone;
  53274. };
  53275. GLTFLoader.prototype._loadMesh = function (node) {
  53276. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  53277. babylonMesh.isVisible = false;
  53278. this._loadTransform(node, babylonMesh);
  53279. if (node.mesh !== undefined) {
  53280. var mesh = this._gltf.meshes[node.mesh];
  53281. this._loadMeshData(node, mesh, babylonMesh);
  53282. }
  53283. babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  53284. node.babylonMesh = babylonMesh;
  53285. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  53286. node.babylonAnimationTargets.push(node.babylonMesh);
  53287. if (node.skin !== undefined) {
  53288. var skin = this._gltf.skins[node.skin];
  53289. babylonMesh.skeleton = skin.babylonSkeleton;
  53290. }
  53291. if (node.camera !== undefined) {
  53292. // TODO: handle cameras
  53293. }
  53294. return true;
  53295. };
  53296. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  53297. var _this = this;
  53298. babylonMesh.name = mesh.name || babylonMesh.name;
  53299. var babylonMultiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  53300. babylonMesh.material = babylonMultiMaterial;
  53301. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  53302. var vertexData = new BABYLON.VertexData();
  53303. vertexData.positions = [];
  53304. vertexData.indices = [];
  53305. var subMeshInfos = [];
  53306. var loadedPrimitives = 0;
  53307. var totalPrimitives = mesh.primitives.length;
  53308. var _loop_1 = function (i) {
  53309. var primitive = mesh.primitives[i];
  53310. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  53311. // TODO: handle other primitive modes
  53312. throw new Error("Not implemented");
  53313. }
  53314. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  53315. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  53316. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  53317. subMeshInfos.push({
  53318. materialIndex: i,
  53319. verticesStart: vertexData.positions.length,
  53320. verticesCount: subVertexData.positions.length,
  53321. indicesStart: vertexData.indices.length,
  53322. indicesCount: subVertexData.indices.length,
  53323. loadMaterial: function () {
  53324. if (primitive.material === undefined) {
  53325. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  53326. }
  53327. else {
  53328. var material = _this._gltf.materials[primitive.material];
  53329. _this.loadMaterial(material, function (babylonMaterial, isNew) {
  53330. if (isNew && _this._parent.onMaterialLoaded) {
  53331. _this._parent.onMaterialLoaded(babylonMaterial);
  53332. }
  53333. if (_this._parent.onBeforeMaterialReadyAsync) {
  53334. _this.addLoaderPendingData(material);
  53335. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  53336. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  53337. _this.removeLoaderPendingData(material);
  53338. });
  53339. }
  53340. else {
  53341. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  53342. }
  53343. });
  53344. }
  53345. }
  53346. });
  53347. vertexData.merge(subVertexData);
  53348. if (++loadedPrimitives === totalPrimitives) {
  53349. geometry.setAllVerticesData(vertexData, false);
  53350. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  53351. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  53352. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  53353. babylonMesh.subMeshes = [];
  53354. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh); });
  53355. }
  53356. });
  53357. };
  53358. var this_1 = this;
  53359. for (var i = 0; i < totalPrimitives; i++) {
  53360. _loop_1(i);
  53361. }
  53362. };
  53363. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  53364. var _this = this;
  53365. var attributes = primitive.attributes;
  53366. if (!attributes) {
  53367. this._onError("Primitive has no attributes");
  53368. return;
  53369. }
  53370. var vertexData = new BABYLON.VertexData();
  53371. var loadedAttributes = 0;
  53372. var totalAttributes = Object.keys(attributes).length;
  53373. var _loop_2 = function (semantic) {
  53374. accessor = this_2._gltf.accessors[attributes[semantic]];
  53375. this_2._loadAccessorAsync(accessor, function (data) {
  53376. switch (semantic) {
  53377. case "NORMAL":
  53378. vertexData.normals = data;
  53379. break;
  53380. case "POSITION":
  53381. vertexData.positions = data;
  53382. break;
  53383. case "TANGENT":
  53384. vertexData.tangents = data;
  53385. break;
  53386. case "TEXCOORD_0":
  53387. vertexData.uvs = data;
  53388. break;
  53389. case "TEXCOORD_1":
  53390. vertexData.uvs2 = data;
  53391. break;
  53392. case "JOINTS_0":
  53393. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  53394. break;
  53395. case "WEIGHTS_0":
  53396. vertexData.matricesWeights = data;
  53397. break;
  53398. case "COLOR_0":
  53399. vertexData.colors = data;
  53400. break;
  53401. default:
  53402. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  53403. break;
  53404. }
  53405. if (++loadedAttributes === totalAttributes) {
  53406. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  53407. if (indicesAccessor) {
  53408. _this._loadAccessorAsync(indicesAccessor, function (data) {
  53409. vertexData.indices = data;
  53410. onSuccess(vertexData);
  53411. });
  53412. }
  53413. else {
  53414. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  53415. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  53416. onSuccess(vertexData);
  53417. }
  53418. }
  53419. });
  53420. };
  53421. var this_2 = this, accessor;
  53422. for (var semantic in attributes) {
  53423. _loop_2(semantic);
  53424. }
  53425. };
  53426. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  53427. var targets = primitive.targets;
  53428. if (!targets) {
  53429. return;
  53430. }
  53431. if (!babylonMesh.morphTargetManager) {
  53432. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  53433. }
  53434. for (var index = 0; index < targets.length; index++) {
  53435. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  53436. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  53437. }
  53438. };
  53439. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  53440. var targets = primitive.targets;
  53441. if (!targets) {
  53442. return;
  53443. }
  53444. var _loop_3 = function () {
  53445. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  53446. attributes = targets[index];
  53447. var _loop_4 = function (semantic) {
  53448. accessor = this_3._gltf.accessors[attributes[semantic]];
  53449. this_3._loadAccessorAsync(accessor, function (data) {
  53450. if (accessor.name) {
  53451. babylonMorphTarget.name = accessor.name;
  53452. }
  53453. // glTF stores morph target information as deltas while babylon.js expects the final data.
  53454. // As a result we have to add the original data to the delta to calculate the final data.
  53455. var values = data;
  53456. switch (semantic) {
  53457. case "NORMAL":
  53458. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  53459. babylonMorphTarget.setNormals(values);
  53460. break;
  53461. case "POSITION":
  53462. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  53463. babylonMorphTarget.setPositions(values);
  53464. break;
  53465. case "TANGENT":
  53466. // Tangent data for morph targets is stored as xyz delta.
  53467. // The vertexData.tangent is stored as xyzw.
  53468. // So we need to skip every fourth vertexData.tangent.
  53469. for (var i = 0, j = 0; i < values.length; i++, j++) {
  53470. values[i] += vertexData.tangents[j];
  53471. if ((i + 1) % 3 == 0) {
  53472. j++;
  53473. }
  53474. }
  53475. babylonMorphTarget.setTangents(values);
  53476. break;
  53477. default:
  53478. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  53479. break;
  53480. }
  53481. });
  53482. };
  53483. for (var semantic in attributes) {
  53484. _loop_4(semantic);
  53485. }
  53486. };
  53487. var this_3 = this, attributes, accessor;
  53488. for (var index = 0; index < targets.length; index++) {
  53489. _loop_3();
  53490. }
  53491. };
  53492. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  53493. var position = BABYLON.Vector3.Zero();
  53494. var rotation = BABYLON.Quaternion.Identity();
  53495. var scaling = BABYLON.Vector3.One();
  53496. if (node.matrix) {
  53497. var mat = BABYLON.Matrix.FromArray(node.matrix);
  53498. mat.decompose(scaling, rotation, position);
  53499. }
  53500. else {
  53501. if (node.translation)
  53502. position = BABYLON.Vector3.FromArray(node.translation);
  53503. if (node.rotation)
  53504. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  53505. if (node.scale)
  53506. scaling = BABYLON.Vector3.FromArray(node.scale);
  53507. }
  53508. babylonMesh.position = position;
  53509. babylonMesh.rotationQuaternion = rotation;
  53510. babylonMesh.scaling = scaling;
  53511. };
  53512. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  53513. if (parentNode === void 0) { parentNode = null; }
  53514. for (var i = 0; i < indices.length; i++) {
  53515. this._traverseNode(indices[i], action, parentNode);
  53516. }
  53517. };
  53518. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  53519. if (parentNode === void 0) { parentNode = null; }
  53520. var node = this._gltf.nodes[index];
  53521. if (!action(node, index, parentNode)) {
  53522. return;
  53523. }
  53524. if (node.children) {
  53525. for (var i = 0; i < node.children.length; i++) {
  53526. this._traverseNode(node.children[i], action, node);
  53527. }
  53528. }
  53529. };
  53530. GLTFLoader.prototype._loadAnimations = function () {
  53531. var animations = this._gltf.animations;
  53532. if (!animations || animations.length === 0) {
  53533. return;
  53534. }
  53535. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  53536. var animation = animations[animationIndex];
  53537. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  53538. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  53539. }
  53540. }
  53541. };
  53542. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  53543. var channel = animation.channels[channelIndex];
  53544. var samplerIndex = channel.sampler;
  53545. var sampler = animation.samplers[samplerIndex];
  53546. var targetNode = this._gltf.nodes[channel.target.node];
  53547. if (!targetNode) {
  53548. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  53549. return;
  53550. }
  53551. var targetPath = {
  53552. "translation": "position",
  53553. "rotation": "rotationQuaternion",
  53554. "scale": "scaling",
  53555. "weights": "influence"
  53556. }[channel.target.path];
  53557. if (!targetPath) {
  53558. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  53559. return;
  53560. }
  53561. var animationType = {
  53562. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  53563. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  53564. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  53565. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  53566. }[targetPath];
  53567. var inputData;
  53568. var outputData;
  53569. var checkSuccess = function () {
  53570. if (!inputData || !outputData) {
  53571. return;
  53572. }
  53573. var outputBufferOffset = 0;
  53574. var getNextOutputValue = {
  53575. "position": function () {
  53576. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  53577. outputBufferOffset += 3;
  53578. return value;
  53579. },
  53580. "rotationQuaternion": function () {
  53581. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  53582. outputBufferOffset += 4;
  53583. return value;
  53584. },
  53585. "scaling": function () {
  53586. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  53587. outputBufferOffset += 3;
  53588. return value;
  53589. },
  53590. "influence": function () {
  53591. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  53592. var value = new Array(numTargets);
  53593. for (var i = 0; i < numTargets; i++) {
  53594. value[i] = outputData[outputBufferOffset++];
  53595. }
  53596. return value;
  53597. },
  53598. }[targetPath];
  53599. var getNextKey = {
  53600. "LINEAR": function (frameIndex) { return ({
  53601. frame: inputData[frameIndex],
  53602. value: getNextOutputValue()
  53603. }); },
  53604. "CUBICSPLINE": function (frameIndex) { return ({
  53605. frame: inputData[frameIndex],
  53606. inTangent: getNextOutputValue(),
  53607. value: getNextOutputValue(),
  53608. outTangent: getNextOutputValue()
  53609. }); },
  53610. }[sampler.interpolation];
  53611. var keys = new Array(inputData.length);
  53612. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  53613. keys[frameIndex] = getNextKey(frameIndex);
  53614. }
  53615. animation.targets = animation.targets || [];
  53616. if (targetPath === "influence") {
  53617. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  53618. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  53619. var morphTarget = morphTargetManager.getTarget(targetIndex);
  53620. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  53621. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  53622. babylonAnimation.setKeys(keys.map(function (key) { return ({
  53623. frame: key.frame,
  53624. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  53625. value: key.value[targetIndex],
  53626. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  53627. }); }));
  53628. morphTarget.animations.push(babylonAnimation);
  53629. animation.targets.push(morphTarget);
  53630. }
  53631. }
  53632. else {
  53633. var animationName = animation.name || "anim" + animationIndex;
  53634. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  53635. babylonAnimation.setKeys(keys);
  53636. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  53637. var target = targetNode.babylonAnimationTargets[i];
  53638. target.animations.push(babylonAnimation.clone());
  53639. animation.targets.push(target);
  53640. }
  53641. }
  53642. };
  53643. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  53644. inputData = data;
  53645. checkSuccess();
  53646. });
  53647. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  53648. outputData = data;
  53649. checkSuccess();
  53650. });
  53651. };
  53652. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  53653. var _this = this;
  53654. var buffer = this._gltf.buffers[index];
  53655. this.addPendingData(buffer);
  53656. if (buffer.loadedData) {
  53657. setTimeout(function () {
  53658. onSuccess(buffer.loadedData);
  53659. _this.removePendingData(buffer);
  53660. });
  53661. }
  53662. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  53663. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  53664. buffer.loadedData = new Uint8Array(data);
  53665. setTimeout(function () {
  53666. onSuccess(buffer.loadedData);
  53667. _this.removePendingData(buffer);
  53668. });
  53669. }
  53670. else if (buffer.loadedObservable) {
  53671. buffer.loadedObservable.add(function (buffer) {
  53672. onSuccess(buffer.loadedData);
  53673. _this.removePendingData(buffer);
  53674. });
  53675. }
  53676. else {
  53677. buffer.loadedObservable = new BABYLON.Observable();
  53678. buffer.loadedObservable.add(function (buffer) {
  53679. onSuccess(buffer.loadedData);
  53680. _this.removePendingData(buffer);
  53681. });
  53682. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  53683. buffer.loadedData = new Uint8Array(data);
  53684. buffer.loadedObservable.notifyObservers(buffer);
  53685. buffer.loadedObservable = null;
  53686. }, function (event) {
  53687. if (!_this._disposed) {
  53688. _this._onProgress(event);
  53689. }
  53690. }, this._babylonScene.database, true, function (request) {
  53691. if (!_this._disposed) {
  53692. _this._onError("Failed to load file '" + buffer.uri + "': " + request.status + " " + request.statusText);
  53693. _this.removePendingData(buffer);
  53694. }
  53695. });
  53696. }
  53697. };
  53698. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, componentType, onSuccess) {
  53699. var _this = this;
  53700. byteOffset += (bufferView.byteOffset || 0);
  53701. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  53702. if (byteOffset + byteLength > bufferData.byteLength) {
  53703. _this._onError("Buffer access is out of range");
  53704. return;
  53705. }
  53706. var buffer = bufferData.buffer;
  53707. byteOffset += bufferData.byteOffset;
  53708. var bufferViewData;
  53709. switch (componentType) {
  53710. case GLTF2.EComponentType.BYTE:
  53711. bufferViewData = new Int8Array(buffer, byteOffset, byteLength);
  53712. break;
  53713. case GLTF2.EComponentType.UNSIGNED_BYTE:
  53714. bufferViewData = new Uint8Array(buffer, byteOffset, byteLength);
  53715. break;
  53716. case GLTF2.EComponentType.SHORT:
  53717. bufferViewData = new Int16Array(buffer, byteOffset, byteLength);
  53718. break;
  53719. case GLTF2.EComponentType.UNSIGNED_SHORT:
  53720. bufferViewData = new Uint16Array(buffer, byteOffset, byteLength);
  53721. break;
  53722. case GLTF2.EComponentType.UNSIGNED_INT:
  53723. bufferViewData = new Uint32Array(buffer, byteOffset, byteLength);
  53724. break;
  53725. case GLTF2.EComponentType.FLOAT:
  53726. bufferViewData = new Float32Array(buffer, byteOffset, byteLength);
  53727. break;
  53728. default:
  53729. _this._onError("Invalid component type (" + componentType + ")");
  53730. return;
  53731. }
  53732. onSuccess(bufferViewData);
  53733. });
  53734. };
  53735. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  53736. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  53737. var byteOffset = accessor.byteOffset || 0;
  53738. var byteLength = accessor.count * this._getByteStrideFromType(accessor);
  53739. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, accessor.componentType, onSuccess);
  53740. };
  53741. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  53742. switch (accessor.type) {
  53743. case "SCALAR": return 1;
  53744. case "VEC2": return 2;
  53745. case "VEC3": return 3;
  53746. case "VEC4": return 4;
  53747. case "MAT2": return 4;
  53748. case "MAT3": return 9;
  53749. case "MAT4": return 16;
  53750. default:
  53751. this._onError("Invalid accessor type (" + accessor.type + ")");
  53752. return 0;
  53753. }
  53754. };
  53755. Object.defineProperty(GLTFLoader.prototype, "blockPendingTracking", {
  53756. set: function (value) {
  53757. this._blockPendingTracking = value;
  53758. },
  53759. enumerable: true,
  53760. configurable: true
  53761. });
  53762. GLTFLoader.prototype.addPendingData = function (data) {
  53763. if (!this._renderReady) {
  53764. this._renderPendingCount++;
  53765. }
  53766. this.addLoaderPendingData(data);
  53767. };
  53768. GLTFLoader.prototype.removePendingData = function (data) {
  53769. if (!this._renderReady) {
  53770. if (--this._renderPendingCount === 0) {
  53771. this._renderReady = true;
  53772. this._onRenderReady();
  53773. }
  53774. }
  53775. this.removeLoaderPendingData(data);
  53776. };
  53777. GLTFLoader.prototype.addLoaderNonBlockingPendingData = function (data) {
  53778. if (!this._nonBlockingData) {
  53779. this._nonBlockingData = new Array();
  53780. }
  53781. this._nonBlockingData.push(data);
  53782. };
  53783. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  53784. if (this._blockPendingTracking) {
  53785. this.addLoaderNonBlockingPendingData(data);
  53786. return;
  53787. }
  53788. this._loaderPendingCount++;
  53789. };
  53790. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  53791. var indexInPending = this._nonBlockingData ? this._nonBlockingData.indexOf(data) : -1;
  53792. if (indexInPending !== -1) {
  53793. this._nonBlockingData.splice(indexInPending, 1);
  53794. }
  53795. else if (--this._loaderPendingCount === 0) {
  53796. this._onLoaderFirstLODComplete();
  53797. }
  53798. if ((!this._nonBlockingData || this._nonBlockingData.length === 0) && this._loaderPendingCount === 0) {
  53799. this._onLoaderComplete();
  53800. this.dispose();
  53801. }
  53802. };
  53803. GLTFLoader.prototype._getDefaultMaterial = function () {
  53804. if (!this._defaultMaterial) {
  53805. var id = "__gltf_default";
  53806. var material = this._babylonScene.getMaterialByName(id);
  53807. if (!material) {
  53808. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  53809. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  53810. material.metallic = 1;
  53811. material.roughness = 1;
  53812. }
  53813. this._defaultMaterial = material;
  53814. }
  53815. return this._defaultMaterial;
  53816. };
  53817. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  53818. var babylonMaterial = material.babylonMaterial;
  53819. // Ensure metallic workflow
  53820. babylonMaterial.metallic = 1;
  53821. babylonMaterial.roughness = 1;
  53822. var properties = material.pbrMetallicRoughness;
  53823. if (!properties) {
  53824. return;
  53825. }
  53826. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  53827. babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  53828. babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  53829. if (properties.baseColorTexture) {
  53830. babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  53831. }
  53832. if (properties.metallicRoughnessTexture) {
  53833. babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  53834. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  53835. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  53836. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  53837. }
  53838. this.loadMaterialAlphaProperties(material, properties.baseColorFactor);
  53839. };
  53840. GLTFLoader.prototype.loadMaterial = function (material, assign) {
  53841. if (material.babylonMaterial) {
  53842. assign(material.babylonMaterial, false);
  53843. return;
  53844. }
  53845. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  53846. return;
  53847. }
  53848. this.createPbrMaterial(material);
  53849. this.loadMaterialBaseProperties(material);
  53850. this._loadMaterialMetallicRoughnessProperties(material);
  53851. assign(material.babylonMaterial, true);
  53852. };
  53853. GLTFLoader.prototype.createPbrMaterial = function (material) {
  53854. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  53855. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  53856. material.babylonMaterial = babylonMaterial;
  53857. };
  53858. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  53859. var babylonMaterial = material.babylonMaterial;
  53860. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  53861. if (material.doubleSided) {
  53862. babylonMaterial.backFaceCulling = false;
  53863. babylonMaterial.twoSidedLighting = true;
  53864. }
  53865. if (material.normalTexture) {
  53866. babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  53867. babylonMaterial.invertNormalMapX = true;
  53868. babylonMaterial.invertNormalMapY = true;
  53869. if (material.normalTexture.scale !== undefined) {
  53870. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  53871. }
  53872. }
  53873. if (material.occlusionTexture) {
  53874. babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  53875. babylonMaterial.useAmbientInGrayScale = true;
  53876. if (material.occlusionTexture.strength !== undefined) {
  53877. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  53878. }
  53879. }
  53880. if (material.emissiveTexture) {
  53881. babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  53882. }
  53883. };
  53884. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material, colorFactor) {
  53885. var babylonMaterial = material.babylonMaterial;
  53886. var alphaMode = material.alphaMode || "OPAQUE";
  53887. switch (alphaMode) {
  53888. case "OPAQUE":
  53889. // default is opaque
  53890. break;
  53891. case "MASK":
  53892. case "BLEND":
  53893. if (colorFactor) {
  53894. babylonMaterial.alpha = colorFactor[3];
  53895. }
  53896. if (babylonMaterial.albedoTexture) {
  53897. babylonMaterial.albedoTexture.hasAlpha = true;
  53898. babylonMaterial.useAlphaFromAlbedoTexture = (alphaMode === "BLEND");
  53899. }
  53900. break;
  53901. default:
  53902. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  53903. break;
  53904. }
  53905. };
  53906. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  53907. var _this = this;
  53908. var texture = this._gltf.textures[textureInfo.index];
  53909. var texCoord = textureInfo.texCoord || 0;
  53910. if (!texture || texture.source === undefined) {
  53911. return null;
  53912. }
  53913. // check the cache first
  53914. var babylonTexture;
  53915. if (texture.babylonTextures) {
  53916. babylonTexture = texture.babylonTextures[texCoord];
  53917. if (!babylonTexture) {
  53918. for (var i = 0; i < texture.babylonTextures.length; i++) {
  53919. babylonTexture = texture.babylonTextures[i];
  53920. if (babylonTexture) {
  53921. babylonTexture = babylonTexture.clone();
  53922. babylonTexture.coordinatesIndex = texCoord;
  53923. break;
  53924. }
  53925. }
  53926. }
  53927. return babylonTexture;
  53928. }
  53929. var source = this._gltf.images[texture.source];
  53930. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  53931. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  53932. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  53933. this.addPendingData(texture);
  53934. babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  53935. if (!_this._disposed) {
  53936. _this.removePendingData(texture);
  53937. }
  53938. }, function () {
  53939. if (!_this._disposed) {
  53940. _this._onError("Failed to load texture '" + source.uri + "'");
  53941. _this.removePendingData(texture);
  53942. }
  53943. });
  53944. var setTextureData = function (data) {
  53945. var url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  53946. _this._objectURLs.push(url);
  53947. babylonTexture.updateURL(url);
  53948. };
  53949. if (!source.uri) {
  53950. var bufferView = this._gltf.bufferViews[source.bufferView];
  53951. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  53952. }
  53953. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  53954. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  53955. }
  53956. else {
  53957. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  53958. if (!_this._disposed) {
  53959. _this._onProgress(event);
  53960. }
  53961. }, this._babylonScene.database, true, function (request) {
  53962. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  53963. });
  53964. }
  53965. babylonTexture.coordinatesIndex = texCoord;
  53966. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  53967. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  53968. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  53969. // Cache the texture
  53970. texture.babylonTextures = texture.babylonTextures || [];
  53971. texture.babylonTextures[texCoord] = babylonTexture;
  53972. if (this._parent.onTextureLoaded) {
  53973. this._parent.onTextureLoaded(babylonTexture);
  53974. }
  53975. return babylonTexture;
  53976. };
  53977. GLTFLoader.Extensions = {};
  53978. return GLTFLoader;
  53979. }());
  53980. GLTF2.GLTFLoader = GLTFLoader;
  53981. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  53982. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  53983. })(BABYLON || (BABYLON = {}));
  53984. //# sourceMappingURL=babylon.glTFLoader.js.map
  53985. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53986. var BABYLON;
  53987. (function (BABYLON) {
  53988. var GLTF2;
  53989. (function (GLTF2) {
  53990. /**
  53991. * Utils functions for GLTF
  53992. */
  53993. var GLTFUtils = (function () {
  53994. function GLTFUtils() {
  53995. }
  53996. /**
  53997. * If the uri is a base64 string
  53998. * @param uri: the uri to test
  53999. */
  54000. GLTFUtils.IsBase64 = function (uri) {
  54001. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  54002. };
  54003. /**
  54004. * Decode the base64 uri
  54005. * @param uri: the uri to decode
  54006. */
  54007. GLTFUtils.DecodeBase64 = function (uri) {
  54008. var decodedString = atob(uri.split(",")[1]);
  54009. var bufferLength = decodedString.length;
  54010. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  54011. for (var i = 0; i < bufferLength; i++) {
  54012. bufferView[i] = decodedString.charCodeAt(i);
  54013. }
  54014. return bufferView.buffer;
  54015. };
  54016. GLTFUtils.ForEach = function (view, func) {
  54017. for (var index = 0; index < view.length; index++) {
  54018. func(view[index], index);
  54019. }
  54020. };
  54021. GLTFUtils.GetTextureWrapMode = function (mode) {
  54022. // Set defaults if undefined
  54023. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  54024. switch (mode) {
  54025. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: BABYLON.Texture.CLAMP_ADDRESSMODE;
  54026. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  54027. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  54028. default:
  54029. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  54030. return BABYLON.Texture.WRAP_ADDRESSMODE;
  54031. }
  54032. };
  54033. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  54034. // Set defaults if undefined
  54035. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  54036. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST : minFilter;
  54037. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  54038. switch (minFilter) {
  54039. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  54040. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  54041. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  54042. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  54043. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  54044. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  54045. default:
  54046. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  54047. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  54048. }
  54049. }
  54050. else {
  54051. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  54052. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  54053. }
  54054. switch (minFilter) {
  54055. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  54056. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  54057. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  54058. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  54059. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  54060. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  54061. default:
  54062. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  54063. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  54064. }
  54065. }
  54066. };
  54067. /**
  54068. * Decodes a buffer view into a string
  54069. * @param view: the buffer view
  54070. */
  54071. GLTFUtils.DecodeBufferToText = function (view) {
  54072. var result = "";
  54073. var length = view.byteLength;
  54074. for (var i = 0; i < length; ++i) {
  54075. result += String.fromCharCode(view[i]);
  54076. }
  54077. return result;
  54078. };
  54079. return GLTFUtils;
  54080. }());
  54081. GLTF2.GLTFUtils = GLTFUtils;
  54082. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54083. })(BABYLON || (BABYLON = {}));
  54084. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  54085. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  54086. var BABYLON;
  54087. (function (BABYLON) {
  54088. var GLTF2;
  54089. (function (GLTF2) {
  54090. var GLTFLoaderExtension = (function () {
  54091. function GLTFLoaderExtension() {
  54092. this.enabled = true;
  54093. }
  54094. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  54095. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  54096. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  54097. };
  54098. GLTFLoaderExtension._ApplyExtensions = function (action) {
  54099. var extensions = GLTFLoaderExtension._Extensions;
  54100. if (!extensions) {
  54101. return;
  54102. }
  54103. for (var i = 0; i < extensions.length; i++) {
  54104. var extension = extensions[i];
  54105. if (extension.enabled && action(extension)) {
  54106. return true;
  54107. }
  54108. }
  54109. return false;
  54110. };
  54111. //
  54112. // Utilities
  54113. //
  54114. GLTFLoaderExtension._Extensions = [];
  54115. return GLTFLoaderExtension;
  54116. }());
  54117. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  54118. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54119. })(BABYLON || (BABYLON = {}));
  54120. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  54121. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  54122. var BABYLON;
  54123. (function (BABYLON) {
  54124. var GLTF2;
  54125. (function (GLTF2) {
  54126. var Extensions;
  54127. (function (Extensions) {
  54128. var MSFTLOD = (function (_super) {
  54129. __extends(MSFTLOD, _super);
  54130. function MSFTLOD() {
  54131. return _super !== null && _super.apply(this, arguments) || this;
  54132. }
  54133. Object.defineProperty(MSFTLOD.prototype, "name", {
  54134. get: function () {
  54135. return "MSFT_lod";
  54136. },
  54137. enumerable: true,
  54138. configurable: true
  54139. });
  54140. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  54141. if (!material.extensions) {
  54142. return false;
  54143. }
  54144. var properties = material.extensions[this.name];
  54145. if (!properties) {
  54146. return false;
  54147. }
  54148. // Clear out the extension so that it won't get loaded again.
  54149. material.extensions[this.name] = undefined;
  54150. // Tell the loader not to clear its state until the highest LOD is loaded.
  54151. var materialLODs = [material.index].concat(properties.ids);
  54152. loader.addLoaderPendingData(material);
  54153. for (var index = 0; index < materialLODs.length; index++) {
  54154. loader.addLoaderNonBlockingPendingData(index);
  54155. }
  54156. // Start with the lowest quality LOD.
  54157. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  54158. return true;
  54159. };
  54160. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  54161. var _this = this;
  54162. var materialLOD = loader.gltf.materials[materialLODs[lod]];
  54163. if (lod !== materialLODs.length - 1) {
  54164. loader.blockPendingTracking = true;
  54165. }
  54166. loader.loadMaterial(materialLOD, function (babylonMaterial, isNew) {
  54167. assign(babylonMaterial, isNew);
  54168. loader.removeLoaderPendingData(lod);
  54169. // Loading is considered complete if this is the lowest quality LOD.
  54170. if (lod === materialLODs.length - 1) {
  54171. loader.removeLoaderPendingData(material);
  54172. }
  54173. if (lod === 0) {
  54174. loader.blockPendingTracking = false;
  54175. return;
  54176. }
  54177. // Load the next LOD when the loader is ready to render and
  54178. // all active material textures of the current LOD are loaded.
  54179. loader.executeWhenRenderReady(function () {
  54180. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  54181. setTimeout(function () {
  54182. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  54183. }, MSFTLOD.MinimalLODDelay);
  54184. });
  54185. });
  54186. });
  54187. };
  54188. /**
  54189. * Specify the minimal delay between LODs in ms (default = 250)
  54190. */
  54191. MSFTLOD.MinimalLODDelay = 250;
  54192. return MSFTLOD;
  54193. }(GLTF2.GLTFLoaderExtension));
  54194. Extensions.MSFTLOD = MSFTLOD;
  54195. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  54196. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  54197. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54198. })(BABYLON || (BABYLON = {}));
  54199. //# sourceMappingURL=MSFT_lod.js.map
  54200. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  54201. var BABYLON;
  54202. (function (BABYLON) {
  54203. var GLTF2;
  54204. (function (GLTF2) {
  54205. var Extensions;
  54206. (function (Extensions) {
  54207. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  54208. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  54209. function KHRMaterialsPbrSpecularGlossiness() {
  54210. return _super !== null && _super.apply(this, arguments) || this;
  54211. }
  54212. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  54213. get: function () {
  54214. return "KHR_materials_pbrSpecularGlossiness";
  54215. },
  54216. enumerable: true,
  54217. configurable: true
  54218. });
  54219. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  54220. if (!material.extensions) {
  54221. return false;
  54222. }
  54223. var properties = material.extensions[this.name];
  54224. if (!properties) {
  54225. return false;
  54226. }
  54227. loader.createPbrMaterial(material);
  54228. loader.loadMaterialBaseProperties(material);
  54229. this._loadSpecularGlossinessProperties(loader, material, properties);
  54230. assign(material.babylonMaterial, true);
  54231. return true;
  54232. };
  54233. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  54234. var babylonMaterial = material.babylonMaterial;
  54235. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  54236. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  54237. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  54238. if (properties.diffuseTexture) {
  54239. babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  54240. loader.loadMaterialAlphaProperties(material);
  54241. }
  54242. if (properties.specularGlossinessTexture) {
  54243. babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  54244. babylonMaterial.reflectivityTexture.hasAlpha = true;
  54245. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  54246. }
  54247. loader.loadMaterialAlphaProperties(material, properties.diffuseFactor);
  54248. };
  54249. return KHRMaterialsPbrSpecularGlossiness;
  54250. }(GLTF2.GLTFLoaderExtension));
  54251. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  54252. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  54253. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  54254. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54255. })(BABYLON || (BABYLON = {}));
  54256. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  54257. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  54258. module.exports = BABYLON;
  54259. };