babylon.max.js 2.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282
  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.getRenderWidth) {
  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. url = Tools.PreprocessUrl(url);
  5709. var img = new Image();
  5710. if (url.substr(0, 5) !== "data:") {
  5711. Tools.SetCorsBehavior(url, img);
  5712. }
  5713. img.onload = function () {
  5714. onload(img);
  5715. };
  5716. img.onerror = function (err) {
  5717. Tools.Error("Error while trying to load image: " + url);
  5718. if (Tools.UseFallbackTexture) {
  5719. img.src = Tools.fallbackTexture;
  5720. onload(img);
  5721. }
  5722. else {
  5723. onerror();
  5724. }
  5725. };
  5726. var noIndexedDB = function () {
  5727. img.src = url;
  5728. };
  5729. var loadFromIndexedDB = function () {
  5730. database.loadImageFromDB(url, img);
  5731. };
  5732. //ANY database to do!
  5733. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5734. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5735. }
  5736. else {
  5737. if (url.indexOf("file:") !== 0) {
  5738. noIndexedDB();
  5739. }
  5740. else {
  5741. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5742. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5743. try {
  5744. var blobURL;
  5745. try {
  5746. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5747. }
  5748. catch (ex) {
  5749. // Chrome doesn't support oneTimeOnly parameter
  5750. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5751. }
  5752. img.src = blobURL;
  5753. }
  5754. catch (e) {
  5755. img.src = null;
  5756. }
  5757. }
  5758. else {
  5759. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5760. img.src = Tools.fallbackTexture;
  5761. }
  5762. }
  5763. }
  5764. return img;
  5765. };
  5766. //ANY
  5767. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5768. url = Tools.CleanUrl(url);
  5769. url = Tools.PreprocessUrl(url);
  5770. var noIndexedDB = function () {
  5771. var request = new XMLHttpRequest();
  5772. var loadUrl = Tools.BaseUrl + url;
  5773. request.open('GET', loadUrl, true);
  5774. if (useArrayBuffer) {
  5775. request.responseType = "arraybuffer";
  5776. }
  5777. request.onprogress = progressCallBack;
  5778. request.onreadystatechange = function () {
  5779. // In case of undefined state in some browsers.
  5780. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5781. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5782. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5783. callback(!useArrayBuffer ? request.responseText : request.response);
  5784. }
  5785. else {
  5786. if (onError) {
  5787. onError(request);
  5788. }
  5789. else {
  5790. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5791. }
  5792. }
  5793. }
  5794. };
  5795. request.send(null);
  5796. };
  5797. var loadFromIndexedDB = function () {
  5798. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5799. };
  5800. if (url.indexOf("file:") !== -1) {
  5801. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5802. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5803. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5804. }
  5805. else {
  5806. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5807. }
  5808. }
  5809. else {
  5810. // Caching all files
  5811. if (database && database.enableSceneOffline) {
  5812. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5813. }
  5814. else {
  5815. noIndexedDB();
  5816. }
  5817. }
  5818. };
  5819. /**
  5820. * Load a script (identified by an url). When the url returns, the
  5821. * content of this file is added into a new script element, attached to the DOM (body element)
  5822. */
  5823. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5824. var head = document.getElementsByTagName('head')[0];
  5825. var script = document.createElement('script');
  5826. script.type = 'text/javascript';
  5827. script.src = scriptUrl;
  5828. var self = this;
  5829. script.onload = function () {
  5830. if (onSuccess) {
  5831. onSuccess();
  5832. }
  5833. };
  5834. script.onerror = function () {
  5835. if (onError) {
  5836. onError();
  5837. }
  5838. };
  5839. head.appendChild(script);
  5840. };
  5841. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5842. var reader = new FileReader();
  5843. reader.onload = function (e) {
  5844. //target doesn't have result from ts 1.3
  5845. callback(e.target['result']);
  5846. };
  5847. reader.onprogress = progressCallback;
  5848. reader.readAsDataURL(fileToLoad);
  5849. };
  5850. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5851. var reader = new FileReader();
  5852. reader.onerror = function (e) {
  5853. Tools.Log("Error while reading file: " + fileToLoad.name);
  5854. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5855. };
  5856. reader.onload = function (e) {
  5857. //target doesn't have result from ts 1.3
  5858. callback(e.target['result']);
  5859. };
  5860. reader.onprogress = progressCallBack;
  5861. if (!useArrayBuffer) {
  5862. // Asynchronous read
  5863. reader.readAsText(fileToLoad);
  5864. }
  5865. else {
  5866. reader.readAsArrayBuffer(fileToLoad);
  5867. }
  5868. };
  5869. //returns a downloadable url to a file content.
  5870. Tools.FileAsURL = function (content) {
  5871. var fileBlob = new Blob([content]);
  5872. var url = window.URL || window.webkitURL;
  5873. var link = url.createObjectURL(fileBlob);
  5874. return link;
  5875. };
  5876. // Misc.
  5877. Tools.Format = function (value, decimals) {
  5878. if (decimals === void 0) { decimals = 2; }
  5879. return value.toFixed(decimals);
  5880. };
  5881. Tools.CheckExtends = function (v, min, max) {
  5882. if (v.x < min.x)
  5883. min.x = v.x;
  5884. if (v.y < min.y)
  5885. min.y = v.y;
  5886. if (v.z < min.z)
  5887. min.z = v.z;
  5888. if (v.x > max.x)
  5889. max.x = v.x;
  5890. if (v.y > max.y)
  5891. max.y = v.y;
  5892. if (v.z > max.z)
  5893. max.z = v.z;
  5894. };
  5895. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5896. for (var prop in source) {
  5897. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5898. continue;
  5899. }
  5900. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5901. continue;
  5902. }
  5903. var sourceValue = source[prop];
  5904. var typeOfSourceValue = typeof sourceValue;
  5905. if (typeOfSourceValue === "function") {
  5906. continue;
  5907. }
  5908. if (typeOfSourceValue === "object") {
  5909. if (sourceValue instanceof Array) {
  5910. destination[prop] = [];
  5911. if (sourceValue.length > 0) {
  5912. if (typeof sourceValue[0] == "object") {
  5913. for (var index = 0; index < sourceValue.length; index++) {
  5914. var clonedValue = cloneValue(sourceValue[index], destination);
  5915. if (destination[prop].indexOf(clonedValue) === -1) {
  5916. destination[prop].push(clonedValue);
  5917. }
  5918. }
  5919. }
  5920. else {
  5921. destination[prop] = sourceValue.slice(0);
  5922. }
  5923. }
  5924. }
  5925. else {
  5926. destination[prop] = cloneValue(sourceValue, destination);
  5927. }
  5928. }
  5929. else {
  5930. destination[prop] = sourceValue;
  5931. }
  5932. }
  5933. };
  5934. Tools.IsEmpty = function (obj) {
  5935. for (var i in obj) {
  5936. return false;
  5937. }
  5938. return true;
  5939. };
  5940. Tools.RegisterTopRootEvents = function (events) {
  5941. for (var index = 0; index < events.length; index++) {
  5942. var event = events[index];
  5943. window.addEventListener(event.name, event.handler, false);
  5944. try {
  5945. if (window.parent) {
  5946. window.parent.addEventListener(event.name, event.handler, false);
  5947. }
  5948. }
  5949. catch (e) {
  5950. // Silently fails...
  5951. }
  5952. }
  5953. };
  5954. Tools.UnregisterTopRootEvents = function (events) {
  5955. for (var index = 0; index < events.length; index++) {
  5956. var event = events[index];
  5957. window.removeEventListener(event.name, event.handler);
  5958. try {
  5959. if (window.parent) {
  5960. window.parent.removeEventListener(event.name, event.handler);
  5961. }
  5962. }
  5963. catch (e) {
  5964. // Silently fails...
  5965. }
  5966. }
  5967. };
  5968. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5969. if (mimeType === void 0) { mimeType = "image/png"; }
  5970. // Read the contents of the framebuffer
  5971. var numberOfChannelsByLine = width * 4;
  5972. var halfHeight = height / 2;
  5973. //Reading datas from WebGL
  5974. var data = engine.readPixels(0, 0, width, height);
  5975. //To flip image on Y axis.
  5976. for (var i = 0; i < halfHeight; i++) {
  5977. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5978. var currentCell = j + i * numberOfChannelsByLine;
  5979. var targetLine = height - i - 1;
  5980. var targetCell = j + targetLine * numberOfChannelsByLine;
  5981. var temp = data[currentCell];
  5982. data[currentCell] = data[targetCell];
  5983. data[targetCell] = temp;
  5984. }
  5985. }
  5986. // Create a 2D canvas to store the result
  5987. if (!screenshotCanvas) {
  5988. screenshotCanvas = document.createElement('canvas');
  5989. }
  5990. screenshotCanvas.width = width;
  5991. screenshotCanvas.height = height;
  5992. var context = screenshotCanvas.getContext('2d');
  5993. // Copy the pixels to a 2D canvas
  5994. var imageData = context.createImageData(width, height);
  5995. var castData = (imageData.data);
  5996. castData.set(data);
  5997. context.putImageData(imageData, 0, 0);
  5998. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5999. };
  6000. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6001. if (mimeType === void 0) { mimeType = "image/png"; }
  6002. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6003. if (successCallback) {
  6004. successCallback(base64Image);
  6005. }
  6006. else {
  6007. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6008. if (("download" in document.createElement("a"))) {
  6009. var a = window.document.createElement("a");
  6010. a.href = base64Image;
  6011. var date = new Date();
  6012. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6013. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6014. window.document.body.appendChild(a);
  6015. a.addEventListener("click", function () {
  6016. a.parentElement.removeChild(a);
  6017. });
  6018. a.click();
  6019. //Or opening a new tab with the image if it is not possible to automatically start download.
  6020. }
  6021. else {
  6022. var newWindow = window.open("");
  6023. var img = newWindow.document.createElement("img");
  6024. img.src = base64Image;
  6025. newWindow.document.body.appendChild(img);
  6026. }
  6027. }
  6028. };
  6029. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6030. if (mimeType === void 0) { mimeType = "image/png"; }
  6031. var width;
  6032. var height;
  6033. // If a precision value is specified
  6034. if (size.precision) {
  6035. width = Math.round(engine.getRenderWidth() * size.precision);
  6036. height = Math.round(width / engine.getAspectRatio(camera));
  6037. }
  6038. else if (size.width && size.height) {
  6039. width = size.width;
  6040. height = size.height;
  6041. }
  6042. else if (size.width && !size.height) {
  6043. width = size.width;
  6044. height = Math.round(width / engine.getAspectRatio(camera));
  6045. }
  6046. else if (size.height && !size.width) {
  6047. height = size.height;
  6048. width = Math.round(height * engine.getAspectRatio(camera));
  6049. }
  6050. else if (!isNaN(size)) {
  6051. height = size;
  6052. width = size;
  6053. }
  6054. else {
  6055. Tools.Error("Invalid 'size' parameter !");
  6056. return;
  6057. }
  6058. if (!screenshotCanvas) {
  6059. screenshotCanvas = document.createElement('canvas');
  6060. }
  6061. screenshotCanvas.width = width;
  6062. screenshotCanvas.height = height;
  6063. var renderContext = screenshotCanvas.getContext("2d");
  6064. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6065. var newWidth = width;
  6066. var newHeight = newWidth / ratio;
  6067. if (newHeight > height) {
  6068. newHeight = height;
  6069. newWidth = newHeight * ratio;
  6070. }
  6071. var offsetX = Math.max(0, width - newWidth) / 2;
  6072. var offsetY = Math.max(0, height - newHeight) / 2;
  6073. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6074. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6075. };
  6076. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6077. if (mimeType === void 0) { mimeType = "image/png"; }
  6078. if (samples === void 0) { samples = 1; }
  6079. var width;
  6080. var height;
  6081. //If a precision value is specified
  6082. if (size.precision) {
  6083. width = Math.round(engine.getRenderWidth() * size.precision);
  6084. height = Math.round(width / engine.getAspectRatio(camera));
  6085. size = { width: width, height: height };
  6086. }
  6087. else if (size.width && size.height) {
  6088. width = size.width;
  6089. height = size.height;
  6090. }
  6091. else if (size.width && !size.height) {
  6092. width = size.width;
  6093. height = Math.round(width / engine.getAspectRatio(camera));
  6094. size = { width: width, height: height };
  6095. }
  6096. else if (size.height && !size.width) {
  6097. height = size.height;
  6098. width = Math.round(height * engine.getAspectRatio(camera));
  6099. size = { width: width, height: height };
  6100. }
  6101. else if (!isNaN(size)) {
  6102. height = size;
  6103. width = size;
  6104. }
  6105. else {
  6106. Tools.Error("Invalid 'size' parameter !");
  6107. return;
  6108. }
  6109. var scene = camera.getScene();
  6110. var previousCamera = null;
  6111. if (scene.activeCamera !== camera) {
  6112. previousCamera = scene.activeCamera;
  6113. scene.activeCamera = camera;
  6114. }
  6115. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6116. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6117. texture.renderList = null;
  6118. texture.samples = samples;
  6119. texture.onAfterRenderObservable.add(function () {
  6120. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6121. });
  6122. scene.incrementRenderId();
  6123. scene.resetCachedMaterial();
  6124. texture.render(true);
  6125. texture.dispose();
  6126. if (previousCamera) {
  6127. scene.activeCamera = previousCamera;
  6128. }
  6129. camera.getProjectionMatrix(true); // Force cache refresh;
  6130. };
  6131. // XHR response validator for local file scenario
  6132. Tools.ValidateXHRData = function (xhr, dataType) {
  6133. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6134. if (dataType === void 0) { dataType = 7; }
  6135. try {
  6136. if (dataType & 1) {
  6137. if (xhr.responseText && xhr.responseText.length > 0) {
  6138. return true;
  6139. }
  6140. else if (dataType === 1) {
  6141. return false;
  6142. }
  6143. }
  6144. if (dataType & 2) {
  6145. // Check header width and height since there is no "TGA" magic number
  6146. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6147. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6148. return true;
  6149. }
  6150. else if (dataType === 2) {
  6151. return false;
  6152. }
  6153. }
  6154. if (dataType & 4) {
  6155. // Check for the "DDS" magic number
  6156. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6157. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6158. return true;
  6159. }
  6160. else {
  6161. return false;
  6162. }
  6163. }
  6164. }
  6165. catch (e) {
  6166. // Global protection
  6167. }
  6168. return false;
  6169. };
  6170. /**
  6171. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6172. * Be aware Math.random() could cause collisions, but:
  6173. * "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"
  6174. */
  6175. Tools.RandomId = function () {
  6176. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6177. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6178. return v.toString(16);
  6179. });
  6180. };
  6181. Object.defineProperty(Tools, "NoneLogLevel", {
  6182. get: function () {
  6183. return Tools._NoneLogLevel;
  6184. },
  6185. enumerable: true,
  6186. configurable: true
  6187. });
  6188. Object.defineProperty(Tools, "MessageLogLevel", {
  6189. get: function () {
  6190. return Tools._MessageLogLevel;
  6191. },
  6192. enumerable: true,
  6193. configurable: true
  6194. });
  6195. Object.defineProperty(Tools, "WarningLogLevel", {
  6196. get: function () {
  6197. return Tools._WarningLogLevel;
  6198. },
  6199. enumerable: true,
  6200. configurable: true
  6201. });
  6202. Object.defineProperty(Tools, "ErrorLogLevel", {
  6203. get: function () {
  6204. return Tools._ErrorLogLevel;
  6205. },
  6206. enumerable: true,
  6207. configurable: true
  6208. });
  6209. Object.defineProperty(Tools, "AllLogLevel", {
  6210. get: function () {
  6211. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6212. },
  6213. enumerable: true,
  6214. configurable: true
  6215. });
  6216. Tools._AddLogEntry = function (entry) {
  6217. Tools._LogCache = entry + Tools._LogCache;
  6218. if (Tools.OnNewCacheEntry) {
  6219. Tools.OnNewCacheEntry(entry);
  6220. }
  6221. };
  6222. Tools._FormatMessage = function (message) {
  6223. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6224. var date = new Date();
  6225. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6226. };
  6227. Tools._LogDisabled = function (message) {
  6228. // nothing to do
  6229. };
  6230. Tools._LogEnabled = function (message) {
  6231. var formattedMessage = Tools._FormatMessage(message);
  6232. console.log("BJS - " + formattedMessage);
  6233. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6234. Tools._AddLogEntry(entry);
  6235. };
  6236. Tools._WarnDisabled = function (message) {
  6237. // nothing to do
  6238. };
  6239. Tools._WarnEnabled = function (message) {
  6240. var formattedMessage = Tools._FormatMessage(message);
  6241. console.warn("BJS - " + formattedMessage);
  6242. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6243. Tools._AddLogEntry(entry);
  6244. };
  6245. Tools._ErrorDisabled = function (message) {
  6246. // nothing to do
  6247. };
  6248. Tools._ErrorEnabled = function (message) {
  6249. Tools.errorsCount++;
  6250. var formattedMessage = Tools._FormatMessage(message);
  6251. console.error("BJS - " + formattedMessage);
  6252. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6253. Tools._AddLogEntry(entry);
  6254. };
  6255. Object.defineProperty(Tools, "LogCache", {
  6256. get: function () {
  6257. return Tools._LogCache;
  6258. },
  6259. enumerable: true,
  6260. configurable: true
  6261. });
  6262. Tools.ClearLogCache = function () {
  6263. Tools._LogCache = "";
  6264. Tools.errorsCount = 0;
  6265. };
  6266. Object.defineProperty(Tools, "LogLevels", {
  6267. set: function (level) {
  6268. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6269. Tools.Log = Tools._LogEnabled;
  6270. }
  6271. else {
  6272. Tools.Log = Tools._LogDisabled;
  6273. }
  6274. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6275. Tools.Warn = Tools._WarnEnabled;
  6276. }
  6277. else {
  6278. Tools.Warn = Tools._WarnDisabled;
  6279. }
  6280. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6281. Tools.Error = Tools._ErrorEnabled;
  6282. }
  6283. else {
  6284. Tools.Error = Tools._ErrorDisabled;
  6285. }
  6286. },
  6287. enumerable: true,
  6288. configurable: true
  6289. });
  6290. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6291. get: function () {
  6292. return Tools._PerformanceNoneLogLevel;
  6293. },
  6294. enumerable: true,
  6295. configurable: true
  6296. });
  6297. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6298. get: function () {
  6299. return Tools._PerformanceUserMarkLogLevel;
  6300. },
  6301. enumerable: true,
  6302. configurable: true
  6303. });
  6304. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6305. get: function () {
  6306. return Tools._PerformanceConsoleLogLevel;
  6307. },
  6308. enumerable: true,
  6309. configurable: true
  6310. });
  6311. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6312. set: function (level) {
  6313. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6314. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6315. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6316. return;
  6317. }
  6318. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6319. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6320. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6321. return;
  6322. }
  6323. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6324. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6325. },
  6326. enumerable: true,
  6327. configurable: true
  6328. });
  6329. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6330. };
  6331. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6332. };
  6333. Tools._StartUserMark = function (counterName, condition) {
  6334. if (condition === void 0) { condition = true; }
  6335. if (!condition || !Tools._performance.mark) {
  6336. return;
  6337. }
  6338. Tools._performance.mark(counterName + "-Begin");
  6339. };
  6340. Tools._EndUserMark = function (counterName, condition) {
  6341. if (condition === void 0) { condition = true; }
  6342. if (!condition || !Tools._performance.mark) {
  6343. return;
  6344. }
  6345. Tools._performance.mark(counterName + "-End");
  6346. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6347. };
  6348. Tools._StartPerformanceConsole = function (counterName, condition) {
  6349. if (condition === void 0) { condition = true; }
  6350. if (!condition) {
  6351. return;
  6352. }
  6353. Tools._StartUserMark(counterName, condition);
  6354. if (console.time) {
  6355. console.time(counterName);
  6356. }
  6357. };
  6358. Tools._EndPerformanceConsole = function (counterName, condition) {
  6359. if (condition === void 0) { condition = true; }
  6360. if (!condition) {
  6361. return;
  6362. }
  6363. Tools._EndUserMark(counterName, condition);
  6364. if (console.time) {
  6365. console.timeEnd(counterName);
  6366. }
  6367. };
  6368. Object.defineProperty(Tools, "Now", {
  6369. get: function () {
  6370. if (window.performance && window.performance.now) {
  6371. return window.performance.now();
  6372. }
  6373. return new Date().getTime();
  6374. },
  6375. enumerable: true,
  6376. configurable: true
  6377. });
  6378. /**
  6379. * This method will return the name of the class used to create the instance of the given object.
  6380. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6381. * @param object the object to get the class name from
  6382. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6383. */
  6384. Tools.GetClassName = function (object, isType) {
  6385. if (isType === void 0) { isType = false; }
  6386. var name = null;
  6387. if (!isType && object.getClassName) {
  6388. name = object.getClassName();
  6389. }
  6390. else {
  6391. if (object instanceof Object) {
  6392. var classObj = isType ? object : Object.getPrototypeOf(object);
  6393. name = classObj.constructor["__bjsclassName__"];
  6394. }
  6395. if (!name) {
  6396. name = typeof object;
  6397. }
  6398. }
  6399. return name;
  6400. };
  6401. Tools.first = function (array, predicate) {
  6402. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6403. var el = array_1[_i];
  6404. if (predicate(el)) {
  6405. return el;
  6406. }
  6407. }
  6408. };
  6409. /**
  6410. * This method will return the name of the full name of the class, including its owning module (if any).
  6411. * 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).
  6412. * @param object the object to get the class name from
  6413. * @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.
  6414. */
  6415. Tools.getFullClassName = function (object, isType) {
  6416. if (isType === void 0) { isType = false; }
  6417. var className = null;
  6418. var moduleName = null;
  6419. if (!isType && object.getClassName) {
  6420. className = object.getClassName();
  6421. }
  6422. else {
  6423. if (object instanceof Object) {
  6424. var classObj = isType ? object : Object.getPrototypeOf(object);
  6425. className = classObj.constructor["__bjsclassName__"];
  6426. moduleName = classObj.constructor["__bjsmoduleName__"];
  6427. }
  6428. if (!className) {
  6429. className = typeof object;
  6430. }
  6431. }
  6432. if (!className) {
  6433. return null;
  6434. }
  6435. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6436. };
  6437. /**
  6438. * 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.
  6439. * @param array
  6440. */
  6441. Tools.arrayOrStringFeeder = function (array) {
  6442. return function (index) {
  6443. if (index >= array.length) {
  6444. return null;
  6445. }
  6446. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6447. if (val && val.getHashCode) {
  6448. val = val.getHashCode();
  6449. }
  6450. if (typeof val === "string") {
  6451. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6452. }
  6453. return val;
  6454. };
  6455. };
  6456. /**
  6457. * Compute the hashCode of a stream of number
  6458. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6459. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6460. * @return the hash code computed
  6461. */
  6462. Tools.hashCodeFromStream = function (feeder) {
  6463. // Based from here: http://stackoverflow.com/a/7616484/802124
  6464. var hash = 0;
  6465. var index = 0;
  6466. var chr = feeder(index++);
  6467. while (chr != null) {
  6468. hash = ((hash << 5) - hash) + chr;
  6469. hash |= 0; // Convert to 32bit integer
  6470. chr = feeder(index++);
  6471. }
  6472. return hash;
  6473. };
  6474. Tools.BaseUrl = "";
  6475. Tools.CorsBehavior = "anonymous";
  6476. Tools.UseFallbackTexture = true;
  6477. // Used in case of a texture loading problem
  6478. 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";
  6479. Tools.PreprocessUrl = function (url) {
  6480. return url;
  6481. };
  6482. // Logs
  6483. Tools._NoneLogLevel = 0;
  6484. Tools._MessageLogLevel = 1;
  6485. Tools._WarningLogLevel = 2;
  6486. Tools._ErrorLogLevel = 4;
  6487. Tools._LogCache = "";
  6488. Tools.errorsCount = 0;
  6489. Tools.Log = Tools._LogEnabled;
  6490. Tools.Warn = Tools._WarnEnabled;
  6491. Tools.Error = Tools._ErrorEnabled;
  6492. // Performances
  6493. Tools._PerformanceNoneLogLevel = 0;
  6494. Tools._PerformanceUserMarkLogLevel = 1;
  6495. Tools._PerformanceConsoleLogLevel = 2;
  6496. Tools._performance = window.performance;
  6497. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6498. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6499. return Tools;
  6500. }());
  6501. BABYLON.Tools = Tools;
  6502. /**
  6503. * This class is used to track a performance counter which is number based.
  6504. * The user has access to many properties which give statistics of different nature
  6505. *
  6506. * The implementer can track two kinds of Performance Counter: time and count
  6507. * 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.
  6508. * 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.
  6509. */
  6510. var PerfCounter = (function () {
  6511. function PerfCounter() {
  6512. this._startMonitoringTime = 0;
  6513. this._min = 0;
  6514. this._max = 0;
  6515. this._average = 0;
  6516. this._lastSecAverage = 0;
  6517. this._current = 0;
  6518. this._totalValueCount = 0;
  6519. this._totalAccumulated = 0;
  6520. this._lastSecAccumulated = 0;
  6521. this._lastSecTime = 0;
  6522. this._lastSecValueCount = 0;
  6523. }
  6524. Object.defineProperty(PerfCounter.prototype, "min", {
  6525. /**
  6526. * Returns the smallest value ever
  6527. */
  6528. get: function () {
  6529. return this._min;
  6530. },
  6531. enumerable: true,
  6532. configurable: true
  6533. });
  6534. Object.defineProperty(PerfCounter.prototype, "max", {
  6535. /**
  6536. * Returns the biggest value ever
  6537. */
  6538. get: function () {
  6539. return this._max;
  6540. },
  6541. enumerable: true,
  6542. configurable: true
  6543. });
  6544. Object.defineProperty(PerfCounter.prototype, "average", {
  6545. /**
  6546. * Returns the average value since the performance counter is running
  6547. */
  6548. get: function () {
  6549. return this._average;
  6550. },
  6551. enumerable: true,
  6552. configurable: true
  6553. });
  6554. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6555. /**
  6556. * Returns the average value of the last second the counter was monitored
  6557. */
  6558. get: function () {
  6559. return this._lastSecAverage;
  6560. },
  6561. enumerable: true,
  6562. configurable: true
  6563. });
  6564. Object.defineProperty(PerfCounter.prototype, "current", {
  6565. /**
  6566. * Returns the current value
  6567. */
  6568. get: function () {
  6569. return this._current;
  6570. },
  6571. enumerable: true,
  6572. configurable: true
  6573. });
  6574. Object.defineProperty(PerfCounter.prototype, "total", {
  6575. get: function () {
  6576. return this._totalAccumulated;
  6577. },
  6578. enumerable: true,
  6579. configurable: true
  6580. });
  6581. /**
  6582. * Call this method to start monitoring a new frame.
  6583. * 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.
  6584. */
  6585. PerfCounter.prototype.fetchNewFrame = function () {
  6586. this._totalValueCount++;
  6587. this._current = 0;
  6588. this._lastSecValueCount++;
  6589. };
  6590. /**
  6591. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6592. * @param newCount the count value to add to the monitored count
  6593. * @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.
  6594. */
  6595. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6596. if (!PerfCounter.Enabled) {
  6597. return;
  6598. }
  6599. this._current += newCount;
  6600. if (fetchResult) {
  6601. this._fetchResult();
  6602. }
  6603. };
  6604. /**
  6605. * Start monitoring this performance counter
  6606. */
  6607. PerfCounter.prototype.beginMonitoring = function () {
  6608. if (!PerfCounter.Enabled) {
  6609. return;
  6610. }
  6611. this._startMonitoringTime = Tools.Now;
  6612. };
  6613. /**
  6614. * Compute the time lapsed since the previous beginMonitoring() call.
  6615. * @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
  6616. */
  6617. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6618. if (newFrame === void 0) { newFrame = true; }
  6619. if (!PerfCounter.Enabled) {
  6620. return;
  6621. }
  6622. if (newFrame) {
  6623. this.fetchNewFrame();
  6624. }
  6625. var currentTime = Tools.Now;
  6626. this._current = currentTime - this._startMonitoringTime;
  6627. if (newFrame) {
  6628. this._fetchResult();
  6629. }
  6630. };
  6631. PerfCounter.prototype._fetchResult = function () {
  6632. this._totalAccumulated += this._current;
  6633. this._lastSecAccumulated += this._current;
  6634. // Min/Max update
  6635. this._min = Math.min(this._min, this._current);
  6636. this._max = Math.max(this._max, this._current);
  6637. this._average = this._totalAccumulated / this._totalValueCount;
  6638. // Reset last sec?
  6639. var now = Tools.Now;
  6640. if ((now - this._lastSecTime) > 1000) {
  6641. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6642. this._lastSecTime = now;
  6643. this._lastSecAccumulated = 0;
  6644. this._lastSecValueCount = 0;
  6645. }
  6646. };
  6647. PerfCounter.Enabled = true;
  6648. return PerfCounter;
  6649. }());
  6650. BABYLON.PerfCounter = PerfCounter;
  6651. /**
  6652. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6653. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6654. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6655. * @param name The name of the class, case should be preserved
  6656. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6657. */
  6658. function className(name, module) {
  6659. return function (target) {
  6660. target["__bjsclassName__"] = name;
  6661. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6662. };
  6663. }
  6664. BABYLON.className = className;
  6665. /**
  6666. * An implementation of a loop for asynchronous functions.
  6667. */
  6668. var AsyncLoop = (function () {
  6669. /**
  6670. * Constroctor.
  6671. * @param iterations the number of iterations.
  6672. * @param _fn the function to run each iteration
  6673. * @param _successCallback the callback that will be called upon succesful execution
  6674. * @param offset starting offset.
  6675. */
  6676. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6677. if (offset === void 0) { offset = 0; }
  6678. this.iterations = iterations;
  6679. this._fn = _fn;
  6680. this._successCallback = _successCallback;
  6681. this.index = offset - 1;
  6682. this._done = false;
  6683. }
  6684. /**
  6685. * Execute the next iteration. Must be called after the last iteration was finished.
  6686. */
  6687. AsyncLoop.prototype.executeNext = function () {
  6688. if (!this._done) {
  6689. if (this.index + 1 < this.iterations) {
  6690. ++this.index;
  6691. this._fn(this);
  6692. }
  6693. else {
  6694. this.breakLoop();
  6695. }
  6696. }
  6697. };
  6698. /**
  6699. * Break the loop and run the success callback.
  6700. */
  6701. AsyncLoop.prototype.breakLoop = function () {
  6702. this._done = true;
  6703. this._successCallback();
  6704. };
  6705. /**
  6706. * Helper function
  6707. */
  6708. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6709. if (offset === void 0) { offset = 0; }
  6710. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6711. loop.executeNext();
  6712. return loop;
  6713. };
  6714. /**
  6715. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6716. * @param iterations total number of iterations
  6717. * @param syncedIterations number of synchronous iterations in each async iteration.
  6718. * @param fn the function to call each iteration.
  6719. * @param callback a success call back that will be called when iterating stops.
  6720. * @param breakFunction a break condition (optional)
  6721. * @param timeout timeout settings for the setTimeout function. default - 0.
  6722. * @constructor
  6723. */
  6724. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6725. if (timeout === void 0) { timeout = 0; }
  6726. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6727. if (breakFunction && breakFunction())
  6728. loop.breakLoop();
  6729. else {
  6730. setTimeout(function () {
  6731. for (var i = 0; i < syncedIterations; ++i) {
  6732. var iteration = (loop.index * syncedIterations) + i;
  6733. if (iteration >= iterations)
  6734. break;
  6735. fn(iteration);
  6736. if (breakFunction && breakFunction()) {
  6737. loop.breakLoop();
  6738. break;
  6739. }
  6740. }
  6741. loop.executeNext();
  6742. }, timeout);
  6743. }
  6744. }, callback);
  6745. };
  6746. return AsyncLoop;
  6747. }());
  6748. BABYLON.AsyncLoop = AsyncLoop;
  6749. })(BABYLON || (BABYLON = {}));
  6750. //# sourceMappingURL=babylon.tools.js.map
  6751. var BABYLON;
  6752. (function (BABYLON) {
  6753. var Internals;
  6754. (function (Internals) {
  6755. var _AlphaState = (function () {
  6756. /**
  6757. * Initializes the state.
  6758. */
  6759. function _AlphaState() {
  6760. this._isAlphaBlendDirty = false;
  6761. this._isBlendFunctionParametersDirty = false;
  6762. this._isBlendEquationParametersDirty = false;
  6763. this._isBlendConstantsDirty = false;
  6764. this._alphaBlend = false;
  6765. this._blendFunctionParameters = new Array(4);
  6766. this._blendEquationParameters = new Array(2);
  6767. this._blendConstants = new Array(4);
  6768. this.reset();
  6769. }
  6770. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6771. get: function () {
  6772. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6773. },
  6774. enumerable: true,
  6775. configurable: true
  6776. });
  6777. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6778. get: function () {
  6779. return this._alphaBlend;
  6780. },
  6781. set: function (value) {
  6782. if (this._alphaBlend === value) {
  6783. return;
  6784. }
  6785. this._alphaBlend = value;
  6786. this._isAlphaBlendDirty = true;
  6787. },
  6788. enumerable: true,
  6789. configurable: true
  6790. });
  6791. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6792. if (this._blendConstants[0] === r &&
  6793. this._blendConstants[1] === g &&
  6794. this._blendConstants[2] === b &&
  6795. this._blendConstants[3] === a) {
  6796. return;
  6797. }
  6798. this._blendConstants[0] = r;
  6799. this._blendConstants[1] = g;
  6800. this._blendConstants[2] = b;
  6801. this._blendConstants[3] = a;
  6802. this._isBlendConstantsDirty = true;
  6803. };
  6804. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6805. if (this._blendFunctionParameters[0] === value0 &&
  6806. this._blendFunctionParameters[1] === value1 &&
  6807. this._blendFunctionParameters[2] === value2 &&
  6808. this._blendFunctionParameters[3] === value3) {
  6809. return;
  6810. }
  6811. this._blendFunctionParameters[0] = value0;
  6812. this._blendFunctionParameters[1] = value1;
  6813. this._blendFunctionParameters[2] = value2;
  6814. this._blendFunctionParameters[3] = value3;
  6815. this._isBlendFunctionParametersDirty = true;
  6816. };
  6817. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6818. if (this._blendEquationParameters[0] === rgb &&
  6819. this._blendEquationParameters[1] === alpha) {
  6820. return;
  6821. }
  6822. this._blendEquationParameters[0] = rgb;
  6823. this._blendEquationParameters[1] = alpha;
  6824. this._isBlendEquationParametersDirty = true;
  6825. };
  6826. _AlphaState.prototype.reset = function () {
  6827. this._alphaBlend = false;
  6828. this._blendFunctionParameters[0] = null;
  6829. this._blendFunctionParameters[1] = null;
  6830. this._blendFunctionParameters[2] = null;
  6831. this._blendFunctionParameters[3] = null;
  6832. this._blendEquationParameters[0] = null;
  6833. this._blendEquationParameters[1] = null;
  6834. this._blendConstants[0] = null;
  6835. this._blendConstants[1] = null;
  6836. this._blendConstants[2] = null;
  6837. this._blendConstants[3] = null;
  6838. this._isAlphaBlendDirty = true;
  6839. this._isBlendFunctionParametersDirty = false;
  6840. this._isBlendEquationParametersDirty = false;
  6841. this._isBlendConstantsDirty = false;
  6842. };
  6843. _AlphaState.prototype.apply = function (gl) {
  6844. if (!this.isDirty) {
  6845. return;
  6846. }
  6847. // Alpha blend
  6848. if (this._isAlphaBlendDirty) {
  6849. if (this._alphaBlend) {
  6850. gl.enable(gl.BLEND);
  6851. }
  6852. else {
  6853. gl.disable(gl.BLEND);
  6854. }
  6855. this._isAlphaBlendDirty = false;
  6856. }
  6857. // Alpha function
  6858. if (this._isBlendFunctionParametersDirty) {
  6859. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6860. this._isBlendFunctionParametersDirty = false;
  6861. }
  6862. // Alpha equation
  6863. if (this._isBlendEquationParametersDirty) {
  6864. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6865. this._isBlendEquationParametersDirty = false;
  6866. }
  6867. // Constants
  6868. if (this._isBlendConstantsDirty) {
  6869. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6870. this._isBlendConstantsDirty = false;
  6871. }
  6872. };
  6873. return _AlphaState;
  6874. }());
  6875. Internals._AlphaState = _AlphaState;
  6876. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6877. })(BABYLON || (BABYLON = {}));
  6878. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6879. var BABYLON;
  6880. (function (BABYLON) {
  6881. var Internals;
  6882. (function (Internals) {
  6883. var _DepthCullingState = (function () {
  6884. /**
  6885. * Initializes the state.
  6886. */
  6887. function _DepthCullingState() {
  6888. this._isDepthTestDirty = false;
  6889. this._isDepthMaskDirty = false;
  6890. this._isDepthFuncDirty = false;
  6891. this._isCullFaceDirty = false;
  6892. this._isCullDirty = false;
  6893. this._isZOffsetDirty = false;
  6894. this.reset();
  6895. }
  6896. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6897. get: function () {
  6898. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6899. },
  6900. enumerable: true,
  6901. configurable: true
  6902. });
  6903. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6904. get: function () {
  6905. return this._zOffset;
  6906. },
  6907. set: function (value) {
  6908. if (this._zOffset === value) {
  6909. return;
  6910. }
  6911. this._zOffset = value;
  6912. this._isZOffsetDirty = true;
  6913. },
  6914. enumerable: true,
  6915. configurable: true
  6916. });
  6917. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6918. get: function () {
  6919. return this._cullFace;
  6920. },
  6921. set: function (value) {
  6922. if (this._cullFace === value) {
  6923. return;
  6924. }
  6925. this._cullFace = value;
  6926. this._isCullFaceDirty = true;
  6927. },
  6928. enumerable: true,
  6929. configurable: true
  6930. });
  6931. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6932. get: function () {
  6933. return this._cull;
  6934. },
  6935. set: function (value) {
  6936. if (this._cull === value) {
  6937. return;
  6938. }
  6939. this._cull = value;
  6940. this._isCullDirty = true;
  6941. },
  6942. enumerable: true,
  6943. configurable: true
  6944. });
  6945. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6946. get: function () {
  6947. return this._depthFunc;
  6948. },
  6949. set: function (value) {
  6950. if (this._depthFunc === value) {
  6951. return;
  6952. }
  6953. this._depthFunc = value;
  6954. this._isDepthFuncDirty = true;
  6955. },
  6956. enumerable: true,
  6957. configurable: true
  6958. });
  6959. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6960. get: function () {
  6961. return this._depthMask;
  6962. },
  6963. set: function (value) {
  6964. if (this._depthMask === value) {
  6965. return;
  6966. }
  6967. this._depthMask = value;
  6968. this._isDepthMaskDirty = true;
  6969. },
  6970. enumerable: true,
  6971. configurable: true
  6972. });
  6973. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6974. get: function () {
  6975. return this._depthTest;
  6976. },
  6977. set: function (value) {
  6978. if (this._depthTest === value) {
  6979. return;
  6980. }
  6981. this._depthTest = value;
  6982. this._isDepthTestDirty = true;
  6983. },
  6984. enumerable: true,
  6985. configurable: true
  6986. });
  6987. _DepthCullingState.prototype.reset = function () {
  6988. this._depthMask = true;
  6989. this._depthTest = true;
  6990. this._depthFunc = null;
  6991. this._cullFace = null;
  6992. this._cull = null;
  6993. this._zOffset = 0;
  6994. this._isDepthTestDirty = true;
  6995. this._isDepthMaskDirty = true;
  6996. this._isDepthFuncDirty = false;
  6997. this._isCullFaceDirty = false;
  6998. this._isCullDirty = false;
  6999. this._isZOffsetDirty = false;
  7000. };
  7001. _DepthCullingState.prototype.apply = function (gl) {
  7002. if (!this.isDirty) {
  7003. return;
  7004. }
  7005. // Cull
  7006. if (this._isCullDirty) {
  7007. if (this.cull) {
  7008. gl.enable(gl.CULL_FACE);
  7009. }
  7010. else {
  7011. gl.disable(gl.CULL_FACE);
  7012. }
  7013. this._isCullDirty = false;
  7014. }
  7015. // Cull face
  7016. if (this._isCullFaceDirty) {
  7017. gl.cullFace(this.cullFace);
  7018. this._isCullFaceDirty = false;
  7019. }
  7020. // Depth mask
  7021. if (this._isDepthMaskDirty) {
  7022. gl.depthMask(this.depthMask);
  7023. this._isDepthMaskDirty = false;
  7024. }
  7025. // Depth test
  7026. if (this._isDepthTestDirty) {
  7027. if (this.depthTest) {
  7028. gl.enable(gl.DEPTH_TEST);
  7029. }
  7030. else {
  7031. gl.disable(gl.DEPTH_TEST);
  7032. }
  7033. this._isDepthTestDirty = false;
  7034. }
  7035. // Depth func
  7036. if (this._isDepthFuncDirty) {
  7037. gl.depthFunc(this.depthFunc);
  7038. this._isDepthFuncDirty = false;
  7039. }
  7040. // zOffset
  7041. if (this._isZOffsetDirty) {
  7042. if (this.zOffset) {
  7043. gl.enable(gl.POLYGON_OFFSET_FILL);
  7044. gl.polygonOffset(this.zOffset, 0);
  7045. }
  7046. else {
  7047. gl.disable(gl.POLYGON_OFFSET_FILL);
  7048. }
  7049. this._isZOffsetDirty = false;
  7050. }
  7051. };
  7052. return _DepthCullingState;
  7053. }());
  7054. Internals._DepthCullingState = _DepthCullingState;
  7055. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7056. })(BABYLON || (BABYLON = {}));
  7057. //# sourceMappingURL=babylon.depthCullingState.js.map
  7058. var BABYLON;
  7059. (function (BABYLON) {
  7060. var Internals;
  7061. (function (Internals) {
  7062. var _StencilState = (function () {
  7063. function _StencilState() {
  7064. this._isStencilTestDirty = false;
  7065. this._isStencilMaskDirty = false;
  7066. this._isStencilFuncDirty = false;
  7067. this._isStencilOpDirty = false;
  7068. this.reset();
  7069. }
  7070. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7071. get: function () {
  7072. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7073. },
  7074. enumerable: true,
  7075. configurable: true
  7076. });
  7077. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7078. get: function () {
  7079. return this._stencilFunc;
  7080. },
  7081. set: function (value) {
  7082. if (this._stencilFunc === value) {
  7083. return;
  7084. }
  7085. this._stencilFunc = value;
  7086. this._isStencilFuncDirty = true;
  7087. },
  7088. enumerable: true,
  7089. configurable: true
  7090. });
  7091. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7092. get: function () {
  7093. return this._stencilFuncRef;
  7094. },
  7095. set: function (value) {
  7096. if (this._stencilFuncRef === value) {
  7097. return;
  7098. }
  7099. this._stencilFuncRef = value;
  7100. this._isStencilFuncDirty = true;
  7101. },
  7102. enumerable: true,
  7103. configurable: true
  7104. });
  7105. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7106. get: function () {
  7107. return this._stencilFuncMask;
  7108. },
  7109. set: function (value) {
  7110. if (this._stencilFuncMask === value) {
  7111. return;
  7112. }
  7113. this._stencilFuncMask = value;
  7114. this._isStencilFuncDirty = true;
  7115. },
  7116. enumerable: true,
  7117. configurable: true
  7118. });
  7119. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7120. get: function () {
  7121. return this._stencilOpStencilFail;
  7122. },
  7123. set: function (value) {
  7124. if (this._stencilOpStencilFail === value) {
  7125. return;
  7126. }
  7127. this._stencilOpStencilFail = value;
  7128. this._isStencilOpDirty = true;
  7129. },
  7130. enumerable: true,
  7131. configurable: true
  7132. });
  7133. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7134. get: function () {
  7135. return this._stencilOpDepthFail;
  7136. },
  7137. set: function (value) {
  7138. if (this._stencilOpDepthFail === value) {
  7139. return;
  7140. }
  7141. this._stencilOpDepthFail = value;
  7142. this._isStencilOpDirty = true;
  7143. },
  7144. enumerable: true,
  7145. configurable: true
  7146. });
  7147. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7148. get: function () {
  7149. return this._stencilOpStencilDepthPass;
  7150. },
  7151. set: function (value) {
  7152. if (this._stencilOpStencilDepthPass === value) {
  7153. return;
  7154. }
  7155. this._stencilOpStencilDepthPass = value;
  7156. this._isStencilOpDirty = true;
  7157. },
  7158. enumerable: true,
  7159. configurable: true
  7160. });
  7161. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7162. get: function () {
  7163. return this._stencilMask;
  7164. },
  7165. set: function (value) {
  7166. if (this._stencilMask === value) {
  7167. return;
  7168. }
  7169. this._stencilMask = value;
  7170. this._isStencilMaskDirty = true;
  7171. },
  7172. enumerable: true,
  7173. configurable: true
  7174. });
  7175. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7176. get: function () {
  7177. return this._stencilTest;
  7178. },
  7179. set: function (value) {
  7180. if (this._stencilTest === value) {
  7181. return;
  7182. }
  7183. this._stencilTest = value;
  7184. this._isStencilTestDirty = true;
  7185. },
  7186. enumerable: true,
  7187. configurable: true
  7188. });
  7189. _StencilState.prototype.reset = function () {
  7190. this._stencilTest = false;
  7191. this._stencilMask = 0xFF;
  7192. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7193. this._stencilFuncRef = 1;
  7194. this._stencilFuncMask = 0xFF;
  7195. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7196. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7197. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7198. this._isStencilTestDirty = true;
  7199. this._isStencilMaskDirty = true;
  7200. this._isStencilFuncDirty = true;
  7201. this._isStencilOpDirty = true;
  7202. };
  7203. _StencilState.prototype.apply = function (gl) {
  7204. if (!this.isDirty) {
  7205. return;
  7206. }
  7207. // Stencil test
  7208. if (this._isStencilTestDirty) {
  7209. if (this.stencilTest) {
  7210. gl.enable(gl.STENCIL_TEST);
  7211. }
  7212. else {
  7213. gl.disable(gl.STENCIL_TEST);
  7214. }
  7215. this._isStencilTestDirty = false;
  7216. }
  7217. // Stencil mask
  7218. if (this._isStencilMaskDirty) {
  7219. gl.stencilMask(this.stencilMask);
  7220. this._isStencilMaskDirty = false;
  7221. }
  7222. // Stencil func
  7223. if (this._isStencilFuncDirty) {
  7224. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7225. this._isStencilFuncDirty = false;
  7226. }
  7227. // Stencil op
  7228. if (this._isStencilOpDirty) {
  7229. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7230. this._isStencilOpDirty = false;
  7231. }
  7232. };
  7233. return _StencilState;
  7234. }());
  7235. Internals._StencilState = _StencilState;
  7236. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7237. })(BABYLON || (BABYLON = {}));
  7238. //# sourceMappingURL=babylon.stencilState.js.map
  7239. var BABYLON;
  7240. (function (BABYLON) {
  7241. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7242. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7243. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7244. gl.compileShader(shader);
  7245. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7246. throw new Error(gl.getShaderInfoLog(shader));
  7247. }
  7248. return shader;
  7249. };
  7250. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7251. var magFilter = gl.NEAREST;
  7252. var minFilter = gl.NEAREST;
  7253. switch (samplingMode) {
  7254. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7255. magFilter = gl.LINEAR;
  7256. if (generateMipMaps) {
  7257. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7258. }
  7259. else {
  7260. minFilter = gl.LINEAR;
  7261. }
  7262. break;
  7263. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7264. magFilter = gl.LINEAR;
  7265. if (generateMipMaps) {
  7266. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7267. }
  7268. else {
  7269. minFilter = gl.LINEAR;
  7270. }
  7271. break;
  7272. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7273. magFilter = gl.NEAREST;
  7274. if (generateMipMaps) {
  7275. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7276. }
  7277. else {
  7278. minFilter = gl.NEAREST;
  7279. }
  7280. break;
  7281. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7282. magFilter = gl.NEAREST;
  7283. if (generateMipMaps) {
  7284. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7285. }
  7286. else {
  7287. minFilter = gl.NEAREST;
  7288. }
  7289. break;
  7290. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7291. magFilter = gl.NEAREST;
  7292. if (generateMipMaps) {
  7293. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7294. }
  7295. else {
  7296. minFilter = gl.LINEAR;
  7297. }
  7298. break;
  7299. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7300. magFilter = gl.NEAREST;
  7301. if (generateMipMaps) {
  7302. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7303. }
  7304. else {
  7305. minFilter = gl.LINEAR;
  7306. }
  7307. break;
  7308. case BABYLON.Texture.NEAREST_LINEAR:
  7309. magFilter = gl.NEAREST;
  7310. minFilter = gl.LINEAR;
  7311. break;
  7312. case BABYLON.Texture.NEAREST_NEAREST:
  7313. magFilter = gl.NEAREST;
  7314. minFilter = gl.NEAREST;
  7315. break;
  7316. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7317. magFilter = gl.LINEAR;
  7318. if (generateMipMaps) {
  7319. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7320. }
  7321. else {
  7322. minFilter = gl.NEAREST;
  7323. }
  7324. break;
  7325. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7326. magFilter = gl.LINEAR;
  7327. if (generateMipMaps) {
  7328. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7329. }
  7330. else {
  7331. minFilter = gl.NEAREST;
  7332. }
  7333. break;
  7334. case BABYLON.Texture.LINEAR_LINEAR:
  7335. magFilter = gl.LINEAR;
  7336. minFilter = gl.LINEAR;
  7337. break;
  7338. case BABYLON.Texture.LINEAR_NEAREST:
  7339. magFilter = gl.LINEAR;
  7340. minFilter = gl.NEAREST;
  7341. break;
  7342. }
  7343. return {
  7344. min: minFilter,
  7345. mag: magFilter
  7346. };
  7347. };
  7348. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7349. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7350. var img;
  7351. var onload = function () {
  7352. loadedImages[index] = img;
  7353. loadedImages._internalCount++;
  7354. if (scene) {
  7355. scene._removePendingData(img);
  7356. }
  7357. if (loadedImages._internalCount === 6) {
  7358. onfinish(loadedImages);
  7359. }
  7360. };
  7361. var onerror = function () {
  7362. if (scene) {
  7363. scene._removePendingData(img);
  7364. }
  7365. if (onErrorCallBack) {
  7366. onErrorCallBack();
  7367. }
  7368. };
  7369. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7370. if (scene) {
  7371. scene._addPendingData(img);
  7372. }
  7373. };
  7374. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7375. if (onError === void 0) { onError = null; }
  7376. var loadedImages = [];
  7377. loadedImages._internalCount = 0;
  7378. for (var index = 0; index < 6; index++) {
  7379. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7380. }
  7381. };
  7382. var BufferPointer = (function () {
  7383. function BufferPointer() {
  7384. }
  7385. return BufferPointer;
  7386. }());
  7387. var InstancingAttributeInfo = (function () {
  7388. function InstancingAttributeInfo() {
  7389. }
  7390. return InstancingAttributeInfo;
  7391. }());
  7392. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7393. /**
  7394. * Define options used to create a render target texture
  7395. */
  7396. var RenderTargetCreationOptions = (function () {
  7397. function RenderTargetCreationOptions() {
  7398. }
  7399. return RenderTargetCreationOptions;
  7400. }());
  7401. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7402. /**
  7403. * Regroup several parameters relative to the browser in use
  7404. */
  7405. var EngineCapabilities = (function () {
  7406. function EngineCapabilities() {
  7407. }
  7408. return EngineCapabilities;
  7409. }());
  7410. BABYLON.EngineCapabilities = EngineCapabilities;
  7411. /**
  7412. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7413. */
  7414. var Engine = (function () {
  7415. /**
  7416. * @constructor
  7417. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7418. * @param {boolean} [antialias] - enable antialias
  7419. * @param options - further options to be sent to the getContext function
  7420. */
  7421. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7422. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7423. var _this = this;
  7424. // Public members
  7425. this.forcePOTTextures = false;
  7426. this.isFullscreen = false;
  7427. this.isPointerLock = false;
  7428. this.cullBackFaces = true;
  7429. this.renderEvenInBackground = true;
  7430. this.preventCacheWipeBetweenFrames = false;
  7431. // To enable/disable IDB support and avoid XHR on .manifest
  7432. this.enableOfflineSupport = false;
  7433. this.scenes = new Array();
  7434. this.postProcesses = new Array();
  7435. // Observables
  7436. /**
  7437. * Observable event triggered each time the rendering canvas is resized
  7438. */
  7439. this.onResizeObservable = new BABYLON.Observable();
  7440. /**
  7441. * Observable event triggered each time the canvas lost focus
  7442. */
  7443. this.onCanvasBlurObservable = new BABYLON.Observable();
  7444. // Uniform buffers list
  7445. this._uniformBuffers = new Array();
  7446. this._windowIsBackground = false;
  7447. this._webGLVersion = 1.0;
  7448. this._badOS = false;
  7449. this._badDesktopOS = false;
  7450. this._drawCalls = new BABYLON.PerfCounter();
  7451. this._renderingQueueLaunched = false;
  7452. this._activeRenderLoops = [];
  7453. // Deterministic lockstepMaxSteps
  7454. this._deterministicLockstep = false;
  7455. this._lockstepMaxSteps = 4;
  7456. this._contextWasLost = false;
  7457. this._doNotHandleContextLost = false;
  7458. // FPS
  7459. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7460. this._fps = 60;
  7461. this._deltaTime = 0;
  7462. /**
  7463. * Turn this value on if you want to pause FPS computation when in background
  7464. */
  7465. this.disablePerformanceMonitorInBackground = false;
  7466. // States
  7467. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7468. this._stencilState = new BABYLON.Internals._StencilState();
  7469. this._alphaState = new BABYLON.Internals._AlphaState();
  7470. this._alphaMode = Engine.ALPHA_DISABLE;
  7471. // Cache
  7472. this._internalTexturesCache = new Array();
  7473. this._maxTextureChannels = 16;
  7474. this._activeTexturesCache = {};
  7475. this._compiledEffects = {};
  7476. this._vertexAttribArraysEnabled = [];
  7477. this._uintIndicesCurrentlySet = false;
  7478. this._currentBoundBuffer = new Array();
  7479. this._currentBufferPointers = new Array();
  7480. this._currentInstanceLocations = new Array();
  7481. this._currentInstanceBuffers = new Array();
  7482. this._vaoRecordInProgress = false;
  7483. this._mustWipeVertexAttributes = false;
  7484. // Hardware supported Compressed Textures
  7485. this._texturesSupported = new Array();
  7486. this._onVRFullScreenTriggered = function () {
  7487. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7488. //get the old size before we change
  7489. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7490. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7491. //get the width and height, change the render size
  7492. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7493. var width, height;
  7494. _this.setHardwareScalingLevel(1);
  7495. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7496. }
  7497. else {
  7498. //When the specs are implemented, need to uncomment this.
  7499. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7500. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7501. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7502. _this._vrDisplayEnabled = undefined;
  7503. }
  7504. };
  7505. var canvas;
  7506. Engine.Instances.push(this);
  7507. options = options || {};
  7508. if (canvasOrContext.getContext) {
  7509. canvas = canvasOrContext;
  7510. this._renderingCanvas = canvas;
  7511. if (antialias != null) {
  7512. options.antialias = antialias;
  7513. }
  7514. if (options.deterministicLockstep === undefined) {
  7515. options.deterministicLockstep = false;
  7516. }
  7517. if (options.lockstepMaxSteps === undefined) {
  7518. options.lockstepMaxSteps = 4;
  7519. }
  7520. if (options.preserveDrawingBuffer === undefined) {
  7521. options.preserveDrawingBuffer = false;
  7522. }
  7523. if (options.audioEngine === undefined) {
  7524. options.audioEngine = true;
  7525. }
  7526. if (options.stencil === undefined) {
  7527. options.stencil = true;
  7528. }
  7529. this._deterministicLockstep = options.deterministicLockstep;
  7530. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7531. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7532. // GL
  7533. if (!options.disableWebGL2Support) {
  7534. try {
  7535. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7536. if (this._gl) {
  7537. this._webGLVersion = 2.0;
  7538. }
  7539. }
  7540. catch (e) {
  7541. // Do nothing
  7542. }
  7543. }
  7544. if (!this._gl) {
  7545. if (!canvas) {
  7546. throw new Error("The provided canvas is null or undefined.");
  7547. }
  7548. try {
  7549. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7550. }
  7551. catch (e) {
  7552. throw new Error("WebGL not supported");
  7553. }
  7554. }
  7555. if (!this._gl) {
  7556. throw new Error("WebGL not supported");
  7557. }
  7558. this._onBlur = function () {
  7559. if (_this.disablePerformanceMonitorInBackground) {
  7560. _this._performanceMonitor.disable();
  7561. }
  7562. _this._windowIsBackground = true;
  7563. };
  7564. this._onFocus = function () {
  7565. if (_this.disablePerformanceMonitorInBackground) {
  7566. _this._performanceMonitor.enable();
  7567. }
  7568. _this._windowIsBackground = false;
  7569. };
  7570. this._onCanvasBlur = function () {
  7571. _this.onCanvasBlurObservable.notifyObservers(_this);
  7572. };
  7573. window.addEventListener("blur", this._onBlur);
  7574. window.addEventListener("focus", this._onFocus);
  7575. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7576. }
  7577. else {
  7578. this._gl = canvasOrContext;
  7579. this._renderingCanvas = this._gl.canvas;
  7580. if (this._gl.renderbufferStorageMultisample) {
  7581. this._webGLVersion = 2.0;
  7582. }
  7583. options.stencil = this._gl.getContextAttributes().stencil;
  7584. }
  7585. // Context lost
  7586. if (!this._doNotHandleContextLost) {
  7587. this._onContextLost = function (evt) {
  7588. evt.preventDefault();
  7589. _this._contextWasLost = true;
  7590. BABYLON.Tools.Warn("WebGL context lost.");
  7591. };
  7592. this._onContextRestored = function (evt) {
  7593. // Rebuild gl context
  7594. _this._initGLContext();
  7595. // Rebuild effects
  7596. _this._rebuildEffects();
  7597. // Rebuild textures
  7598. _this._rebuildInternalTextures();
  7599. // Rebuild buffers
  7600. _this._rebuildBuffers();
  7601. // Cache
  7602. _this.wipeCaches(true);
  7603. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7604. _this._contextWasLost = false;
  7605. };
  7606. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7607. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7608. }
  7609. // Viewport
  7610. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7611. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7612. this.resize();
  7613. this._isStencilEnable = options.stencil;
  7614. this._initGLContext();
  7615. if (canvas) {
  7616. // Fullscreen
  7617. this._onFullscreenChange = function () {
  7618. if (document.fullscreen !== undefined) {
  7619. _this.isFullscreen = document.fullscreen;
  7620. }
  7621. else if (document.mozFullScreen !== undefined) {
  7622. _this.isFullscreen = document.mozFullScreen;
  7623. }
  7624. else if (document.webkitIsFullScreen !== undefined) {
  7625. _this.isFullscreen = document.webkitIsFullScreen;
  7626. }
  7627. else if (document.msIsFullScreen !== undefined) {
  7628. _this.isFullscreen = document.msIsFullScreen;
  7629. }
  7630. // Pointer lock
  7631. if (_this.isFullscreen && _this._pointerLockRequested) {
  7632. canvas.requestPointerLock = canvas.requestPointerLock ||
  7633. canvas.msRequestPointerLock ||
  7634. canvas.mozRequestPointerLock ||
  7635. canvas.webkitRequestPointerLock;
  7636. if (canvas.requestPointerLock) {
  7637. canvas.requestPointerLock();
  7638. }
  7639. }
  7640. };
  7641. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7642. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7643. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7644. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7645. // Pointer lock
  7646. this._onPointerLockChange = function () {
  7647. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7648. document.webkitPointerLockElement === canvas ||
  7649. document.msPointerLockElement === canvas ||
  7650. document.pointerLockElement === canvas);
  7651. };
  7652. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7653. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7654. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7655. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7656. this._onVRDisplayPointerRestricted = function () {
  7657. canvas.requestPointerLock();
  7658. };
  7659. this._onVRDisplayPointerUnrestricted = function () {
  7660. document.exitPointerLock();
  7661. };
  7662. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7663. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7664. }
  7665. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7666. Engine.audioEngine = new BABYLON.AudioEngine();
  7667. }
  7668. // Prepare buffer pointers
  7669. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7670. this._currentBufferPointers[i] = new BufferPointer();
  7671. }
  7672. // Load WebVR Devices
  7673. if (options.autoEnableWebVR) {
  7674. this.initWebVR();
  7675. }
  7676. // Detect if we are running on a faulty buggy OS.
  7677. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7678. // Detect if we are running on a faulty buggy desktop OS.
  7679. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7680. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7681. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7682. }
  7683. Object.defineProperty(Engine, "LastCreatedEngine", {
  7684. get: function () {
  7685. if (Engine.Instances.length === 0) {
  7686. return null;
  7687. }
  7688. return Engine.Instances[Engine.Instances.length - 1];
  7689. },
  7690. enumerable: true,
  7691. configurable: true
  7692. });
  7693. Object.defineProperty(Engine, "LastCreatedScene", {
  7694. get: function () {
  7695. var lastCreatedEngine = Engine.LastCreatedEngine;
  7696. if (!lastCreatedEngine) {
  7697. return null;
  7698. }
  7699. if (lastCreatedEngine.scenes.length === 0) {
  7700. return null;
  7701. }
  7702. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7703. },
  7704. enumerable: true,
  7705. configurable: true
  7706. });
  7707. /**
  7708. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7709. */
  7710. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7711. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7712. var engine = Engine.Instances[engineIndex];
  7713. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7714. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7715. }
  7716. }
  7717. };
  7718. Object.defineProperty(Engine, "NEVER", {
  7719. get: function () {
  7720. return Engine._NEVER;
  7721. },
  7722. enumerable: true,
  7723. configurable: true
  7724. });
  7725. Object.defineProperty(Engine, "ALWAYS", {
  7726. get: function () {
  7727. return Engine._ALWAYS;
  7728. },
  7729. enumerable: true,
  7730. configurable: true
  7731. });
  7732. Object.defineProperty(Engine, "LESS", {
  7733. get: function () {
  7734. return Engine._LESS;
  7735. },
  7736. enumerable: true,
  7737. configurable: true
  7738. });
  7739. Object.defineProperty(Engine, "EQUAL", {
  7740. get: function () {
  7741. return Engine._EQUAL;
  7742. },
  7743. enumerable: true,
  7744. configurable: true
  7745. });
  7746. Object.defineProperty(Engine, "LEQUAL", {
  7747. get: function () {
  7748. return Engine._LEQUAL;
  7749. },
  7750. enumerable: true,
  7751. configurable: true
  7752. });
  7753. Object.defineProperty(Engine, "GREATER", {
  7754. get: function () {
  7755. return Engine._GREATER;
  7756. },
  7757. enumerable: true,
  7758. configurable: true
  7759. });
  7760. Object.defineProperty(Engine, "GEQUAL", {
  7761. get: function () {
  7762. return Engine._GEQUAL;
  7763. },
  7764. enumerable: true,
  7765. configurable: true
  7766. });
  7767. Object.defineProperty(Engine, "NOTEQUAL", {
  7768. get: function () {
  7769. return Engine._NOTEQUAL;
  7770. },
  7771. enumerable: true,
  7772. configurable: true
  7773. });
  7774. Object.defineProperty(Engine, "KEEP", {
  7775. get: function () {
  7776. return Engine._KEEP;
  7777. },
  7778. enumerable: true,
  7779. configurable: true
  7780. });
  7781. Object.defineProperty(Engine, "REPLACE", {
  7782. get: function () {
  7783. return Engine._REPLACE;
  7784. },
  7785. enumerable: true,
  7786. configurable: true
  7787. });
  7788. Object.defineProperty(Engine, "INCR", {
  7789. get: function () {
  7790. return Engine._INCR;
  7791. },
  7792. enumerable: true,
  7793. configurable: true
  7794. });
  7795. Object.defineProperty(Engine, "DECR", {
  7796. get: function () {
  7797. return Engine._DECR;
  7798. },
  7799. enumerable: true,
  7800. configurable: true
  7801. });
  7802. Object.defineProperty(Engine, "INVERT", {
  7803. get: function () {
  7804. return Engine._INVERT;
  7805. },
  7806. enumerable: true,
  7807. configurable: true
  7808. });
  7809. Object.defineProperty(Engine, "INCR_WRAP", {
  7810. get: function () {
  7811. return Engine._INCR_WRAP;
  7812. },
  7813. enumerable: true,
  7814. configurable: true
  7815. });
  7816. Object.defineProperty(Engine, "DECR_WRAP", {
  7817. get: function () {
  7818. return Engine._DECR_WRAP;
  7819. },
  7820. enumerable: true,
  7821. configurable: true
  7822. });
  7823. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7824. get: function () {
  7825. return Engine._ALPHA_DISABLE;
  7826. },
  7827. enumerable: true,
  7828. configurable: true
  7829. });
  7830. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7831. get: function () {
  7832. return Engine._ALPHA_ONEONE;
  7833. },
  7834. enumerable: true,
  7835. configurable: true
  7836. });
  7837. Object.defineProperty(Engine, "ALPHA_ADD", {
  7838. get: function () {
  7839. return Engine._ALPHA_ADD;
  7840. },
  7841. enumerable: true,
  7842. configurable: true
  7843. });
  7844. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7845. get: function () {
  7846. return Engine._ALPHA_COMBINE;
  7847. },
  7848. enumerable: true,
  7849. configurable: true
  7850. });
  7851. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7852. get: function () {
  7853. return Engine._ALPHA_SUBTRACT;
  7854. },
  7855. enumerable: true,
  7856. configurable: true
  7857. });
  7858. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7859. get: function () {
  7860. return Engine._ALPHA_MULTIPLY;
  7861. },
  7862. enumerable: true,
  7863. configurable: true
  7864. });
  7865. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7866. get: function () {
  7867. return Engine._ALPHA_MAXIMIZED;
  7868. },
  7869. enumerable: true,
  7870. configurable: true
  7871. });
  7872. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7873. get: function () {
  7874. return Engine._ALPHA_PREMULTIPLIED;
  7875. },
  7876. enumerable: true,
  7877. configurable: true
  7878. });
  7879. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7880. get: function () {
  7881. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7882. },
  7883. enumerable: true,
  7884. configurable: true
  7885. });
  7886. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7887. get: function () {
  7888. return Engine._ALPHA_INTERPOLATE;
  7889. },
  7890. enumerable: true,
  7891. configurable: true
  7892. });
  7893. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7894. get: function () {
  7895. return Engine._ALPHA_SCREENMODE;
  7896. },
  7897. enumerable: true,
  7898. configurable: true
  7899. });
  7900. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7901. get: function () {
  7902. return Engine._DELAYLOADSTATE_NONE;
  7903. },
  7904. enumerable: true,
  7905. configurable: true
  7906. });
  7907. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7908. get: function () {
  7909. return Engine._DELAYLOADSTATE_LOADED;
  7910. },
  7911. enumerable: true,
  7912. configurable: true
  7913. });
  7914. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7915. get: function () {
  7916. return Engine._DELAYLOADSTATE_LOADING;
  7917. },
  7918. enumerable: true,
  7919. configurable: true
  7920. });
  7921. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7922. get: function () {
  7923. return Engine._DELAYLOADSTATE_NOTLOADED;
  7924. },
  7925. enumerable: true,
  7926. configurable: true
  7927. });
  7928. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7929. get: function () {
  7930. return Engine._TEXTUREFORMAT_ALPHA;
  7931. },
  7932. enumerable: true,
  7933. configurable: true
  7934. });
  7935. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7936. get: function () {
  7937. return Engine._TEXTUREFORMAT_LUMINANCE;
  7938. },
  7939. enumerable: true,
  7940. configurable: true
  7941. });
  7942. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7943. get: function () {
  7944. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7945. },
  7946. enumerable: true,
  7947. configurable: true
  7948. });
  7949. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7950. get: function () {
  7951. return Engine._TEXTUREFORMAT_RGB;
  7952. },
  7953. enumerable: true,
  7954. configurable: true
  7955. });
  7956. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7957. get: function () {
  7958. return Engine._TEXTUREFORMAT_RGBA;
  7959. },
  7960. enumerable: true,
  7961. configurable: true
  7962. });
  7963. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7964. get: function () {
  7965. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7966. },
  7967. enumerable: true,
  7968. configurable: true
  7969. });
  7970. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7971. get: function () {
  7972. return Engine._TEXTURETYPE_FLOAT;
  7973. },
  7974. enumerable: true,
  7975. configurable: true
  7976. });
  7977. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7978. get: function () {
  7979. return Engine._TEXTURETYPE_HALF_FLOAT;
  7980. },
  7981. enumerable: true,
  7982. configurable: true
  7983. });
  7984. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7985. get: function () {
  7986. return Engine._SCALEMODE_FLOOR;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7992. get: function () {
  7993. return Engine._SCALEMODE_NEAREST;
  7994. },
  7995. enumerable: true,
  7996. configurable: true
  7997. });
  7998. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7999. get: function () {
  8000. return Engine._SCALEMODE_CEILING;
  8001. },
  8002. enumerable: true,
  8003. configurable: true
  8004. });
  8005. Object.defineProperty(Engine, "Version", {
  8006. get: function () {
  8007. return "3.1-alpha";
  8008. },
  8009. enumerable: true,
  8010. configurable: true
  8011. });
  8012. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8013. get: function () {
  8014. return this._webGLVersion < 2 || this.forcePOTTextures;
  8015. },
  8016. enumerable: true,
  8017. configurable: true
  8018. });
  8019. Object.defineProperty(Engine.prototype, "badOS", {
  8020. get: function () {
  8021. return this._badOS;
  8022. },
  8023. enumerable: true,
  8024. configurable: true
  8025. });
  8026. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8027. get: function () {
  8028. return this._badDesktopOS;
  8029. },
  8030. enumerable: true,
  8031. configurable: true
  8032. });
  8033. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8034. get: function () {
  8035. return this._performanceMonitor;
  8036. },
  8037. enumerable: true,
  8038. configurable: true
  8039. });
  8040. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8041. get: function () {
  8042. return this._texturesSupported;
  8043. },
  8044. enumerable: true,
  8045. configurable: true
  8046. });
  8047. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8048. get: function () {
  8049. return this._textureFormatInUse;
  8050. },
  8051. enumerable: true,
  8052. configurable: true
  8053. });
  8054. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8055. // Empty texture
  8056. get: function () {
  8057. if (!this._emptyTexture) {
  8058. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8059. }
  8060. return this._emptyTexture;
  8061. },
  8062. enumerable: true,
  8063. configurable: true
  8064. });
  8065. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8066. get: function () {
  8067. if (!this._emptyCubeTexture) {
  8068. var faceData = new Uint8Array(4);
  8069. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8070. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8071. }
  8072. return this._emptyCubeTexture;
  8073. },
  8074. enumerable: true,
  8075. configurable: true
  8076. });
  8077. Engine.prototype._rebuildInternalTextures = function () {
  8078. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8079. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8080. var internalTexture = currentState_1[_i];
  8081. internalTexture._rebuild();
  8082. }
  8083. };
  8084. Engine.prototype._rebuildEffects = function () {
  8085. for (var key in this._compiledEffects) {
  8086. var effect = this._compiledEffects[key];
  8087. effect._prepareEffect();
  8088. }
  8089. BABYLON.Effect.ResetCache();
  8090. };
  8091. Engine.prototype._rebuildBuffers = function () {
  8092. // Index / Vertex
  8093. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8094. var scene = _a[_i];
  8095. scene.resetCachedMaterial();
  8096. scene._rebuildGeometries();
  8097. scene._rebuildTextures();
  8098. }
  8099. // Uniforms
  8100. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8101. var uniformBuffer = _c[_b];
  8102. uniformBuffer._rebuild();
  8103. }
  8104. };
  8105. Engine.prototype._initGLContext = function () {
  8106. // Caps
  8107. this._caps = new EngineCapabilities();
  8108. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8109. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8110. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8111. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8112. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8113. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8114. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8115. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8116. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8117. // Infos
  8118. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8119. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8120. if (rendererInfo != null) {
  8121. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8122. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8123. }
  8124. if (!this._glVendor) {
  8125. this._glVendor = "Unknown vendor";
  8126. }
  8127. if (!this._glRenderer) {
  8128. this._glRenderer = "Unknown renderer";
  8129. }
  8130. // Constants
  8131. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8132. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8133. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8134. this._gl.DEPTH24_STENCIL8 = 35056;
  8135. // Extensions
  8136. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8137. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8138. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8139. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8140. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8141. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8142. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8143. 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');
  8144. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8145. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8146. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8147. this._caps.highPrecisionShaderSupported = true;
  8148. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8149. // Checks if some of the format renders first to allow the use of webgl inspector.
  8150. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8151. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8152. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8153. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8154. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8155. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8156. if (this._webGLVersion > 1) {
  8157. this._gl.HALF_FLOAT_OES = 0x140B;
  8158. }
  8159. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8160. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8161. // Vertex array object
  8162. if (this._webGLVersion > 1) {
  8163. this._caps.vertexArrayObject = true;
  8164. }
  8165. else {
  8166. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8167. if (vertexArrayObjectExtension != null) {
  8168. this._caps.vertexArrayObject = true;
  8169. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8170. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8171. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8172. }
  8173. else {
  8174. this._caps.vertexArrayObject = false;
  8175. }
  8176. }
  8177. // Instances count
  8178. if (this._webGLVersion > 1) {
  8179. this._caps.instancedArrays = true;
  8180. }
  8181. else {
  8182. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8183. if (instanceExtension != null) {
  8184. this._caps.instancedArrays = true;
  8185. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8186. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8187. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8188. }
  8189. else {
  8190. this._caps.instancedArrays = false;
  8191. }
  8192. }
  8193. // Intelligently add supported compressed formats in order to check for.
  8194. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8195. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8196. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8197. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8198. if (this._caps.astc)
  8199. this.texturesSupported.push('-astc.ktx');
  8200. if (this._caps.s3tc)
  8201. this.texturesSupported.push('-dxt.ktx');
  8202. if (this._caps.pvrtc)
  8203. this.texturesSupported.push('-pvrtc.ktx');
  8204. if (this._caps.etc2)
  8205. this.texturesSupported.push('-etc2.ktx');
  8206. if (this._caps.etc1)
  8207. this.texturesSupported.push('-etc1.ktx');
  8208. if (this._gl.getShaderPrecisionFormat) {
  8209. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8210. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8211. }
  8212. // Depth buffer
  8213. this.setDepthBuffer(true);
  8214. this.setDepthFunctionToLessOrEqual();
  8215. this.setDepthWrite(true);
  8216. };
  8217. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8218. get: function () {
  8219. return this._webGLVersion;
  8220. },
  8221. enumerable: true,
  8222. configurable: true
  8223. });
  8224. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8225. /**
  8226. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8227. */
  8228. get: function () {
  8229. return this._isStencilEnable;
  8230. },
  8231. enumerable: true,
  8232. configurable: true
  8233. });
  8234. Engine.prototype._prepareWorkingCanvas = function () {
  8235. if (this._workingCanvas) {
  8236. return;
  8237. }
  8238. this._workingCanvas = document.createElement("canvas");
  8239. this._workingContext = this._workingCanvas.getContext("2d");
  8240. };
  8241. Engine.prototype.resetTextureCache = function () {
  8242. for (var key in this._activeTexturesCache) {
  8243. this._activeTexturesCache[key] = null;
  8244. }
  8245. };
  8246. Engine.prototype.isDeterministicLockStep = function () {
  8247. return this._deterministicLockstep;
  8248. };
  8249. Engine.prototype.getLockstepMaxSteps = function () {
  8250. return this._lockstepMaxSteps;
  8251. };
  8252. Engine.prototype.getGlInfo = function () {
  8253. return {
  8254. vendor: this._glVendor,
  8255. renderer: this._glRenderer,
  8256. version: this._glVersion
  8257. };
  8258. };
  8259. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8260. if (useScreen === void 0) { useScreen = false; }
  8261. var viewport = camera.viewport;
  8262. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8263. };
  8264. Engine.prototype.getRenderWidth = function (useScreen) {
  8265. if (useScreen === void 0) { useScreen = false; }
  8266. if (!useScreen && this._currentRenderTarget) {
  8267. return this._currentRenderTarget.width;
  8268. }
  8269. return this._gl.drawingBufferWidth;
  8270. };
  8271. Engine.prototype.getRenderHeight = function (useScreen) {
  8272. if (useScreen === void 0) { useScreen = false; }
  8273. if (!useScreen && this._currentRenderTarget) {
  8274. return this._currentRenderTarget.height;
  8275. }
  8276. return this._gl.drawingBufferHeight;
  8277. };
  8278. Engine.prototype.getRenderingCanvas = function () {
  8279. return this._renderingCanvas;
  8280. };
  8281. Engine.prototype.getRenderingCanvasClientRect = function () {
  8282. return this._renderingCanvas.getBoundingClientRect();
  8283. };
  8284. Engine.prototype.setHardwareScalingLevel = function (level) {
  8285. this._hardwareScalingLevel = level;
  8286. this.resize();
  8287. };
  8288. Engine.prototype.getHardwareScalingLevel = function () {
  8289. return this._hardwareScalingLevel;
  8290. };
  8291. Engine.prototype.getLoadedTexturesCache = function () {
  8292. return this._internalTexturesCache;
  8293. };
  8294. Engine.prototype.getCaps = function () {
  8295. return this._caps;
  8296. };
  8297. Object.defineProperty(Engine.prototype, "drawCalls", {
  8298. /** The number of draw calls submitted last frame */
  8299. get: function () {
  8300. return this._drawCalls.current;
  8301. },
  8302. enumerable: true,
  8303. configurable: true
  8304. });
  8305. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8306. get: function () {
  8307. return this._drawCalls;
  8308. },
  8309. enumerable: true,
  8310. configurable: true
  8311. });
  8312. Engine.prototype.getDepthFunction = function () {
  8313. return this._depthCullingState.depthFunc;
  8314. };
  8315. Engine.prototype.setDepthFunction = function (depthFunc) {
  8316. this._depthCullingState.depthFunc = depthFunc;
  8317. };
  8318. Engine.prototype.setDepthFunctionToGreater = function () {
  8319. this._depthCullingState.depthFunc = this._gl.GREATER;
  8320. };
  8321. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8322. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8323. };
  8324. Engine.prototype.setDepthFunctionToLess = function () {
  8325. this._depthCullingState.depthFunc = this._gl.LESS;
  8326. };
  8327. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8328. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8329. };
  8330. Engine.prototype.getStencilBuffer = function () {
  8331. return this._stencilState.stencilTest;
  8332. };
  8333. Engine.prototype.setStencilBuffer = function (enable) {
  8334. this._stencilState.stencilTest = enable;
  8335. };
  8336. Engine.prototype.getStencilMask = function () {
  8337. return this._stencilState.stencilMask;
  8338. };
  8339. Engine.prototype.setStencilMask = function (mask) {
  8340. this._stencilState.stencilMask = mask;
  8341. };
  8342. Engine.prototype.getStencilFunction = function () {
  8343. return this._stencilState.stencilFunc;
  8344. };
  8345. Engine.prototype.getStencilFunctionReference = function () {
  8346. return this._stencilState.stencilFuncRef;
  8347. };
  8348. Engine.prototype.getStencilFunctionMask = function () {
  8349. return this._stencilState.stencilFuncMask;
  8350. };
  8351. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8352. this._stencilState.stencilFunc = stencilFunc;
  8353. };
  8354. Engine.prototype.setStencilFunctionReference = function (reference) {
  8355. this._stencilState.stencilFuncRef = reference;
  8356. };
  8357. Engine.prototype.setStencilFunctionMask = function (mask) {
  8358. this._stencilState.stencilFuncMask = mask;
  8359. };
  8360. Engine.prototype.getStencilOperationFail = function () {
  8361. return this._stencilState.stencilOpStencilFail;
  8362. };
  8363. Engine.prototype.getStencilOperationDepthFail = function () {
  8364. return this._stencilState.stencilOpDepthFail;
  8365. };
  8366. Engine.prototype.getStencilOperationPass = function () {
  8367. return this._stencilState.stencilOpStencilDepthPass;
  8368. };
  8369. Engine.prototype.setStencilOperationFail = function (operation) {
  8370. this._stencilState.stencilOpStencilFail = operation;
  8371. };
  8372. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8373. this._stencilState.stencilOpDepthFail = operation;
  8374. };
  8375. Engine.prototype.setStencilOperationPass = function (operation) {
  8376. this._stencilState.stencilOpStencilDepthPass = operation;
  8377. };
  8378. Engine.prototype.setDitheringState = function (value) {
  8379. if (value) {
  8380. this._gl.enable(this._gl.DITHER);
  8381. }
  8382. else {
  8383. this._gl.disable(this._gl.DITHER);
  8384. }
  8385. };
  8386. /**
  8387. * stop executing a render loop function and remove it from the execution array
  8388. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8389. */
  8390. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8391. if (!renderFunction) {
  8392. this._activeRenderLoops = [];
  8393. return;
  8394. }
  8395. var index = this._activeRenderLoops.indexOf(renderFunction);
  8396. if (index >= 0) {
  8397. this._activeRenderLoops.splice(index, 1);
  8398. }
  8399. };
  8400. Engine.prototype._renderLoop = function () {
  8401. if (!this._contextWasLost) {
  8402. var shouldRender = true;
  8403. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8404. shouldRender = false;
  8405. }
  8406. if (shouldRender) {
  8407. // Start new frame
  8408. this.beginFrame();
  8409. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8410. var renderFunction = this._activeRenderLoops[index];
  8411. renderFunction();
  8412. }
  8413. // Present
  8414. this.endFrame();
  8415. }
  8416. }
  8417. if (this._activeRenderLoops.length > 0) {
  8418. // Register new frame
  8419. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8420. }
  8421. else {
  8422. this._renderingQueueLaunched = false;
  8423. }
  8424. };
  8425. /**
  8426. * Register and execute a render loop. The engine can have more than one render function.
  8427. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8428. * @example
  8429. * engine.runRenderLoop(function () {
  8430. * scene.render()
  8431. * })
  8432. */
  8433. Engine.prototype.runRenderLoop = function (renderFunction) {
  8434. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8435. return;
  8436. }
  8437. this._activeRenderLoops.push(renderFunction);
  8438. if (!this._renderingQueueLaunched) {
  8439. this._renderingQueueLaunched = true;
  8440. this._bindedRenderFunction = this._renderLoop.bind(this);
  8441. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8442. }
  8443. };
  8444. /**
  8445. * Toggle full screen mode.
  8446. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8447. * @param {any} options - an options object to be sent to the requestFullscreen function
  8448. */
  8449. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8450. if (this.isFullscreen) {
  8451. BABYLON.Tools.ExitFullscreen();
  8452. }
  8453. else {
  8454. this._pointerLockRequested = requestPointerLock;
  8455. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8456. }
  8457. };
  8458. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8459. if (stencil === void 0) { stencil = false; }
  8460. this.applyStates();
  8461. var mode = 0;
  8462. if (backBuffer && color) {
  8463. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8464. mode |= this._gl.COLOR_BUFFER_BIT;
  8465. }
  8466. if (depth) {
  8467. this._gl.clearDepth(1.0);
  8468. mode |= this._gl.DEPTH_BUFFER_BIT;
  8469. }
  8470. if (stencil) {
  8471. this._gl.clearStencil(0);
  8472. mode |= this._gl.STENCIL_BUFFER_BIT;
  8473. }
  8474. this._gl.clear(mode);
  8475. };
  8476. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8477. var gl = this._gl;
  8478. // Save state
  8479. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8480. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8481. // Change state
  8482. gl.enable(gl.SCISSOR_TEST);
  8483. gl.scissor(x, y, width, height);
  8484. // Clear
  8485. this.clear(clearColor, true, true, true);
  8486. // Restore state
  8487. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8488. if (curScissor === true) {
  8489. gl.enable(gl.SCISSOR_TEST);
  8490. }
  8491. else {
  8492. gl.disable(gl.SCISSOR_TEST);
  8493. }
  8494. };
  8495. /**
  8496. * Set the WebGL's viewport
  8497. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8498. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8499. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8500. */
  8501. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8502. var width = requiredWidth || this.getRenderWidth();
  8503. var height = requiredHeight || this.getRenderHeight();
  8504. var x = viewport.x || 0;
  8505. var y = viewport.y || 0;
  8506. this._cachedViewport = viewport;
  8507. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8508. };
  8509. /**
  8510. * Directly set the WebGL Viewport
  8511. * The x, y, width & height are directly passed to the WebGL call
  8512. * @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.
  8513. */
  8514. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8515. var currentViewport = this._cachedViewport;
  8516. this._cachedViewport = null;
  8517. this._gl.viewport(x, y, width, height);
  8518. return currentViewport;
  8519. };
  8520. Engine.prototype.beginFrame = function () {
  8521. this._measureFps();
  8522. };
  8523. Engine.prototype.endFrame = function () {
  8524. //force a flush in case we are using a bad OS.
  8525. if (this._badOS) {
  8526. this.flushFramebuffer();
  8527. }
  8528. //submit frame to the vr device, if enabled
  8529. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8530. this._vrDisplayEnabled.submitFrame();
  8531. }
  8532. };
  8533. /**
  8534. * resize the view according to the canvas' size.
  8535. * @example
  8536. * window.addEventListener("resize", function () {
  8537. * engine.resize();
  8538. * });
  8539. */
  8540. Engine.prototype.resize = function () {
  8541. // We're not resizing the size of the canvas while in VR mode & presenting
  8542. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8543. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8544. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8545. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8546. }
  8547. };
  8548. /**
  8549. * force a specific size of the canvas
  8550. * @param {number} width - the new canvas' width
  8551. * @param {number} height - the new canvas' height
  8552. */
  8553. Engine.prototype.setSize = function (width, height) {
  8554. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8555. return;
  8556. }
  8557. this._renderingCanvas.width = width;
  8558. this._renderingCanvas.height = height;
  8559. for (var index = 0; index < this.scenes.length; index++) {
  8560. var scene = this.scenes[index];
  8561. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8562. var cam = scene.cameras[camIndex];
  8563. cam._currentRenderId = 0;
  8564. }
  8565. }
  8566. if (this.onResizeObservable.hasObservers) {
  8567. this.onResizeObservable.notifyObservers(this);
  8568. }
  8569. };
  8570. //WebVR functions
  8571. Engine.prototype.isVRDevicePresent = function (callback) {
  8572. this.getVRDevice(null, function (device) {
  8573. callback(device !== null);
  8574. });
  8575. };
  8576. Engine.prototype.getVRDevice = function (name, callback) {
  8577. if (!this.vrDisplaysPromise) {
  8578. callback(null);
  8579. return;
  8580. }
  8581. this.vrDisplaysPromise.then(function (devices) {
  8582. if (devices.length > 0) {
  8583. if (name) {
  8584. var found = devices.some(function (device) {
  8585. if (device.displayName === name) {
  8586. callback(device);
  8587. return true;
  8588. }
  8589. else {
  8590. return false;
  8591. }
  8592. });
  8593. if (!found) {
  8594. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8595. callback(devices[0]);
  8596. }
  8597. }
  8598. else {
  8599. //choose the first one
  8600. callback(devices[0]);
  8601. }
  8602. }
  8603. else {
  8604. BABYLON.Tools.Error("No WebVR devices found!");
  8605. callback(null);
  8606. }
  8607. });
  8608. };
  8609. Engine.prototype.initWebVR = function () {
  8610. if (!this.vrDisplaysPromise) {
  8611. this._getVRDisplays();
  8612. }
  8613. };
  8614. Engine.prototype.enableVR = function (vrDevice) {
  8615. this._vrDisplayEnabled = vrDevice;
  8616. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8617. };
  8618. Engine.prototype.disableVR = function () {
  8619. if (this._vrDisplayEnabled) {
  8620. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8621. }
  8622. };
  8623. Engine.prototype._getVRDisplays = function () {
  8624. var _this = this;
  8625. var getWebVRDevices = function (devices) {
  8626. _this._vrDisplays = devices.filter(function (device) {
  8627. return device instanceof VRDisplay;
  8628. });
  8629. return _this._vrDisplays;
  8630. };
  8631. if (navigator.getVRDisplays) {
  8632. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8633. }
  8634. };
  8635. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8636. if (this._currentRenderTarget) {
  8637. this.unBindFramebuffer(this._currentRenderTarget);
  8638. }
  8639. this._currentRenderTarget = texture;
  8640. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8641. var gl = this._gl;
  8642. if (texture.isCube) {
  8643. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8644. }
  8645. if (this._cachedViewport && !forceFullscreenViewport) {
  8646. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8647. }
  8648. else {
  8649. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8650. }
  8651. this.wipeCaches();
  8652. };
  8653. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8654. if (this._currentFramebuffer !== framebuffer) {
  8655. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8656. this._currentFramebuffer = framebuffer;
  8657. }
  8658. };
  8659. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8660. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8661. this._currentRenderTarget = null;
  8662. // If MSAA, we need to bitblt back to main texture
  8663. var gl = this._gl;
  8664. if (texture._MSAAFramebuffer) {
  8665. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8666. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8667. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8668. }
  8669. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8670. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8671. gl.generateMipmap(gl.TEXTURE_2D);
  8672. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8673. }
  8674. if (onBeforeUnbind) {
  8675. if (texture._MSAAFramebuffer) {
  8676. // Bind the correct framebuffer
  8677. this.bindUnboundFramebuffer(texture._framebuffer);
  8678. }
  8679. onBeforeUnbind();
  8680. }
  8681. this.bindUnboundFramebuffer(null);
  8682. };
  8683. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8684. if (texture.generateMipMaps) {
  8685. var gl = this._gl;
  8686. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8687. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8688. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8689. }
  8690. };
  8691. Engine.prototype.flushFramebuffer = function () {
  8692. this._gl.flush();
  8693. };
  8694. Engine.prototype.restoreDefaultFramebuffer = function () {
  8695. if (this._currentRenderTarget) {
  8696. this.unBindFramebuffer(this._currentRenderTarget);
  8697. }
  8698. else {
  8699. this.bindUnboundFramebuffer(null);
  8700. }
  8701. if (this._cachedViewport) {
  8702. this.setViewport(this._cachedViewport);
  8703. }
  8704. this.wipeCaches();
  8705. };
  8706. // UBOs
  8707. Engine.prototype.createUniformBuffer = function (elements) {
  8708. var ubo = this._gl.createBuffer();
  8709. this.bindUniformBuffer(ubo);
  8710. if (elements instanceof Float32Array) {
  8711. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8712. }
  8713. else {
  8714. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8715. }
  8716. this.bindUniformBuffer(null);
  8717. ubo.references = 1;
  8718. return ubo;
  8719. };
  8720. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8721. var ubo = this._gl.createBuffer();
  8722. this.bindUniformBuffer(ubo);
  8723. if (elements instanceof Float32Array) {
  8724. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8725. }
  8726. else {
  8727. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8728. }
  8729. this.bindUniformBuffer(null);
  8730. ubo.references = 1;
  8731. return ubo;
  8732. };
  8733. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8734. this.bindUniformBuffer(uniformBuffer);
  8735. if (offset === undefined) {
  8736. offset = 0;
  8737. }
  8738. if (count === undefined) {
  8739. if (elements instanceof Float32Array) {
  8740. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8741. }
  8742. else {
  8743. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8744. }
  8745. }
  8746. else {
  8747. if (elements instanceof Float32Array) {
  8748. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8749. }
  8750. else {
  8751. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8752. }
  8753. }
  8754. this.bindUniformBuffer(null);
  8755. };
  8756. // VBOs
  8757. Engine.prototype._resetVertexBufferBinding = function () {
  8758. this.bindArrayBuffer(null);
  8759. this._cachedVertexBuffers = null;
  8760. };
  8761. Engine.prototype.createVertexBuffer = function (vertices) {
  8762. var vbo = this._gl.createBuffer();
  8763. this.bindArrayBuffer(vbo);
  8764. if (vertices instanceof Float32Array) {
  8765. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8766. }
  8767. else {
  8768. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8769. }
  8770. this._resetVertexBufferBinding();
  8771. vbo.references = 1;
  8772. return vbo;
  8773. };
  8774. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8775. var vbo = this._gl.createBuffer();
  8776. this.bindArrayBuffer(vbo);
  8777. if (vertices instanceof Float32Array) {
  8778. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8779. }
  8780. else {
  8781. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8782. }
  8783. this._resetVertexBufferBinding();
  8784. vbo.references = 1;
  8785. return vbo;
  8786. };
  8787. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8788. this.bindArrayBuffer(vertexBuffer);
  8789. if (offset === undefined) {
  8790. offset = 0;
  8791. }
  8792. if (count === undefined) {
  8793. if (vertices instanceof Float32Array) {
  8794. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8795. }
  8796. else {
  8797. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8798. }
  8799. }
  8800. else {
  8801. if (vertices instanceof Float32Array) {
  8802. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8803. }
  8804. else {
  8805. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8806. }
  8807. }
  8808. this._resetVertexBufferBinding();
  8809. };
  8810. Engine.prototype._resetIndexBufferBinding = function () {
  8811. this.bindIndexBuffer(null);
  8812. this._cachedIndexBuffer = null;
  8813. };
  8814. Engine.prototype.createIndexBuffer = function (indices) {
  8815. var vbo = this._gl.createBuffer();
  8816. this.bindIndexBuffer(vbo);
  8817. // Check for 32 bits indices
  8818. var arrayBuffer;
  8819. var need32Bits = false;
  8820. if (indices instanceof Uint16Array) {
  8821. arrayBuffer = indices;
  8822. }
  8823. else {
  8824. //check 32 bit support
  8825. if (this._caps.uintIndices) {
  8826. if (indices instanceof Uint32Array) {
  8827. arrayBuffer = indices;
  8828. need32Bits = true;
  8829. }
  8830. else {
  8831. //number[] or Int32Array, check if 32 bit is necessary
  8832. for (var index = 0; index < indices.length; index++) {
  8833. if (indices[index] > 65535) {
  8834. need32Bits = true;
  8835. break;
  8836. }
  8837. }
  8838. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8839. }
  8840. }
  8841. else {
  8842. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8843. arrayBuffer = new Uint16Array(indices);
  8844. }
  8845. }
  8846. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8847. this._resetIndexBufferBinding();
  8848. vbo.references = 1;
  8849. vbo.is32Bits = need32Bits;
  8850. return vbo;
  8851. };
  8852. Engine.prototype.bindArrayBuffer = function (buffer) {
  8853. if (!this._vaoRecordInProgress) {
  8854. this._unbindVertexArrayObject();
  8855. }
  8856. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8857. };
  8858. Engine.prototype.bindUniformBuffer = function (buffer) {
  8859. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8860. };
  8861. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8862. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8863. };
  8864. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8865. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8866. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8867. };
  8868. ;
  8869. Engine.prototype.bindIndexBuffer = function (buffer) {
  8870. if (!this._vaoRecordInProgress) {
  8871. this._unbindVertexArrayObject();
  8872. }
  8873. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8874. };
  8875. Engine.prototype.bindBuffer = function (buffer, target) {
  8876. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8877. this._gl.bindBuffer(target, buffer);
  8878. this._currentBoundBuffer[target] = buffer;
  8879. }
  8880. };
  8881. Engine.prototype.updateArrayBuffer = function (data) {
  8882. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8883. };
  8884. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8885. var pointer = this._currentBufferPointers[indx];
  8886. var changed = false;
  8887. if (!pointer.active) {
  8888. changed = true;
  8889. pointer.active = true;
  8890. pointer.index = indx;
  8891. pointer.size = size;
  8892. pointer.type = type;
  8893. pointer.normalized = normalized;
  8894. pointer.stride = stride;
  8895. pointer.offset = offset;
  8896. pointer.buffer = buffer;
  8897. }
  8898. else {
  8899. if (pointer.buffer !== buffer) {
  8900. pointer.buffer = buffer;
  8901. changed = true;
  8902. }
  8903. if (pointer.size !== size) {
  8904. pointer.size = size;
  8905. changed = true;
  8906. }
  8907. if (pointer.type !== type) {
  8908. pointer.type = type;
  8909. changed = true;
  8910. }
  8911. if (pointer.normalized !== normalized) {
  8912. pointer.normalized = normalized;
  8913. changed = true;
  8914. }
  8915. if (pointer.stride !== stride) {
  8916. pointer.stride = stride;
  8917. changed = true;
  8918. }
  8919. if (pointer.offset !== offset) {
  8920. pointer.offset = offset;
  8921. changed = true;
  8922. }
  8923. }
  8924. if (changed || this._vaoRecordInProgress) {
  8925. this.bindArrayBuffer(buffer);
  8926. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8927. }
  8928. };
  8929. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8930. if (indexBuffer == null) {
  8931. return;
  8932. }
  8933. if (this._cachedIndexBuffer !== indexBuffer) {
  8934. this._cachedIndexBuffer = indexBuffer;
  8935. this.bindIndexBuffer(indexBuffer);
  8936. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8937. }
  8938. };
  8939. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8940. var attributes = effect.getAttributesNames();
  8941. if (!this._vaoRecordInProgress) {
  8942. this._unbindVertexArrayObject();
  8943. }
  8944. this.unbindAllAttributes();
  8945. for (var index = 0; index < attributes.length; index++) {
  8946. var order = effect.getAttributeLocation(index);
  8947. if (order >= 0) {
  8948. var vertexBuffer = vertexBuffers[attributes[index]];
  8949. if (!vertexBuffer) {
  8950. continue;
  8951. }
  8952. this._gl.enableVertexAttribArray(order);
  8953. if (!this._vaoRecordInProgress) {
  8954. this._vertexAttribArraysEnabled[order] = true;
  8955. }
  8956. var buffer = vertexBuffer.getBuffer();
  8957. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8958. if (vertexBuffer.getIsInstanced()) {
  8959. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8960. if (!this._vaoRecordInProgress) {
  8961. this._currentInstanceLocations.push(order);
  8962. this._currentInstanceBuffers.push(buffer);
  8963. }
  8964. }
  8965. }
  8966. }
  8967. };
  8968. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8969. var vao = this._gl.createVertexArray();
  8970. this._vaoRecordInProgress = true;
  8971. this._gl.bindVertexArray(vao);
  8972. this._mustWipeVertexAttributes = true;
  8973. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8974. this.bindIndexBuffer(indexBuffer);
  8975. this._vaoRecordInProgress = false;
  8976. this._gl.bindVertexArray(null);
  8977. return vao;
  8978. };
  8979. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8980. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8981. this._cachedVertexArrayObject = vertexArrayObject;
  8982. this._gl.bindVertexArray(vertexArrayObject);
  8983. this._cachedVertexBuffers = null;
  8984. this._cachedIndexBuffer = null;
  8985. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8986. this._mustWipeVertexAttributes = true;
  8987. }
  8988. };
  8989. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8990. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8991. this._cachedVertexBuffers = vertexBuffer;
  8992. this._cachedEffectForVertexBuffers = effect;
  8993. var attributesCount = effect.getAttributesCount();
  8994. this._unbindVertexArrayObject();
  8995. this.unbindAllAttributes();
  8996. var offset = 0;
  8997. for (var index = 0; index < attributesCount; index++) {
  8998. if (index < vertexDeclaration.length) {
  8999. var order = effect.getAttributeLocation(index);
  9000. if (order >= 0) {
  9001. this._gl.enableVertexAttribArray(order);
  9002. this._vertexAttribArraysEnabled[order] = true;
  9003. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9004. }
  9005. offset += vertexDeclaration[index] * 4;
  9006. }
  9007. }
  9008. }
  9009. this._bindIndexBufferWithCache(indexBuffer);
  9010. };
  9011. Engine.prototype._unbindVertexArrayObject = function () {
  9012. if (!this._cachedVertexArrayObject) {
  9013. return;
  9014. }
  9015. this._cachedVertexArrayObject = null;
  9016. this._gl.bindVertexArray(null);
  9017. };
  9018. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9019. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9020. this._cachedVertexBuffers = vertexBuffers;
  9021. this._cachedEffectForVertexBuffers = effect;
  9022. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9023. }
  9024. this._bindIndexBufferWithCache(indexBuffer);
  9025. };
  9026. Engine.prototype.unbindInstanceAttributes = function () {
  9027. var boundBuffer;
  9028. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9029. var instancesBuffer = this._currentInstanceBuffers[i];
  9030. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9031. boundBuffer = instancesBuffer;
  9032. this.bindArrayBuffer(instancesBuffer);
  9033. }
  9034. var offsetLocation = this._currentInstanceLocations[i];
  9035. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9036. }
  9037. this._currentInstanceBuffers.length = 0;
  9038. this._currentInstanceLocations.length = 0;
  9039. };
  9040. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9041. this._gl.deleteVertexArray(vao);
  9042. };
  9043. Engine.prototype._releaseBuffer = function (buffer) {
  9044. buffer.references--;
  9045. if (buffer.references === 0) {
  9046. this._gl.deleteBuffer(buffer);
  9047. return true;
  9048. }
  9049. return false;
  9050. };
  9051. Engine.prototype.createInstancesBuffer = function (capacity) {
  9052. var buffer = this._gl.createBuffer();
  9053. buffer.capacity = capacity;
  9054. this.bindArrayBuffer(buffer);
  9055. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9056. return buffer;
  9057. };
  9058. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9059. this._gl.deleteBuffer(buffer);
  9060. };
  9061. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9062. this.bindArrayBuffer(instancesBuffer);
  9063. if (data) {
  9064. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9065. }
  9066. if (offsetLocations[0].index !== undefined) {
  9067. var stride = 0;
  9068. for (var i = 0; i < offsetLocations.length; i++) {
  9069. var ai = offsetLocations[i];
  9070. stride += ai.attributeSize * 4;
  9071. }
  9072. for (var i = 0; i < offsetLocations.length; i++) {
  9073. var ai = offsetLocations[i];
  9074. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9075. this._gl.enableVertexAttribArray(ai.index);
  9076. this._vertexAttribArraysEnabled[ai.index] = true;
  9077. }
  9078. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9079. this._gl.vertexAttribDivisor(ai.index, 1);
  9080. this._currentInstanceLocations.push(ai.index);
  9081. this._currentInstanceBuffers.push(instancesBuffer);
  9082. }
  9083. }
  9084. else {
  9085. for (var index = 0; index < 4; index++) {
  9086. var offsetLocation = offsetLocations[index];
  9087. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9088. this._gl.enableVertexAttribArray(offsetLocation);
  9089. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9090. }
  9091. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9092. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9093. this._currentInstanceLocations.push(offsetLocation);
  9094. this._currentInstanceBuffers.push(instancesBuffer);
  9095. }
  9096. }
  9097. };
  9098. Engine.prototype.applyStates = function () {
  9099. this._depthCullingState.apply(this._gl);
  9100. this._stencilState.apply(this._gl);
  9101. this._alphaState.apply(this._gl);
  9102. };
  9103. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9104. // Apply states
  9105. this.applyStates();
  9106. this._drawCalls.addCount(1, false);
  9107. // Render
  9108. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9109. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9110. if (instancesCount) {
  9111. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9112. return;
  9113. }
  9114. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9115. };
  9116. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9117. // Apply states
  9118. this.applyStates();
  9119. this._drawCalls.addCount(1, false);
  9120. if (instancesCount) {
  9121. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9122. return;
  9123. }
  9124. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9125. };
  9126. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9127. // Apply states
  9128. this.applyStates();
  9129. this._drawCalls.addCount(1, false);
  9130. if (instancesCount) {
  9131. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9132. return;
  9133. }
  9134. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9135. };
  9136. // Shaders
  9137. Engine.prototype._releaseEffect = function (effect) {
  9138. if (this._compiledEffects[effect._key]) {
  9139. delete this._compiledEffects[effect._key];
  9140. if (effect.getProgram()) {
  9141. this._gl.deleteProgram(effect.getProgram());
  9142. }
  9143. }
  9144. };
  9145. /**
  9146. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9147. * @param samplers An array of string used to represent textures
  9148. */
  9149. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9150. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9151. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9152. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9153. if (this._compiledEffects[name]) {
  9154. var compiledEffect = this._compiledEffects[name];
  9155. if (onCompiled && compiledEffect.isReady()) {
  9156. onCompiled(compiledEffect);
  9157. }
  9158. return compiledEffect;
  9159. }
  9160. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9161. effect._key = name;
  9162. this._compiledEffects[name] = effect;
  9163. return effect;
  9164. };
  9165. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9166. if (uniformsNames === void 0) { uniformsNames = []; }
  9167. if (samplers === void 0) { samplers = []; }
  9168. if (defines === void 0) { defines = ""; }
  9169. return this.createEffect({
  9170. vertex: "particles",
  9171. fragmentElement: fragmentName
  9172. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9173. };
  9174. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9175. context = context || this._gl;
  9176. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9177. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9178. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9179. var shaderProgram = context.createProgram();
  9180. context.attachShader(shaderProgram, vertexShader);
  9181. context.attachShader(shaderProgram, fragmentShader);
  9182. context.linkProgram(shaderProgram);
  9183. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9184. if (!linked) {
  9185. context.validateProgram(shaderProgram);
  9186. var error = context.getProgramInfoLog(shaderProgram);
  9187. if (error) {
  9188. throw new Error(error);
  9189. }
  9190. }
  9191. context.deleteShader(vertexShader);
  9192. context.deleteShader(fragmentShader);
  9193. return shaderProgram;
  9194. };
  9195. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9196. var results = [];
  9197. for (var index = 0; index < uniformsNames.length; index++) {
  9198. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9199. }
  9200. return results;
  9201. };
  9202. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9203. var results = [];
  9204. for (var index = 0; index < attributesNames.length; index++) {
  9205. try {
  9206. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9207. }
  9208. catch (e) {
  9209. results.push(-1);
  9210. }
  9211. }
  9212. return results;
  9213. };
  9214. Engine.prototype.enableEffect = function (effect) {
  9215. // Use program
  9216. this.setProgram(effect.getProgram());
  9217. this._currentEffect = effect;
  9218. if (effect.onBind) {
  9219. effect.onBind(effect);
  9220. }
  9221. effect.onBindObservable.notifyObservers(effect);
  9222. };
  9223. Engine.prototype.setIntArray = function (uniform, array) {
  9224. if (!uniform)
  9225. return;
  9226. this._gl.uniform1iv(uniform, array);
  9227. };
  9228. Engine.prototype.setIntArray2 = function (uniform, array) {
  9229. if (!uniform || array.length % 2 !== 0)
  9230. return;
  9231. this._gl.uniform2iv(uniform, array);
  9232. };
  9233. Engine.prototype.setIntArray3 = function (uniform, array) {
  9234. if (!uniform || array.length % 3 !== 0)
  9235. return;
  9236. this._gl.uniform3iv(uniform, array);
  9237. };
  9238. Engine.prototype.setIntArray4 = function (uniform, array) {
  9239. if (!uniform || array.length % 4 !== 0)
  9240. return;
  9241. this._gl.uniform4iv(uniform, array);
  9242. };
  9243. Engine.prototype.setFloatArray = function (uniform, array) {
  9244. if (!uniform)
  9245. return;
  9246. this._gl.uniform1fv(uniform, array);
  9247. };
  9248. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9249. if (!uniform || array.length % 2 !== 0)
  9250. return;
  9251. this._gl.uniform2fv(uniform, array);
  9252. };
  9253. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9254. if (!uniform || array.length % 3 !== 0)
  9255. return;
  9256. this._gl.uniform3fv(uniform, array);
  9257. };
  9258. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9259. if (!uniform || array.length % 4 !== 0)
  9260. return;
  9261. this._gl.uniform4fv(uniform, array);
  9262. };
  9263. Engine.prototype.setArray = function (uniform, array) {
  9264. if (!uniform)
  9265. return;
  9266. this._gl.uniform1fv(uniform, array);
  9267. };
  9268. Engine.prototype.setArray2 = function (uniform, array) {
  9269. if (!uniform || array.length % 2 !== 0)
  9270. return;
  9271. this._gl.uniform2fv(uniform, array);
  9272. };
  9273. Engine.prototype.setArray3 = function (uniform, array) {
  9274. if (!uniform || array.length % 3 !== 0)
  9275. return;
  9276. this._gl.uniform3fv(uniform, array);
  9277. };
  9278. Engine.prototype.setArray4 = function (uniform, array) {
  9279. if (!uniform || array.length % 4 !== 0)
  9280. return;
  9281. this._gl.uniform4fv(uniform, array);
  9282. };
  9283. Engine.prototype.setMatrices = function (uniform, matrices) {
  9284. if (!uniform)
  9285. return;
  9286. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9287. };
  9288. Engine.prototype.setMatrix = function (uniform, matrix) {
  9289. if (!uniform)
  9290. return;
  9291. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9292. };
  9293. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9294. if (!uniform)
  9295. return;
  9296. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9297. };
  9298. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9299. if (!uniform)
  9300. return;
  9301. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9302. };
  9303. Engine.prototype.setFloat = function (uniform, value) {
  9304. if (!uniform)
  9305. return;
  9306. this._gl.uniform1f(uniform, value);
  9307. };
  9308. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9309. if (!uniform)
  9310. return;
  9311. this._gl.uniform2f(uniform, x, y);
  9312. };
  9313. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9314. if (!uniform)
  9315. return;
  9316. this._gl.uniform3f(uniform, x, y, z);
  9317. };
  9318. Engine.prototype.setBool = function (uniform, bool) {
  9319. if (!uniform)
  9320. return;
  9321. this._gl.uniform1i(uniform, bool);
  9322. };
  9323. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9324. if (!uniform)
  9325. return;
  9326. this._gl.uniform4f(uniform, x, y, z, w);
  9327. };
  9328. Engine.prototype.setColor3 = function (uniform, color3) {
  9329. if (!uniform)
  9330. return;
  9331. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9332. };
  9333. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9334. if (!uniform)
  9335. return;
  9336. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9337. };
  9338. // States
  9339. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9340. if (zOffset === void 0) { zOffset = 0; }
  9341. if (reverseSide === void 0) { reverseSide = false; }
  9342. // Culling
  9343. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9344. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9345. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9346. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9347. if (culling) {
  9348. this._depthCullingState.cullFace = cullFace;
  9349. this._depthCullingState.cull = true;
  9350. }
  9351. else {
  9352. this._depthCullingState.cull = false;
  9353. }
  9354. }
  9355. // Z offset
  9356. this.setZOffset(zOffset);
  9357. };
  9358. Engine.prototype.setZOffset = function (value) {
  9359. this._depthCullingState.zOffset = value;
  9360. };
  9361. Engine.prototype.getZOffset = function () {
  9362. return this._depthCullingState.zOffset;
  9363. };
  9364. Engine.prototype.setDepthBuffer = function (enable) {
  9365. this._depthCullingState.depthTest = enable;
  9366. };
  9367. Engine.prototype.getDepthWrite = function () {
  9368. return this._depthCullingState.depthMask;
  9369. };
  9370. Engine.prototype.setDepthWrite = function (enable) {
  9371. this._depthCullingState.depthMask = enable;
  9372. };
  9373. Engine.prototype.setColorWrite = function (enable) {
  9374. this._gl.colorMask(enable, enable, enable, enable);
  9375. };
  9376. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9377. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9378. };
  9379. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9380. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9381. if (this._alphaMode === mode) {
  9382. return;
  9383. }
  9384. switch (mode) {
  9385. case Engine.ALPHA_DISABLE:
  9386. this._alphaState.alphaBlend = false;
  9387. break;
  9388. case Engine.ALPHA_PREMULTIPLIED:
  9389. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9390. this._alphaState.alphaBlend = true;
  9391. break;
  9392. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9393. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9394. this._alphaState.alphaBlend = true;
  9395. break;
  9396. case Engine.ALPHA_COMBINE:
  9397. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9398. this._alphaState.alphaBlend = true;
  9399. break;
  9400. case Engine.ALPHA_ONEONE:
  9401. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9402. this._alphaState.alphaBlend = true;
  9403. break;
  9404. case Engine.ALPHA_ADD:
  9405. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9406. this._alphaState.alphaBlend = true;
  9407. break;
  9408. case Engine.ALPHA_SUBTRACT:
  9409. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9410. this._alphaState.alphaBlend = true;
  9411. break;
  9412. case Engine.ALPHA_MULTIPLY:
  9413. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9414. this._alphaState.alphaBlend = true;
  9415. break;
  9416. case Engine.ALPHA_MAXIMIZED:
  9417. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9418. this._alphaState.alphaBlend = true;
  9419. break;
  9420. case Engine.ALPHA_INTERPOLATE:
  9421. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9422. this._alphaState.alphaBlend = true;
  9423. break;
  9424. case Engine.ALPHA_SCREENMODE:
  9425. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9426. this._alphaState.alphaBlend = true;
  9427. break;
  9428. }
  9429. if (!noDepthWriteChange) {
  9430. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9431. }
  9432. this._alphaMode = mode;
  9433. };
  9434. Engine.prototype.getAlphaMode = function () {
  9435. return this._alphaMode;
  9436. };
  9437. Engine.prototype.setAlphaTesting = function (enable) {
  9438. this._alphaTest = enable;
  9439. };
  9440. Engine.prototype.getAlphaTesting = function () {
  9441. return !!this._alphaTest;
  9442. };
  9443. // Textures
  9444. Engine.prototype.wipeCaches = function (bruteForce) {
  9445. if (this.preventCacheWipeBetweenFrames) {
  9446. return;
  9447. }
  9448. this.resetTextureCache();
  9449. this._currentEffect = null;
  9450. // 6/8/2017: deltakosh: Should not be required anymore.
  9451. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9452. if (bruteForce) {
  9453. this._currentProgram = null;
  9454. this._stencilState.reset();
  9455. this._depthCullingState.reset();
  9456. this.setDepthFunctionToLessOrEqual();
  9457. this._alphaState.reset();
  9458. }
  9459. this._cachedVertexBuffers = null;
  9460. this._cachedIndexBuffer = null;
  9461. this._cachedEffectForVertexBuffers = null;
  9462. this._unbindVertexArrayObject();
  9463. this.bindIndexBuffer(null);
  9464. this.bindArrayBuffer(null);
  9465. };
  9466. /**
  9467. * Set the compressed texture format to use, based on the formats you have, and the formats
  9468. * supported by the hardware / browser.
  9469. *
  9470. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9471. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9472. * to API arguments needed to compressed textures. This puts the burden on the container
  9473. * generator to house the arcane code for determining these for current & future formats.
  9474. *
  9475. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9476. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9477. *
  9478. * Note: The result of this call is not taken into account when a texture is base64.
  9479. *
  9480. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9481. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9482. *
  9483. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9484. * @returns The extension selected.
  9485. */
  9486. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9487. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9488. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9489. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9490. return this._textureFormatInUse = this._texturesSupported[i];
  9491. }
  9492. }
  9493. }
  9494. // actively set format to nothing, to allow this to be called more than once
  9495. // and possibly fail the 2nd time
  9496. return this._textureFormatInUse = null;
  9497. };
  9498. Engine.prototype._createTexture = function () {
  9499. return this._gl.createTexture();
  9500. };
  9501. /**
  9502. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9503. * @param {string} urlArg- This contains one of the following:
  9504. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9505. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9506. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9507. *
  9508. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9509. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9510. * @param {Scene} scene- Needed for loading to the correct scene.
  9511. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9512. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9513. * @param {callback} onError- Optional callback to be called upon failure.
  9514. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9515. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9516. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9517. *
  9518. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9519. */
  9520. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9521. var _this = this;
  9522. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9523. if (onLoad === void 0) { onLoad = null; }
  9524. if (onError === void 0) { onError = null; }
  9525. if (buffer === void 0) { buffer = null; }
  9526. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9527. var fromData = url.substr(0, 5) === "data:";
  9528. var fromBlob = url.substr(0, 5) === "blob:";
  9529. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9530. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9531. // establish the file extension, if possible
  9532. var lastDot = url.lastIndexOf('.');
  9533. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9534. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9535. var isTGA = (extension === ".tga");
  9536. // determine if a ktx file should be substituted
  9537. var isKTX = false;
  9538. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9539. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9540. isKTX = true;
  9541. }
  9542. if (scene) {
  9543. scene._addPendingData(texture);
  9544. }
  9545. texture.url = url;
  9546. texture.generateMipMaps = !noMipmap;
  9547. texture.samplingMode = samplingMode;
  9548. texture.invertY = invertY;
  9549. if (!this._doNotHandleContextLost) {
  9550. // Keep a link to the buffer only if we plan to handle context lost
  9551. texture._buffer = buffer;
  9552. }
  9553. if (onLoad) {
  9554. texture.onLoadedObservable.add(onLoad);
  9555. }
  9556. if (!fallBack)
  9557. this._internalTexturesCache.push(texture);
  9558. var onerror = function () {
  9559. if (scene) {
  9560. scene._removePendingData(texture);
  9561. }
  9562. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9563. if (isKTX) {
  9564. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9565. }
  9566. else if (onError) {
  9567. onError();
  9568. }
  9569. };
  9570. var callback;
  9571. // processing for non-image formats
  9572. if (isKTX || isTGA || isDDS) {
  9573. if (isKTX) {
  9574. callback = function (data) {
  9575. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9576. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9577. ktx.uploadLevels(_this._gl, !noMipmap);
  9578. return false;
  9579. }, samplingMode);
  9580. };
  9581. }
  9582. else if (isTGA) {
  9583. callback = function (arrayBuffer) {
  9584. var data = new Uint8Array(arrayBuffer);
  9585. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9586. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9587. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9588. return false;
  9589. }, samplingMode);
  9590. };
  9591. }
  9592. else if (isDDS) {
  9593. callback = function (data) {
  9594. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9595. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9596. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9597. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9598. return false;
  9599. }, samplingMode);
  9600. };
  9601. }
  9602. if (!buffer) {
  9603. BABYLON.Tools.LoadFile(url, function (data) {
  9604. callback(data);
  9605. }, null, scene ? scene.database : null, true, onerror);
  9606. }
  9607. else {
  9608. callback(buffer);
  9609. }
  9610. // image format processing
  9611. }
  9612. else {
  9613. var onload = function (img) {
  9614. if (fromBlob && !_this._doNotHandleContextLost) {
  9615. // We need to store the image if we need to rebuild the texture
  9616. // in case of a webgl context lost
  9617. texture._buffer = img;
  9618. }
  9619. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9620. var gl = _this._gl;
  9621. var isPot = (img.width === potWidth && img.height === potHeight);
  9622. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9623. if (isPot) {
  9624. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9625. return false;
  9626. }
  9627. // Using shaders to rescale because canvas.drawImage is lossy
  9628. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9629. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9630. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9631. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9632. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9633. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9634. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9635. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9636. _this._releaseTexture(source);
  9637. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9638. continuationCallback();
  9639. });
  9640. return true;
  9641. }, samplingMode);
  9642. };
  9643. if (!fromData || isBase64)
  9644. if (buffer instanceof HTMLImageElement) {
  9645. onload(buffer);
  9646. }
  9647. else {
  9648. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9649. }
  9650. else if (buffer instanceof Array || typeof buffer === "string")
  9651. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9652. else
  9653. onload(buffer);
  9654. }
  9655. return texture;
  9656. };
  9657. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9658. var _this = this;
  9659. var rtt = this.createRenderTargetTexture({
  9660. width: destination.width,
  9661. height: destination.height,
  9662. }, {
  9663. generateMipMaps: false,
  9664. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9665. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9666. generateDepthBuffer: false,
  9667. generateStencilBuffer: false
  9668. });
  9669. if (!this._rescalePostProcess) {
  9670. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9671. }
  9672. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9673. _this._rescalePostProcess.onApply = function (effect) {
  9674. effect._bindTexture("textureSampler", source);
  9675. };
  9676. scene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9677. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9678. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9679. _this.unBindFramebuffer(rtt);
  9680. _this._releaseTexture(rtt);
  9681. if (onComplete) {
  9682. onComplete();
  9683. }
  9684. });
  9685. };
  9686. Engine.prototype._getInternalFormat = function (format) {
  9687. var internalFormat = this._gl.RGBA;
  9688. switch (format) {
  9689. case Engine.TEXTUREFORMAT_ALPHA:
  9690. internalFormat = this._gl.ALPHA;
  9691. break;
  9692. case Engine.TEXTUREFORMAT_LUMINANCE:
  9693. internalFormat = this._gl.LUMINANCE;
  9694. break;
  9695. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9696. internalFormat = this._gl.LUMINANCE_ALPHA;
  9697. break;
  9698. case Engine.TEXTUREFORMAT_RGB:
  9699. internalFormat = this._gl.RGB;
  9700. break;
  9701. case Engine.TEXTUREFORMAT_RGBA:
  9702. internalFormat = this._gl.RGBA;
  9703. break;
  9704. }
  9705. return internalFormat;
  9706. };
  9707. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9708. if (compression === void 0) { compression = null; }
  9709. var internalFormat = this._getInternalFormat(format);
  9710. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9711. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9712. if (!this._doNotHandleContextLost) {
  9713. texture._bufferView = data;
  9714. texture.format = format;
  9715. texture.invertY = invertY;
  9716. texture._compression = compression;
  9717. }
  9718. if (texture.width % 4 !== 0) {
  9719. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9720. }
  9721. if (compression) {
  9722. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  9723. }
  9724. else {
  9725. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9726. }
  9727. if (texture.generateMipMaps) {
  9728. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9729. }
  9730. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9731. this.resetTextureCache();
  9732. texture.isReady = true;
  9733. };
  9734. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9735. if (compression === void 0) { compression = null; }
  9736. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  9737. texture.baseWidth = width;
  9738. texture.baseHeight = height;
  9739. texture.width = width;
  9740. texture.height = height;
  9741. texture.format = format;
  9742. texture.generateMipMaps = generateMipMaps;
  9743. texture.samplingMode = samplingMode;
  9744. texture.invertY = invertY;
  9745. texture._compression = compression;
  9746. if (!this._doNotHandleContextLost) {
  9747. texture._bufferView = data;
  9748. }
  9749. this.updateRawTexture(texture, data, format, invertY, compression);
  9750. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9751. // Filters
  9752. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9753. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9754. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9755. if (generateMipMaps) {
  9756. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9757. }
  9758. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9759. this._internalTexturesCache.push(texture);
  9760. return texture;
  9761. };
  9762. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9763. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  9764. texture.baseWidth = width;
  9765. texture.baseHeight = height;
  9766. if (generateMipMaps) {
  9767. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9768. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9769. }
  9770. this.resetTextureCache();
  9771. texture.width = width;
  9772. texture.height = height;
  9773. texture.isReady = false;
  9774. texture.generateMipMaps = generateMipMaps;
  9775. texture.samplingMode = samplingMode;
  9776. this.updateTextureSamplingMode(samplingMode, texture);
  9777. this._internalTexturesCache.push(texture);
  9778. return texture;
  9779. };
  9780. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9781. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9782. if (texture.isCube) {
  9783. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9784. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9785. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9786. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9787. }
  9788. else {
  9789. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9790. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9791. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9792. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9793. }
  9794. texture.samplingMode = samplingMode;
  9795. };
  9796. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9797. if (premulAlpha === void 0) { premulAlpha = false; }
  9798. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9799. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9800. if (premulAlpha) {
  9801. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9802. }
  9803. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9804. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9805. if (texture.generateMipMaps) {
  9806. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9807. }
  9808. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9809. if (premulAlpha) {
  9810. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9811. }
  9812. this.resetTextureCache();
  9813. texture.isReady = true;
  9814. };
  9815. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9816. if (texture._isDisabled) {
  9817. return;
  9818. }
  9819. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9820. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9821. try {
  9822. // Testing video texture support
  9823. if (this._videoTextureSupported === undefined) {
  9824. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9825. if (this._gl.getError() !== 0) {
  9826. this._videoTextureSupported = false;
  9827. }
  9828. else {
  9829. this._videoTextureSupported = true;
  9830. }
  9831. }
  9832. // Copy video through the current working canvas if video texture is not supported
  9833. if (!this._videoTextureSupported) {
  9834. if (!texture._workingCanvas) {
  9835. texture._workingCanvas = document.createElement("canvas");
  9836. texture._workingContext = texture._workingCanvas.getContext("2d");
  9837. texture._workingCanvas.width = texture.width;
  9838. texture._workingCanvas.height = texture.height;
  9839. }
  9840. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  9841. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9842. }
  9843. else {
  9844. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9845. }
  9846. if (texture.generateMipMaps) {
  9847. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9848. }
  9849. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9850. this.resetTextureCache();
  9851. texture.isReady = true;
  9852. }
  9853. catch (ex) {
  9854. // Something unexpected
  9855. // Let's disable the texture
  9856. texture._isDisabled = true;
  9857. }
  9858. };
  9859. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9860. var fullOptions = new RenderTargetCreationOptions();
  9861. if (options !== undefined && typeof options === "object") {
  9862. fullOptions.generateMipMaps = options.generateMipMaps;
  9863. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9864. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  9865. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  9866. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  9867. }
  9868. else {
  9869. fullOptions.generateMipMaps = options;
  9870. fullOptions.generateDepthBuffer = true;
  9871. fullOptions.generateStencilBuffer = false;
  9872. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9873. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9874. }
  9875. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9876. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9877. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9878. }
  9879. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9880. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9881. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9882. }
  9883. var gl = this._gl;
  9884. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  9885. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9886. var width = size.width || size;
  9887. var height = size.height || size;
  9888. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  9889. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9890. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9891. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9892. }
  9893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9896. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9897. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  9898. // Create the framebuffer
  9899. var framebuffer = gl.createFramebuffer();
  9900. this.bindUnboundFramebuffer(framebuffer);
  9901. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  9902. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  9903. if (fullOptions.generateMipMaps) {
  9904. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9905. }
  9906. // Unbind
  9907. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9908. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9909. this.bindUnboundFramebuffer(null);
  9910. texture._framebuffer = framebuffer;
  9911. texture.baseWidth = width;
  9912. texture.baseHeight = height;
  9913. texture.width = width;
  9914. texture.height = height;
  9915. texture.isReady = true;
  9916. texture.samples = 1;
  9917. texture.generateMipMaps = fullOptions.generateMipMaps;
  9918. texture.samplingMode = fullOptions.samplingMode;
  9919. texture.type = fullOptions.type;
  9920. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  9921. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  9922. this.resetTextureCache();
  9923. this._internalTexturesCache.push(texture);
  9924. return texture;
  9925. };
  9926. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9927. var generateMipMaps = false;
  9928. var generateDepthBuffer = true;
  9929. var generateStencilBuffer = false;
  9930. var generateDepthTexture = false;
  9931. var textureCount = 1;
  9932. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9933. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9934. var types = [], samplingModes = [];
  9935. if (options !== undefined) {
  9936. generateMipMaps = options.generateMipMaps;
  9937. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9938. generateStencilBuffer = options.generateStencilBuffer;
  9939. generateDepthTexture = options.generateDepthTexture;
  9940. textureCount = options.textureCount || 1;
  9941. if (options.types) {
  9942. types = options.types;
  9943. }
  9944. if (options.samplingModes) {
  9945. samplingModes = options.samplingModes;
  9946. }
  9947. }
  9948. var gl = this._gl;
  9949. // Create the framebuffer
  9950. var framebuffer = gl.createFramebuffer();
  9951. this.bindUnboundFramebuffer(framebuffer);
  9952. var width = size.width || size;
  9953. var height = size.height || size;
  9954. var textures = [];
  9955. var attachments = [];
  9956. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9957. for (var i = 0; i < textureCount; i++) {
  9958. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9959. var type = types[i] || defaultType;
  9960. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9961. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9962. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9963. }
  9964. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9965. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9966. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9967. }
  9968. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9969. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9970. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9971. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9972. }
  9973. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  9974. var attachment = gl["COLOR_ATTACHMENT" + i];
  9975. textures.push(texture);
  9976. attachments.push(attachment);
  9977. gl.activeTexture(gl["TEXTURE" + i]);
  9978. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  9979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9980. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9981. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9982. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9983. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9984. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  9985. if (generateMipMaps) {
  9986. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9987. }
  9988. // Unbind
  9989. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9990. texture._framebuffer = framebuffer;
  9991. texture._depthStencilBuffer = depthStencilBuffer;
  9992. texture.baseWidth = width;
  9993. texture.baseHeight = height;
  9994. texture.width = width;
  9995. texture.height = height;
  9996. texture.isReady = true;
  9997. texture.samples = 1;
  9998. texture.generateMipMaps = generateMipMaps;
  9999. texture.samplingMode = samplingMode;
  10000. texture.type = type;
  10001. texture._generateDepthBuffer = generateDepthBuffer;
  10002. texture._generateStencilBuffer = generateStencilBuffer;
  10003. this._internalTexturesCache.push(texture);
  10004. }
  10005. if (generateDepthTexture) {
  10006. // Depth texture
  10007. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10008. gl.activeTexture(gl.TEXTURE0);
  10009. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10010. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10011. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10012. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10013. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10014. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  10015. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10016. depthTexture._framebuffer = framebuffer;
  10017. depthTexture.baseWidth = width;
  10018. depthTexture.baseHeight = height;
  10019. depthTexture.width = width;
  10020. depthTexture.height = height;
  10021. depthTexture.isReady = true;
  10022. depthTexture.samples = 1;
  10023. depthTexture.generateMipMaps = generateMipMaps;
  10024. depthTexture.samplingMode = gl.NEAREST;
  10025. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10026. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10027. textures.push(depthTexture);
  10028. this._internalTexturesCache.push(depthTexture);
  10029. }
  10030. gl.drawBuffers(attachments);
  10031. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10032. this.bindUnboundFramebuffer(null);
  10033. this.resetTextureCache();
  10034. return textures;
  10035. };
  10036. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10037. if (samples === void 0) { samples = 1; }
  10038. var depthStencilBuffer = null;
  10039. var gl = this._gl;
  10040. // Create the depth/stencil buffer
  10041. if (generateStencilBuffer) {
  10042. depthStencilBuffer = gl.createRenderbuffer();
  10043. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10044. if (samples > 1) {
  10045. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10046. }
  10047. else {
  10048. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10049. }
  10050. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10051. }
  10052. else if (generateDepthBuffer) {
  10053. depthStencilBuffer = gl.createRenderbuffer();
  10054. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10055. if (samples > 1) {
  10056. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10057. }
  10058. else {
  10059. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10060. }
  10061. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10062. }
  10063. return depthStencilBuffer;
  10064. };
  10065. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10066. if (this.webGLVersion < 2) {
  10067. return 1;
  10068. }
  10069. if (texture.samples === samples) {
  10070. return samples;
  10071. }
  10072. var gl = this._gl;
  10073. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10074. // Dispose previous render buffers
  10075. if (texture._depthStencilBuffer) {
  10076. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10077. }
  10078. if (texture._MSAAFramebuffer) {
  10079. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10080. }
  10081. if (texture._MSAARenderBuffer) {
  10082. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10083. }
  10084. if (samples > 1) {
  10085. texture._MSAAFramebuffer = gl.createFramebuffer();
  10086. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10087. var colorRenderbuffer = gl.createRenderbuffer();
  10088. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10089. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10090. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10091. texture._MSAARenderBuffer = colorRenderbuffer;
  10092. }
  10093. else {
  10094. this.bindUnboundFramebuffer(texture._framebuffer);
  10095. }
  10096. texture.samples = samples;
  10097. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10098. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10099. this.bindUnboundFramebuffer(null);
  10100. return samples;
  10101. };
  10102. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10103. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10104. };
  10105. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10106. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10107. };
  10108. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10109. var gl = this._gl;
  10110. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10111. var generateMipMaps = true;
  10112. var generateDepthBuffer = true;
  10113. var generateStencilBuffer = false;
  10114. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10115. if (options !== undefined) {
  10116. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10117. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10118. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10119. if (options.samplingMode !== undefined) {
  10120. samplingMode = options.samplingMode;
  10121. }
  10122. }
  10123. texture.isCube = true;
  10124. texture.generateMipMaps = generateMipMaps;
  10125. texture.samples = 1;
  10126. texture.samplingMode = samplingMode;
  10127. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10128. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10129. for (var face = 0; face < 6; face++) {
  10130. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10131. }
  10132. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10133. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10134. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10135. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10136. // Create the framebuffer
  10137. var framebuffer = gl.createFramebuffer();
  10138. this.bindUnboundFramebuffer(framebuffer);
  10139. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10140. // Mipmaps
  10141. if (texture.generateMipMaps) {
  10142. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10143. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10144. }
  10145. // Unbind
  10146. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10147. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10148. this.bindUnboundFramebuffer(null);
  10149. texture._framebuffer = framebuffer;
  10150. texture.width = size;
  10151. texture.height = size;
  10152. texture.isReady = true;
  10153. this.resetTextureCache();
  10154. this._internalTexturesCache.push(texture);
  10155. return texture;
  10156. };
  10157. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10158. var _this = this;
  10159. if (onError === void 0) { onError = null; }
  10160. if (forcedExtension === void 0) { forcedExtension = null; }
  10161. var callback = function (loadData) {
  10162. if (!loadData) {
  10163. if (onLoad) {
  10164. onLoad(null);
  10165. }
  10166. return;
  10167. }
  10168. var texture = loadData.texture;
  10169. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10170. texture._lodGenerationScale = scale;
  10171. texture._lodGenerationOffset = offset;
  10172. if (_this._caps.textureLOD) {
  10173. // Do not add extra process if texture lod is supported.
  10174. if (onLoad) {
  10175. onLoad(texture);
  10176. }
  10177. return;
  10178. }
  10179. var mipSlices = 3;
  10180. var gl = _this._gl;
  10181. var width = loadData.width;
  10182. if (!width) {
  10183. return;
  10184. }
  10185. var textures = [];
  10186. for (var i = 0; i < mipSlices; i++) {
  10187. //compute LOD from even spacing in smoothness (matching shader calculation)
  10188. var smoothness = i / (mipSlices - 1);
  10189. var roughness = 1 - smoothness;
  10190. var minLODIndex = offset; // roughness = 0
  10191. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10192. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10193. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10194. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10195. glTextureFromLod.isCube = true;
  10196. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10197. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10198. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10199. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10200. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10201. if (loadData.isDDS) {
  10202. var info = loadData.info;
  10203. var data = loadData.data;
  10204. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10205. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10206. }
  10207. else {
  10208. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10209. }
  10210. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10211. // Wrap in a base texture for easy binding.
  10212. var lodTexture = new BABYLON.BaseTexture(scene);
  10213. lodTexture.isCube = true;
  10214. lodTexture._texture = glTextureFromLod;
  10215. glTextureFromLod.isReady = true;
  10216. textures.push(lodTexture);
  10217. }
  10218. texture._lodTextureHigh = textures[2];
  10219. texture._lodTextureMid = textures[1];
  10220. texture._lodTextureLow = textures[0];
  10221. if (onLoad) {
  10222. onLoad(texture);
  10223. }
  10224. };
  10225. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10226. };
  10227. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10228. var _this = this;
  10229. if (onLoad === void 0) { onLoad = null; }
  10230. if (onError === void 0) { onError = null; }
  10231. if (forcedExtension === void 0) { forcedExtension = null; }
  10232. var gl = this._gl;
  10233. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10234. texture.isCube = true;
  10235. texture.url = rootUrl;
  10236. texture.generateMipMaps = !noMipmap;
  10237. if (!this._doNotHandleContextLost) {
  10238. texture._extension = forcedExtension;
  10239. texture._files = files;
  10240. }
  10241. var isKTX = false;
  10242. var isDDS = false;
  10243. var lastDot = rootUrl.lastIndexOf('.');
  10244. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10245. if (this._textureFormatInUse) {
  10246. extension = this._textureFormatInUse;
  10247. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10248. isKTX = true;
  10249. }
  10250. else {
  10251. isDDS = (extension === ".dds");
  10252. }
  10253. if (isKTX) {
  10254. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10255. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10256. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10257. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10258. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10259. ktx.uploadLevels(_this._gl, !noMipmap);
  10260. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10261. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10262. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10263. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10264. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10265. _this.resetTextureCache();
  10266. texture.width = ktx.pixelWidth;
  10267. texture.height = ktx.pixelHeight;
  10268. texture.isReady = true;
  10269. }, null, null, true, onError);
  10270. }
  10271. else if (isDDS) {
  10272. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10273. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10274. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10275. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10276. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10277. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10278. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10279. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10280. }
  10281. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10282. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10283. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10284. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10285. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10286. _this.resetTextureCache();
  10287. texture.width = info.width;
  10288. texture.height = info.height;
  10289. texture.isReady = true;
  10290. texture.type = info.textureType;
  10291. if (onLoad) {
  10292. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10293. }
  10294. }, null, null, true, onError);
  10295. }
  10296. else {
  10297. cascadeLoad(rootUrl, scene, function (imgs) {
  10298. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10299. var height = width;
  10300. _this._prepareWorkingCanvas();
  10301. _this._workingCanvas.width = width;
  10302. _this._workingCanvas.height = height;
  10303. var faces = [
  10304. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10305. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10306. ];
  10307. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10308. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10309. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10310. for (var index = 0; index < faces.length; index++) {
  10311. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10312. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10313. }
  10314. if (!noMipmap) {
  10315. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10316. }
  10317. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10318. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10319. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10320. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10321. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10322. _this.resetTextureCache();
  10323. texture.width = width;
  10324. texture.height = height;
  10325. texture.isReady = true;
  10326. texture.format = format;
  10327. texture.onLoadedObservable.notifyObservers(texture);
  10328. texture.onLoadedObservable.clear();
  10329. if (onLoad) {
  10330. onLoad();
  10331. }
  10332. }, files, onError);
  10333. }
  10334. this._internalTexturesCache.push(texture);
  10335. return texture;
  10336. };
  10337. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10338. if (compression === void 0) { compression = null; }
  10339. if (level === void 0) { level = 0; }
  10340. var gl = this._gl;
  10341. var textureType = this._getWebGLTextureType(type);
  10342. var internalFormat = this._getInternalFormat(format);
  10343. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10344. var needConversion = false;
  10345. if (internalFormat === gl.RGB) {
  10346. internalFormat = gl.RGBA;
  10347. needConversion = true;
  10348. }
  10349. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10350. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10351. if (texture.width % 4 !== 0) {
  10352. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10353. }
  10354. // Data are known to be in +X +Y +Z -X -Y -Z
  10355. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10356. var faceData = data[faceIndex];
  10357. if (compression) {
  10358. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10359. }
  10360. else {
  10361. if (needConversion) {
  10362. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10363. }
  10364. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10365. }
  10366. }
  10367. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10368. if (isPot && texture.generateMipMaps && level === 0) {
  10369. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10370. }
  10371. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10372. this.resetTextureCache();
  10373. texture.isReady = true;
  10374. };
  10375. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10376. if (compression === void 0) { compression = null; }
  10377. var gl = this._gl;
  10378. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10379. texture.isCube = true;
  10380. texture.generateMipMaps = generateMipMaps;
  10381. texture.format = format;
  10382. texture.type = type;
  10383. if (!this._doNotHandleContextLost) {
  10384. texture._bufferViewArray = data;
  10385. }
  10386. var textureType = this._getWebGLTextureType(type);
  10387. var internalFormat = this._getInternalFormat(format);
  10388. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10389. var needConversion = false;
  10390. if (internalFormat === gl.RGB) {
  10391. internalFormat = gl.RGBA;
  10392. needConversion = true;
  10393. }
  10394. var width = size;
  10395. var height = width;
  10396. texture.width = width;
  10397. texture.height = height;
  10398. // Double check on POT to generate Mips.
  10399. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10400. if (!isPot) {
  10401. generateMipMaps = false;
  10402. }
  10403. // Upload data if needed. The texture won't be ready until then.
  10404. if (data) {
  10405. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10406. }
  10407. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10408. // Filters
  10409. if (data && generateMipMaps) {
  10410. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10411. }
  10412. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10413. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10414. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10415. }
  10416. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10417. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10418. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10419. }
  10420. else {
  10421. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10424. }
  10425. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10426. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10427. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10428. return texture;
  10429. };
  10430. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10431. var _this = this;
  10432. if (onLoad === void 0) { onLoad = null; }
  10433. if (onError === void 0) { onError = null; }
  10434. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10435. if (invertY === void 0) { invertY = false; }
  10436. var gl = this._gl;
  10437. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10438. scene._addPendingData(texture);
  10439. texture.url = url;
  10440. this._internalTexturesCache.push(texture);
  10441. var onerror = function () {
  10442. scene._removePendingData(texture);
  10443. if (onError) {
  10444. onError();
  10445. }
  10446. };
  10447. var internalCallback = function (data) {
  10448. var width = texture.width;
  10449. var height = texture.height;
  10450. var faceDataArrays = callback(data);
  10451. if (mipmmapGenerator) {
  10452. var textureType = _this._getWebGLTextureType(type);
  10453. var internalFormat = _this._getInternalFormat(format);
  10454. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10455. var needConversion = false;
  10456. if (internalFormat === gl.RGB) {
  10457. internalFormat = gl.RGBA;
  10458. needConversion = true;
  10459. }
  10460. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10461. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10462. var mipData = mipmmapGenerator(faceDataArrays);
  10463. for (var level = 0; level < mipData.length; level++) {
  10464. var mipSize = width >> level;
  10465. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10466. var mipFaceData = mipData[level][faceIndex];
  10467. if (needConversion) {
  10468. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10469. }
  10470. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10471. }
  10472. }
  10473. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10474. }
  10475. else {
  10476. texture.generateMipMaps = !noMipmap;
  10477. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10478. }
  10479. texture.isReady = true;
  10480. _this.resetTextureCache();
  10481. scene._removePendingData(texture);
  10482. if (onLoad) {
  10483. onLoad();
  10484. }
  10485. };
  10486. BABYLON.Tools.LoadFile(url, function (data) {
  10487. internalCallback(data);
  10488. }, onerror, scene.database, true);
  10489. return texture;
  10490. };
  10491. ;
  10492. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10493. var gl = this._gl;
  10494. if (!gl) {
  10495. return;
  10496. }
  10497. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10498. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10500. if (!noMipmap && !isCompressed) {
  10501. gl.generateMipmap(gl.TEXTURE_2D);
  10502. }
  10503. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10504. this.resetTextureCache();
  10505. if (scene) {
  10506. scene._removePendingData(texture);
  10507. }
  10508. texture.onLoadedObservable.notifyObservers(texture);
  10509. texture.onLoadedObservable.clear();
  10510. };
  10511. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10512. var _this = this;
  10513. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10514. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10515. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10516. var gl = this._gl;
  10517. if (!gl) {
  10518. return;
  10519. }
  10520. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10521. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10522. texture.baseWidth = width;
  10523. texture.baseHeight = height;
  10524. texture.width = potWidth;
  10525. texture.height = potHeight;
  10526. texture.isReady = true;
  10527. if (processFunction(potWidth, potHeight, function () {
  10528. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10529. })) {
  10530. // Returning as texture needs extra async steps
  10531. return;
  10532. }
  10533. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10534. };
  10535. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10536. // Create new RGBA data container.
  10537. var rgbaData;
  10538. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10539. rgbaData = new Float32Array(width * height * 4);
  10540. }
  10541. else {
  10542. rgbaData = new Uint32Array(width * height * 4);
  10543. }
  10544. // Convert each pixel.
  10545. for (var x = 0; x < width; x++) {
  10546. for (var y = 0; y < height; y++) {
  10547. var index = (y * width + x) * 3;
  10548. var newIndex = (y * width + x) * 4;
  10549. // Map Old Value to new value.
  10550. rgbaData[newIndex + 0] = rgbData[index + 0];
  10551. rgbaData[newIndex + 1] = rgbData[index + 1];
  10552. rgbaData[newIndex + 2] = rgbData[index + 2];
  10553. // Add fully opaque alpha channel.
  10554. rgbaData[newIndex + 3] = 1;
  10555. }
  10556. }
  10557. return rgbaData;
  10558. };
  10559. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10560. var gl = this._gl;
  10561. if (texture._framebuffer) {
  10562. gl.deleteFramebuffer(texture._framebuffer);
  10563. texture._framebuffer = null;
  10564. }
  10565. if (texture._depthStencilBuffer) {
  10566. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10567. texture._depthStencilBuffer = null;
  10568. }
  10569. if (texture._MSAAFramebuffer) {
  10570. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10571. texture._MSAAFramebuffer = null;
  10572. }
  10573. if (texture._MSAARenderBuffer) {
  10574. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10575. texture._MSAARenderBuffer = null;
  10576. }
  10577. };
  10578. Engine.prototype._releaseTexture = function (texture) {
  10579. var gl = this._gl;
  10580. this._releaseFramebufferObjects(texture);
  10581. gl.deleteTexture(texture._webGLTexture);
  10582. // Unbind channels
  10583. this.unbindAllTextures();
  10584. var index = this._internalTexturesCache.indexOf(texture);
  10585. if (index !== -1) {
  10586. this._internalTexturesCache.splice(index, 1);
  10587. }
  10588. // Integrated fixed lod samplers.
  10589. if (texture._lodTextureHigh) {
  10590. texture._lodTextureHigh.dispose();
  10591. }
  10592. if (texture._lodTextureMid) {
  10593. texture._lodTextureMid.dispose();
  10594. }
  10595. if (texture._lodTextureLow) {
  10596. texture._lodTextureLow.dispose();
  10597. }
  10598. };
  10599. Engine.prototype.setProgram = function (program) {
  10600. if (this._currentProgram !== program) {
  10601. this._gl.useProgram(program);
  10602. this._currentProgram = program;
  10603. }
  10604. };
  10605. Engine.prototype.bindSamplers = function (effect) {
  10606. this.setProgram(effect.getProgram());
  10607. var samplers = effect.getSamplers();
  10608. for (var index = 0; index < samplers.length; index++) {
  10609. var uniform = effect.getUniform(samplers[index]);
  10610. this._gl.uniform1i(uniform, index);
  10611. }
  10612. this._currentEffect = null;
  10613. };
  10614. Engine.prototype.activateTexture = function (texture) {
  10615. if (this._activeTexture !== texture) {
  10616. this._gl.activeTexture(texture);
  10617. this._activeTexture = texture;
  10618. }
  10619. };
  10620. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10621. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10622. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10623. this._activeTexturesCache[this._activeTexture] = texture;
  10624. }
  10625. };
  10626. Engine.prototype._bindTexture = function (channel, texture) {
  10627. if (channel < 0) {
  10628. return;
  10629. }
  10630. this.activateTexture(this._gl.TEXTURE0 + channel);
  10631. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10632. };
  10633. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10634. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10635. };
  10636. Engine.prototype.unbindAllTextures = function () {
  10637. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10638. this.activateTexture(this._gl["TEXTURE" + channel]);
  10639. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10640. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10641. }
  10642. };
  10643. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10644. if (channel < 0) {
  10645. return;
  10646. }
  10647. this._gl.uniform1i(uniform, channel);
  10648. this._setTexture(channel, texture);
  10649. };
  10650. Engine.prototype._setTexture = function (channel, texture) {
  10651. // Not ready?
  10652. if (!texture) {
  10653. if (this._activeTexturesCache[channel] != null) {
  10654. this.activateTexture(this._gl["TEXTURE" + channel]);
  10655. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10656. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10657. }
  10658. return;
  10659. }
  10660. // Video
  10661. var alreadyActivated = false;
  10662. if (texture.video) {
  10663. this.activateTexture(this._gl["TEXTURE" + channel]);
  10664. alreadyActivated = true;
  10665. texture.update();
  10666. }
  10667. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10668. texture.delayLoad();
  10669. return;
  10670. }
  10671. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10672. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10673. if (this._activeTexturesCache[channel] === internalTexture) {
  10674. return;
  10675. }
  10676. if (!alreadyActivated) {
  10677. this.activateTexture(this._gl["TEXTURE" + channel]);
  10678. }
  10679. if (internalTexture.isCube) {
  10680. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10681. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10682. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10683. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10684. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10685. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10686. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10687. }
  10688. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10689. }
  10690. else {
  10691. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10692. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10693. internalTexture._cachedWrapU = texture.wrapU;
  10694. switch (texture.wrapU) {
  10695. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10696. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10697. break;
  10698. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10699. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10700. break;
  10701. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10702. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10703. break;
  10704. }
  10705. }
  10706. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10707. internalTexture._cachedWrapV = texture.wrapV;
  10708. switch (texture.wrapV) {
  10709. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10710. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10711. break;
  10712. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10713. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10714. break;
  10715. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10716. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10717. break;
  10718. }
  10719. }
  10720. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10721. }
  10722. };
  10723. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10724. if (channel < 0) {
  10725. return;
  10726. }
  10727. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10728. this._textureUnits = new Int32Array(textures.length);
  10729. }
  10730. for (var i = 0; i < textures.length; i++) {
  10731. this._textureUnits[i] = channel + i;
  10732. }
  10733. this._gl.uniform1iv(uniform, this._textureUnits);
  10734. for (var index = 0; index < textures.length; index++) {
  10735. this._setTexture(channel + index, textures[index]);
  10736. }
  10737. };
  10738. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10739. var internalTexture = texture.getInternalTexture();
  10740. if (!internalTexture) {
  10741. return;
  10742. }
  10743. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10744. var value = texture.anisotropicFilteringLevel;
  10745. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10746. value = 1;
  10747. }
  10748. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  10749. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10750. internalTexture._cachedAnisotropicFilteringLevel = value;
  10751. }
  10752. };
  10753. Engine.prototype.readPixels = function (x, y, width, height) {
  10754. var data = new Uint8Array(height * width * 4);
  10755. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10756. return data;
  10757. };
  10758. /**
  10759. * Add an externaly attached data from its key.
  10760. * This method call will fail and return false, if such key already exists.
  10761. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10762. * @param key the unique key that identifies the data
  10763. * @param data the data object to associate to the key for this Engine instance
  10764. * @return true if no such key were already present and the data was added successfully, false otherwise
  10765. */
  10766. Engine.prototype.addExternalData = function (key, data) {
  10767. if (!this._externalData) {
  10768. this._externalData = new BABYLON.StringDictionary();
  10769. }
  10770. return this._externalData.add(key, data);
  10771. };
  10772. /**
  10773. * Get an externaly attached data from its key
  10774. * @param key the unique key that identifies the data
  10775. * @return the associated data, if present (can be null), or undefined if not present
  10776. */
  10777. Engine.prototype.getExternalData = function (key) {
  10778. if (!this._externalData) {
  10779. this._externalData = new BABYLON.StringDictionary();
  10780. }
  10781. return this._externalData.get(key);
  10782. };
  10783. /**
  10784. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10785. * @param key the unique key that identifies the data
  10786. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10787. * @return the associated data, can be null if the factory returned null.
  10788. */
  10789. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10790. if (!this._externalData) {
  10791. this._externalData = new BABYLON.StringDictionary();
  10792. }
  10793. return this._externalData.getOrAddWithFactory(key, factory);
  10794. };
  10795. /**
  10796. * Remove an externaly attached data from the Engine instance
  10797. * @param key the unique key that identifies the data
  10798. * @return true if the data was successfully removed, false if it doesn't exist
  10799. */
  10800. Engine.prototype.removeExternalData = function (key) {
  10801. if (!this._externalData) {
  10802. this._externalData = new BABYLON.StringDictionary();
  10803. }
  10804. return this._externalData.remove(key);
  10805. };
  10806. Engine.prototype.unbindAllAttributes = function () {
  10807. if (this._mustWipeVertexAttributes) {
  10808. this._mustWipeVertexAttributes = false;
  10809. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10810. this._gl.disableVertexAttribArray(i);
  10811. this._vertexAttribArraysEnabled[i] = false;
  10812. this._currentBufferPointers[i].active = false;
  10813. }
  10814. return;
  10815. }
  10816. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10817. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10818. continue;
  10819. }
  10820. this._gl.disableVertexAttribArray(i);
  10821. this._vertexAttribArraysEnabled[i] = false;
  10822. this._currentBufferPointers[i].active = false;
  10823. }
  10824. };
  10825. Engine.prototype.releaseEffects = function () {
  10826. for (var name in this._compiledEffects) {
  10827. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10828. }
  10829. this._compiledEffects = {};
  10830. };
  10831. // Dispose
  10832. Engine.prototype.dispose = function () {
  10833. this.hideLoadingUI();
  10834. this.stopRenderLoop();
  10835. // Release postProcesses
  10836. while (this.postProcesses.length) {
  10837. this.postProcesses[0].dispose();
  10838. }
  10839. // Empty texture
  10840. if (this._emptyTexture) {
  10841. this._releaseTexture(this._emptyTexture);
  10842. this._emptyTexture = null;
  10843. }
  10844. if (this._emptyCubeTexture) {
  10845. this._releaseTexture(this._emptyCubeTexture);
  10846. this._emptyCubeTexture = null;
  10847. }
  10848. // Rescale PP
  10849. if (this._rescalePostProcess) {
  10850. this._rescalePostProcess.dispose();
  10851. }
  10852. // Release scenes
  10853. while (this.scenes.length) {
  10854. this.scenes[0].dispose();
  10855. }
  10856. // Release audio engine
  10857. if (Engine.audioEngine) {
  10858. Engine.audioEngine.dispose();
  10859. }
  10860. // Release effects
  10861. this.releaseEffects();
  10862. // Unbind
  10863. this.unbindAllAttributes();
  10864. if (this._dummyFramebuffer) {
  10865. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10866. }
  10867. this._gl = null;
  10868. //WebVR
  10869. this.disableVR();
  10870. // Events
  10871. window.removeEventListener("blur", this._onBlur);
  10872. window.removeEventListener("focus", this._onFocus);
  10873. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  10874. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  10875. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  10876. if (!this._doNotHandleContextLost) {
  10877. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  10878. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  10879. }
  10880. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10881. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10882. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10883. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10884. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10885. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10886. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10887. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10888. // Remove from Instances
  10889. var index = Engine.Instances.indexOf(this);
  10890. if (index >= 0) {
  10891. Engine.Instances.splice(index, 1);
  10892. }
  10893. this._workingCanvas = null;
  10894. this._workingContext = null;
  10895. this._currentBufferPointers = null;
  10896. this._renderingCanvas = null;
  10897. this._currentProgram = null;
  10898. this.onResizeObservable.clear();
  10899. this.onCanvasBlurObservable.clear();
  10900. BABYLON.Effect.ResetCache();
  10901. };
  10902. // Loading screen
  10903. Engine.prototype.displayLoadingUI = function () {
  10904. var loadingScreen = this.loadingScreen;
  10905. if (loadingScreen) {
  10906. loadingScreen.displayLoadingUI();
  10907. }
  10908. };
  10909. Engine.prototype.hideLoadingUI = function () {
  10910. var loadingScreen = this.loadingScreen;
  10911. if (loadingScreen) {
  10912. loadingScreen.hideLoadingUI();
  10913. }
  10914. };
  10915. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10916. get: function () {
  10917. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10918. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10919. return this._loadingScreen;
  10920. },
  10921. set: function (loadingScreen) {
  10922. this._loadingScreen = loadingScreen;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10928. set: function (text) {
  10929. this.loadingScreen.loadingUIText = text;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10935. set: function (color) {
  10936. this.loadingScreen.loadingUIBackgroundColor = color;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Engine.prototype.attachContextLostEvent = function (callback) {
  10942. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10943. };
  10944. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10945. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10946. };
  10947. Engine.prototype.getVertexShaderSource = function (program) {
  10948. var shaders = this._gl.getAttachedShaders(program);
  10949. return this._gl.getShaderSource(shaders[0]);
  10950. };
  10951. Engine.prototype.getFragmentShaderSource = function (program) {
  10952. var shaders = this._gl.getAttachedShaders(program);
  10953. return this._gl.getShaderSource(shaders[1]);
  10954. };
  10955. Engine.prototype.getError = function () {
  10956. return this._gl.getError();
  10957. };
  10958. // FPS
  10959. Engine.prototype.getFps = function () {
  10960. return this._fps;
  10961. };
  10962. Engine.prototype.getDeltaTime = function () {
  10963. return this._deltaTime;
  10964. };
  10965. Engine.prototype._measureFps = function () {
  10966. this._performanceMonitor.sampleFrame();
  10967. this._fps = this._performanceMonitor.averageFPS;
  10968. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  10969. };
  10970. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10971. if (faceIndex === void 0) { faceIndex = -1; }
  10972. var gl = this._gl;
  10973. if (!this._dummyFramebuffer) {
  10974. this._dummyFramebuffer = gl.createFramebuffer();
  10975. }
  10976. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10977. if (faceIndex > -1) {
  10978. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10979. }
  10980. else {
  10981. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10982. }
  10983. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  10984. var buffer;
  10985. switch (readType) {
  10986. case gl.UNSIGNED_BYTE:
  10987. buffer = new Uint8Array(4 * width * height);
  10988. readType = gl.UNSIGNED_BYTE;
  10989. break;
  10990. default:
  10991. buffer = new Float32Array(4 * width * height);
  10992. readType = gl.FLOAT;
  10993. break;
  10994. }
  10995. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  10996. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  10997. return buffer;
  10998. };
  10999. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11000. if (this._webGLVersion > 1) {
  11001. return this._caps.colorBufferFloat;
  11002. }
  11003. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11004. };
  11005. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11006. if (this._webGLVersion > 1) {
  11007. return this._caps.colorBufferFloat;
  11008. }
  11009. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11010. };
  11011. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11012. Engine.prototype._canRenderToFramebuffer = function (type) {
  11013. var gl = this._gl;
  11014. //clear existing errors
  11015. while (gl.getError() !== gl.NO_ERROR) { }
  11016. var successful = true;
  11017. var texture = gl.createTexture();
  11018. gl.bindTexture(gl.TEXTURE_2D, texture);
  11019. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11021. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11022. var fb = gl.createFramebuffer();
  11023. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11024. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11025. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11026. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11027. successful = successful && (gl.getError() === gl.NO_ERROR);
  11028. //try render by clearing frame buffer's color buffer
  11029. if (successful) {
  11030. gl.clear(gl.COLOR_BUFFER_BIT);
  11031. successful = successful && (gl.getError() === gl.NO_ERROR);
  11032. }
  11033. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11034. if (successful) {
  11035. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11036. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11037. var readFormat = gl.RGBA;
  11038. var readType = gl.UNSIGNED_BYTE;
  11039. var buffer = new Uint8Array(4);
  11040. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11041. successful = successful && (gl.getError() === gl.NO_ERROR);
  11042. }
  11043. //clean up
  11044. gl.deleteTexture(texture);
  11045. gl.deleteFramebuffer(fb);
  11046. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11047. //clear accumulated errors
  11048. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11049. return successful;
  11050. };
  11051. Engine.prototype._getWebGLTextureType = function (type) {
  11052. if (type === Engine.TEXTURETYPE_FLOAT) {
  11053. return this._gl.FLOAT;
  11054. }
  11055. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11056. // Add Half Float Constant.
  11057. return this._gl.HALF_FLOAT_OES;
  11058. }
  11059. return this._gl.UNSIGNED_BYTE;
  11060. };
  11061. ;
  11062. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11063. if (this._webGLVersion === 1) {
  11064. return this._gl.RGBA;
  11065. }
  11066. if (type === Engine.TEXTURETYPE_FLOAT) {
  11067. return this._gl.RGBA32F;
  11068. }
  11069. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11070. return this._gl.RGBA16F;
  11071. }
  11072. return this._gl.RGBA;
  11073. };
  11074. ;
  11075. Engine.prototype.createQuery = function () {
  11076. return this._gl.createQuery();
  11077. };
  11078. Engine.prototype.deleteQuery = function (query) {
  11079. this._gl.deleteQuery(query);
  11080. return this;
  11081. };
  11082. Engine.prototype.isQueryResultAvailable = function (query) {
  11083. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11084. };
  11085. Engine.prototype.getQueryResult = function (query) {
  11086. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11087. };
  11088. Engine.prototype.beginQuery = function (algorithmType, query) {
  11089. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11090. this._gl.beginQuery(glAlgorithm, query);
  11091. };
  11092. Engine.prototype.endQuery = function (algorithmType) {
  11093. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11094. this._gl.endQuery(glAlgorithm);
  11095. return this;
  11096. };
  11097. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11098. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11099. };
  11100. // Statics
  11101. Engine.isSupported = function () {
  11102. try {
  11103. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11104. if (navigator.isCocoonJS) {
  11105. return true;
  11106. }
  11107. var tempcanvas = document.createElement("canvas");
  11108. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11109. return gl != null && !!window.WebGLRenderingContext;
  11110. }
  11111. catch (e) {
  11112. return false;
  11113. }
  11114. };
  11115. Engine.Instances = new Array();
  11116. // Const statics
  11117. Engine._ALPHA_DISABLE = 0;
  11118. Engine._ALPHA_ADD = 1;
  11119. Engine._ALPHA_COMBINE = 2;
  11120. Engine._ALPHA_SUBTRACT = 3;
  11121. Engine._ALPHA_MULTIPLY = 4;
  11122. Engine._ALPHA_MAXIMIZED = 5;
  11123. Engine._ALPHA_ONEONE = 6;
  11124. Engine._ALPHA_PREMULTIPLIED = 7;
  11125. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11126. Engine._ALPHA_INTERPOLATE = 9;
  11127. Engine._ALPHA_SCREENMODE = 10;
  11128. Engine._DELAYLOADSTATE_NONE = 0;
  11129. Engine._DELAYLOADSTATE_LOADED = 1;
  11130. Engine._DELAYLOADSTATE_LOADING = 2;
  11131. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11132. Engine._TEXTUREFORMAT_ALPHA = 0;
  11133. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11134. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11135. Engine._TEXTUREFORMAT_RGB = 4;
  11136. Engine._TEXTUREFORMAT_RGBA = 5;
  11137. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11138. Engine._TEXTURETYPE_FLOAT = 1;
  11139. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11140. // Depht or Stencil test Constants.
  11141. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11142. 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.
  11143. 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.
  11144. 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.
  11145. 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.
  11146. 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.
  11147. 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.
  11148. 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.
  11149. // Stencil Actions Constants.
  11150. Engine._KEEP = 0x1E00;
  11151. Engine._REPLACE = 0x1E01;
  11152. Engine._INCR = 0x1E02;
  11153. Engine._DECR = 0x1E03;
  11154. Engine._INVERT = 0x150A;
  11155. Engine._INCR_WRAP = 0x8507;
  11156. Engine._DECR_WRAP = 0x8508;
  11157. // Texture rescaling mode
  11158. Engine._SCALEMODE_FLOOR = 1;
  11159. Engine._SCALEMODE_NEAREST = 2;
  11160. Engine._SCALEMODE_CEILING = 3;
  11161. // Updatable statics so stick with vars here
  11162. Engine.CollisionsEpsilon = 0.001;
  11163. Engine.CodeRepository = "src/";
  11164. Engine.ShadersRepository = "src/Shaders/";
  11165. return Engine;
  11166. }());
  11167. BABYLON.Engine = Engine;
  11168. })(BABYLON || (BABYLON = {}));
  11169. //# sourceMappingURL=babylon.engine.js.map
  11170. /// <reference path="Tools\babylon.decorators.ts" />
  11171. var BABYLON;
  11172. (function (BABYLON) {
  11173. /**
  11174. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11175. */
  11176. var Node = (function () {
  11177. /**
  11178. * @constructor
  11179. * @param {string} name - the name and id to be given to this node
  11180. * @param {BABYLON.Scene} the scene this node will be added to
  11181. */
  11182. function Node(name, scene) {
  11183. this.state = "";
  11184. this.metadata = null;
  11185. this.doNotSerialize = false;
  11186. this.animations = new Array();
  11187. this._ranges = {};
  11188. this._childrenFlag = -1;
  11189. this._isEnabled = true;
  11190. this._isReady = true;
  11191. this._currentRenderId = -1;
  11192. this._parentRenderId = -1;
  11193. /**
  11194. * An event triggered when the mesh is disposed.
  11195. * @type {BABYLON.Observable}
  11196. */
  11197. this.onDisposeObservable = new BABYLON.Observable();
  11198. // Behaviors
  11199. this._behaviors = new Array();
  11200. this.name = name;
  11201. this.id = name;
  11202. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11203. this._initCache();
  11204. }
  11205. Object.defineProperty(Node.prototype, "parent", {
  11206. get: function () {
  11207. return this._parentNode;
  11208. },
  11209. set: function (parent) {
  11210. if (this._parentNode === parent) {
  11211. return;
  11212. }
  11213. if (this._parentNode) {
  11214. var index = this._parentNode._children.indexOf(this);
  11215. if (index !== -1) {
  11216. this._parentNode._children.splice(index, 1);
  11217. }
  11218. }
  11219. this._parentNode = parent;
  11220. if (this._parentNode) {
  11221. if (!this._parentNode._children) {
  11222. this._parentNode._children = new Array();
  11223. }
  11224. this._parentNode._children.push(this);
  11225. }
  11226. },
  11227. enumerable: true,
  11228. configurable: true
  11229. });
  11230. Node.prototype.getClassName = function () {
  11231. return "Node";
  11232. };
  11233. Object.defineProperty(Node.prototype, "onDispose", {
  11234. set: function (callback) {
  11235. if (this._onDisposeObserver) {
  11236. this.onDisposeObservable.remove(this._onDisposeObserver);
  11237. }
  11238. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11239. },
  11240. enumerable: true,
  11241. configurable: true
  11242. });
  11243. Node.prototype.getScene = function () {
  11244. return this._scene;
  11245. };
  11246. Node.prototype.getEngine = function () {
  11247. return this._scene.getEngine();
  11248. };
  11249. Node.prototype.addBehavior = function (behavior) {
  11250. var index = this._behaviors.indexOf(behavior);
  11251. if (index !== -1) {
  11252. return;
  11253. }
  11254. behavior.attach(this);
  11255. this._behaviors.push(behavior);
  11256. return this;
  11257. };
  11258. Node.prototype.removeBehavior = function (behavior) {
  11259. var index = this._behaviors.indexOf(behavior);
  11260. if (index === -1) {
  11261. return;
  11262. }
  11263. this._behaviors[index].detach();
  11264. this._behaviors.splice(index, 1);
  11265. return this;
  11266. };
  11267. Object.defineProperty(Node.prototype, "behaviors", {
  11268. get: function () {
  11269. return this._behaviors;
  11270. },
  11271. enumerable: true,
  11272. configurable: true
  11273. });
  11274. Node.prototype.getBehaviorByName = function (name) {
  11275. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11276. var behavior = _a[_i];
  11277. if (behavior.name === name) {
  11278. return behavior;
  11279. }
  11280. }
  11281. return null;
  11282. };
  11283. // override it in derived class
  11284. Node.prototype.getWorldMatrix = function () {
  11285. return BABYLON.Matrix.Identity();
  11286. };
  11287. // override it in derived class if you add new variables to the cache
  11288. // and call the parent class method
  11289. Node.prototype._initCache = function () {
  11290. this._cache = {};
  11291. this._cache.parent = undefined;
  11292. };
  11293. Node.prototype.updateCache = function (force) {
  11294. if (!force && this.isSynchronized())
  11295. return;
  11296. this._cache.parent = this.parent;
  11297. this._updateCache();
  11298. };
  11299. // override it in derived class if you add new variables to the cache
  11300. // and call the parent class method if !ignoreParentClass
  11301. Node.prototype._updateCache = function (ignoreParentClass) {
  11302. };
  11303. // override it in derived class if you add new variables to the cache
  11304. Node.prototype._isSynchronized = function () {
  11305. return true;
  11306. };
  11307. Node.prototype._markSyncedWithParent = function () {
  11308. this._parentRenderId = this.parent._currentRenderId;
  11309. };
  11310. Node.prototype.isSynchronizedWithParent = function () {
  11311. if (!this.parent) {
  11312. return true;
  11313. }
  11314. if (this._parentRenderId !== this.parent._currentRenderId) {
  11315. return false;
  11316. }
  11317. return this.parent.isSynchronized();
  11318. };
  11319. Node.prototype.isSynchronized = function (updateCache) {
  11320. var check = this.hasNewParent();
  11321. check = check || !this.isSynchronizedWithParent();
  11322. check = check || !this._isSynchronized();
  11323. if (updateCache)
  11324. this.updateCache(true);
  11325. return !check;
  11326. };
  11327. Node.prototype.hasNewParent = function (update) {
  11328. if (this._cache.parent === this.parent)
  11329. return false;
  11330. if (update)
  11331. this._cache.parent = this.parent;
  11332. return true;
  11333. };
  11334. /**
  11335. * Is this node ready to be used/rendered
  11336. * @return {boolean} is it ready
  11337. */
  11338. Node.prototype.isReady = function () {
  11339. return this._isReady;
  11340. };
  11341. /**
  11342. * Is this node enabled.
  11343. * If the node has a parent and is enabled, the parent will be inspected as well.
  11344. * @return {boolean} whether this node (and its parent) is enabled.
  11345. * @see setEnabled
  11346. */
  11347. Node.prototype.isEnabled = function () {
  11348. if (!this._isEnabled) {
  11349. return false;
  11350. }
  11351. if (this.parent) {
  11352. return this.parent.isEnabled();
  11353. }
  11354. return true;
  11355. };
  11356. /**
  11357. * Set the enabled state of this node.
  11358. * @param {boolean} value - the new enabled state
  11359. * @see isEnabled
  11360. */
  11361. Node.prototype.setEnabled = function (value) {
  11362. this._isEnabled = value;
  11363. };
  11364. /**
  11365. * Is this node a descendant of the given node.
  11366. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11367. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11368. * @see parent
  11369. */
  11370. Node.prototype.isDescendantOf = function (ancestor) {
  11371. if (this.parent) {
  11372. if (this.parent === ancestor) {
  11373. return true;
  11374. }
  11375. return this.parent.isDescendantOf(ancestor);
  11376. }
  11377. return false;
  11378. };
  11379. /**
  11380. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11381. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11382. * @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.
  11383. * @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.
  11384. */
  11385. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11386. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11387. if (!this._children) {
  11388. return;
  11389. }
  11390. for (var index = 0; index < this._children.length; index++) {
  11391. var item = this._children[index];
  11392. if (!predicate || predicate(item)) {
  11393. results.push(item);
  11394. }
  11395. if (!directDescendantsOnly) {
  11396. item._getDescendants(results, false, predicate);
  11397. }
  11398. }
  11399. };
  11400. /**
  11401. * Will return all nodes that have this node as ascendant.
  11402. * @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.
  11403. * @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.
  11404. * @return {BABYLON.Node[]} all children nodes of all types.
  11405. */
  11406. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11407. var results = [];
  11408. this._getDescendants(results, directDescendantsOnly, predicate);
  11409. return results;
  11410. };
  11411. /**
  11412. * Get all child-meshes of this node.
  11413. */
  11414. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11415. var results = [];
  11416. this._getDescendants(results, directDecendantsOnly, function (node) {
  11417. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11418. });
  11419. return results;
  11420. };
  11421. /**
  11422. * Get all direct children of this node.
  11423. */
  11424. Node.prototype.getChildren = function (predicate) {
  11425. return this.getDescendants(true, predicate);
  11426. };
  11427. Node.prototype._setReady = function (state) {
  11428. if (state === this._isReady) {
  11429. return;
  11430. }
  11431. if (!state) {
  11432. this._isReady = false;
  11433. return;
  11434. }
  11435. this._isReady = true;
  11436. if (this.onReady) {
  11437. this.onReady(this);
  11438. }
  11439. };
  11440. Node.prototype.getAnimationByName = function (name) {
  11441. for (var i = 0; i < this.animations.length; i++) {
  11442. var animation = this.animations[i];
  11443. if (animation.name === name) {
  11444. return animation;
  11445. }
  11446. }
  11447. return null;
  11448. };
  11449. Node.prototype.createAnimationRange = function (name, from, to) {
  11450. // check name not already in use
  11451. if (!this._ranges[name]) {
  11452. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11453. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11454. if (this.animations[i]) {
  11455. this.animations[i].createRange(name, from, to);
  11456. }
  11457. }
  11458. }
  11459. };
  11460. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11461. if (deleteFrames === void 0) { deleteFrames = true; }
  11462. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11463. if (this.animations[i]) {
  11464. this.animations[i].deleteRange(name, deleteFrames);
  11465. }
  11466. }
  11467. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11468. };
  11469. Node.prototype.getAnimationRange = function (name) {
  11470. return this._ranges[name];
  11471. };
  11472. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11473. var range = this.getAnimationRange(name);
  11474. if (!range) {
  11475. return null;
  11476. }
  11477. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11478. };
  11479. Node.prototype.serializeAnimationRanges = function () {
  11480. var serializationRanges = [];
  11481. for (var name in this._ranges) {
  11482. var range = {};
  11483. range.name = name;
  11484. range.from = this._ranges[name].from;
  11485. range.to = this._ranges[name].to;
  11486. serializationRanges.push(range);
  11487. }
  11488. return serializationRanges;
  11489. };
  11490. Node.prototype.dispose = function () {
  11491. this.parent = null;
  11492. // Callback
  11493. this.onDisposeObservable.notifyObservers(this);
  11494. this.onDisposeObservable.clear();
  11495. // Behaviors
  11496. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11497. var behavior = _a[_i];
  11498. behavior.detach();
  11499. }
  11500. this._behaviors = [];
  11501. };
  11502. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11503. if (parsedNode.ranges) {
  11504. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11505. var data = parsedNode.ranges[index];
  11506. node.createAnimationRange(data.name, data.from, data.to);
  11507. }
  11508. }
  11509. };
  11510. __decorate([
  11511. BABYLON.serialize()
  11512. ], Node.prototype, "name", void 0);
  11513. __decorate([
  11514. BABYLON.serialize()
  11515. ], Node.prototype, "id", void 0);
  11516. __decorate([
  11517. BABYLON.serialize()
  11518. ], Node.prototype, "uniqueId", void 0);
  11519. __decorate([
  11520. BABYLON.serialize()
  11521. ], Node.prototype, "state", void 0);
  11522. __decorate([
  11523. BABYLON.serialize()
  11524. ], Node.prototype, "metadata", void 0);
  11525. return Node;
  11526. }());
  11527. BABYLON.Node = Node;
  11528. })(BABYLON || (BABYLON = {}));
  11529. //# sourceMappingURL=babylon.node.js.map
  11530. var BABYLON;
  11531. (function (BABYLON) {
  11532. var BoundingSphere = (function () {
  11533. function BoundingSphere(minimum, maximum) {
  11534. this.minimum = minimum;
  11535. this.maximum = maximum;
  11536. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11537. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11538. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11539. this.radius = distance * 0.5;
  11540. this.centerWorld = BABYLON.Vector3.Zero();
  11541. this._update(BABYLON.Matrix.Identity());
  11542. }
  11543. // Methods
  11544. BoundingSphere.prototype._update = function (world) {
  11545. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11546. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11547. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11548. };
  11549. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11550. for (var i = 0; i < 6; i++) {
  11551. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11552. return false;
  11553. }
  11554. return true;
  11555. };
  11556. BoundingSphere.prototype.intersectsPoint = function (point) {
  11557. var x = this.centerWorld.x - point.x;
  11558. var y = this.centerWorld.y - point.y;
  11559. var z = this.centerWorld.z - point.z;
  11560. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11561. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11562. return false;
  11563. return true;
  11564. };
  11565. // Statics
  11566. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11567. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11568. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11569. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11570. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11571. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11572. return false;
  11573. return true;
  11574. };
  11575. return BoundingSphere;
  11576. }());
  11577. BABYLON.BoundingSphere = BoundingSphere;
  11578. })(BABYLON || (BABYLON = {}));
  11579. //# sourceMappingURL=babylon.boundingSphere.js.map
  11580. var BABYLON;
  11581. (function (BABYLON) {
  11582. var BoundingBox = (function () {
  11583. function BoundingBox(minimum, maximum) {
  11584. this.minimum = minimum;
  11585. this.maximum = maximum;
  11586. this.vectors = new Array();
  11587. this.vectorsWorld = new Array();
  11588. // Bounding vectors
  11589. this.vectors.push(this.minimum.clone());
  11590. this.vectors.push(this.maximum.clone());
  11591. this.vectors.push(this.minimum.clone());
  11592. this.vectors[2].x = this.maximum.x;
  11593. this.vectors.push(this.minimum.clone());
  11594. this.vectors[3].y = this.maximum.y;
  11595. this.vectors.push(this.minimum.clone());
  11596. this.vectors[4].z = this.maximum.z;
  11597. this.vectors.push(this.maximum.clone());
  11598. this.vectors[5].z = this.minimum.z;
  11599. this.vectors.push(this.maximum.clone());
  11600. this.vectors[6].x = this.minimum.x;
  11601. this.vectors.push(this.maximum.clone());
  11602. this.vectors[7].y = this.minimum.y;
  11603. // OBB
  11604. this.center = this.maximum.add(this.minimum).scale(0.5);
  11605. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11606. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11607. // World
  11608. for (var index = 0; index < this.vectors.length; index++) {
  11609. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11610. }
  11611. this.minimumWorld = BABYLON.Vector3.Zero();
  11612. this.maximumWorld = BABYLON.Vector3.Zero();
  11613. this.centerWorld = BABYLON.Vector3.Zero();
  11614. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11615. this._update(BABYLON.Matrix.Identity());
  11616. }
  11617. // Methods
  11618. BoundingBox.prototype.getWorldMatrix = function () {
  11619. return this._worldMatrix;
  11620. };
  11621. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11622. this._worldMatrix.copyFrom(matrix);
  11623. return this;
  11624. };
  11625. BoundingBox.prototype._update = function (world) {
  11626. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11627. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11628. for (var index = 0; index < this.vectors.length; index++) {
  11629. var v = this.vectorsWorld[index];
  11630. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11631. if (v.x < this.minimumWorld.x)
  11632. this.minimumWorld.x = v.x;
  11633. if (v.y < this.minimumWorld.y)
  11634. this.minimumWorld.y = v.y;
  11635. if (v.z < this.minimumWorld.z)
  11636. this.minimumWorld.z = v.z;
  11637. if (v.x > this.maximumWorld.x)
  11638. this.maximumWorld.x = v.x;
  11639. if (v.y > this.maximumWorld.y)
  11640. this.maximumWorld.y = v.y;
  11641. if (v.z > this.maximumWorld.z)
  11642. this.maximumWorld.z = v.z;
  11643. }
  11644. // Extend
  11645. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11646. this.extendSizeWorld.scaleInPlace(0.5);
  11647. // OBB
  11648. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11649. this.centerWorld.scaleInPlace(0.5);
  11650. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11651. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11652. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11653. this._worldMatrix = world;
  11654. };
  11655. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11656. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11657. };
  11658. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11659. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11660. };
  11661. BoundingBox.prototype.intersectsPoint = function (point) {
  11662. var delta = -BABYLON.Epsilon;
  11663. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11664. return false;
  11665. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11666. return false;
  11667. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11668. return false;
  11669. return true;
  11670. };
  11671. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11672. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11673. };
  11674. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11675. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11676. return false;
  11677. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11678. return false;
  11679. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11680. return false;
  11681. return true;
  11682. };
  11683. // Statics
  11684. BoundingBox.Intersects = function (box0, box1) {
  11685. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11686. return false;
  11687. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11688. return false;
  11689. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11690. return false;
  11691. return true;
  11692. };
  11693. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11694. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11695. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11696. return (num <= (sphereRadius * sphereRadius));
  11697. };
  11698. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11699. for (var p = 0; p < 6; p++) {
  11700. for (var i = 0; i < 8; i++) {
  11701. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11702. return false;
  11703. }
  11704. }
  11705. }
  11706. return true;
  11707. };
  11708. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11709. for (var p = 0; p < 6; p++) {
  11710. var inCount = 8;
  11711. for (var i = 0; i < 8; i++) {
  11712. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11713. --inCount;
  11714. }
  11715. else {
  11716. break;
  11717. }
  11718. }
  11719. if (inCount === 0)
  11720. return false;
  11721. }
  11722. return true;
  11723. };
  11724. return BoundingBox;
  11725. }());
  11726. BABYLON.BoundingBox = BoundingBox;
  11727. })(BABYLON || (BABYLON = {}));
  11728. //# sourceMappingURL=babylon.boundingBox.js.map
  11729. var BABYLON;
  11730. (function (BABYLON) {
  11731. var computeBoxExtents = function (axis, box) {
  11732. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11733. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11734. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11735. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11736. var r = r0 + r1 + r2;
  11737. return {
  11738. min: p - r,
  11739. max: p + r
  11740. };
  11741. };
  11742. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11743. var axisOverlap = function (axis, box0, box1) {
  11744. var result0 = computeBoxExtents(axis, box0);
  11745. var result1 = computeBoxExtents(axis, box1);
  11746. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11747. };
  11748. var BoundingInfo = (function () {
  11749. function BoundingInfo(minimum, maximum) {
  11750. this.minimum = minimum;
  11751. this.maximum = maximum;
  11752. this._isLocked = false;
  11753. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11754. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11755. }
  11756. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11757. get: function () {
  11758. return this._isLocked;
  11759. },
  11760. set: function (value) {
  11761. this._isLocked = value;
  11762. },
  11763. enumerable: true,
  11764. configurable: true
  11765. });
  11766. // Methods
  11767. BoundingInfo.prototype.update = function (world) {
  11768. if (this._isLocked) {
  11769. return;
  11770. }
  11771. this.boundingBox._update(world);
  11772. this.boundingSphere._update(world);
  11773. };
  11774. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11775. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11776. return false;
  11777. return this.boundingBox.isInFrustum(frustumPlanes);
  11778. };
  11779. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  11780. /**
  11781. * Gets the world distance between the min and max points of the bounding box
  11782. */
  11783. get: function () {
  11784. var boundingBox = this.boundingBox;
  11785. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  11786. return size.length();
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11792. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11793. };
  11794. BoundingInfo.prototype._checkCollision = function (collider) {
  11795. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11796. };
  11797. BoundingInfo.prototype.intersectsPoint = function (point) {
  11798. if (!this.boundingSphere.centerWorld) {
  11799. return false;
  11800. }
  11801. if (!this.boundingSphere.intersectsPoint(point)) {
  11802. return false;
  11803. }
  11804. if (!this.boundingBox.intersectsPoint(point)) {
  11805. return false;
  11806. }
  11807. return true;
  11808. };
  11809. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11810. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11811. return false;
  11812. }
  11813. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11814. return false;
  11815. }
  11816. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11817. return false;
  11818. }
  11819. if (!precise) {
  11820. return true;
  11821. }
  11822. var box0 = this.boundingBox;
  11823. var box1 = boundingInfo.boundingBox;
  11824. if (!axisOverlap(box0.directions[0], box0, box1))
  11825. return false;
  11826. if (!axisOverlap(box0.directions[1], box0, box1))
  11827. return false;
  11828. if (!axisOverlap(box0.directions[2], box0, box1))
  11829. return false;
  11830. if (!axisOverlap(box1.directions[0], box0, box1))
  11831. return false;
  11832. if (!axisOverlap(box1.directions[1], box0, box1))
  11833. return false;
  11834. if (!axisOverlap(box1.directions[2], box0, box1))
  11835. return false;
  11836. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11837. return false;
  11838. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11839. return false;
  11840. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11841. return false;
  11842. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11843. return false;
  11844. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11845. return false;
  11846. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11847. return false;
  11848. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11849. return false;
  11850. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11851. return false;
  11852. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11853. return false;
  11854. return true;
  11855. };
  11856. return BoundingInfo;
  11857. }());
  11858. BABYLON.BoundingInfo = BoundingInfo;
  11859. })(BABYLON || (BABYLON = {}));
  11860. //# sourceMappingURL=babylon.boundingInfo.js.map
  11861. var BABYLON;
  11862. (function (BABYLON) {
  11863. var AbstractMesh = (function (_super) {
  11864. __extends(AbstractMesh, _super);
  11865. // Constructor
  11866. function AbstractMesh(name, scene) {
  11867. var _this = _super.call(this, name, scene) || this;
  11868. _this._facetNb = 0; // facet number
  11869. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11870. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11871. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11872. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11873. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11874. _this._subDiv = {
  11875. max: 1,
  11876. X: 1,
  11877. Y: 1,
  11878. Z: 1
  11879. };
  11880. // Events
  11881. /**
  11882. * An event triggered when this mesh collides with another one
  11883. * @type {BABYLON.Observable}
  11884. */
  11885. _this.onCollideObservable = new BABYLON.Observable();
  11886. /**
  11887. * An event triggered when the collision's position changes
  11888. * @type {BABYLON.Observable}
  11889. */
  11890. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11891. /**
  11892. * An event triggered after the world matrix is updated
  11893. * @type {BABYLON.Observable}
  11894. */
  11895. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11896. /**
  11897. * An event triggered when material is changed
  11898. * @type {BABYLON.Observable}
  11899. */
  11900. _this.onMaterialChangedObservable = new BABYLON.Observable();
  11901. // Properties
  11902. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11903. _this.position = BABYLON.Vector3.Zero();
  11904. /**
  11905. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  11906. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  11907. * or
  11908. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  11909. * for more info check WebGl documentations
  11910. */
  11911. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  11912. /**
  11913. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  11914. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  11915. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  11916. * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  11917. */
  11918. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  11919. /**
  11920. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  11921. * The default value is -1 which means don't break the query and wait till the result.
  11922. */
  11923. _this.occlusionRetryCount = -1;
  11924. _this._occlusionInternalRetryCounter = 0;
  11925. _this._isOccluded = false;
  11926. _this._isOcclusionQueryInProgress = false;
  11927. _this._rotation = BABYLON.Vector3.Zero();
  11928. _this._scaling = BABYLON.Vector3.One();
  11929. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11930. _this.visibility = 1.0;
  11931. _this.alphaIndex = Number.MAX_VALUE;
  11932. _this.infiniteDistance = false;
  11933. _this.isVisible = true;
  11934. _this.isPickable = true;
  11935. _this.showBoundingBox = false;
  11936. _this.showSubMeshesBoundingBox = false;
  11937. _this.isBlocker = false;
  11938. _this.enablePointerMoveEvents = false;
  11939. _this.renderingGroupId = 0;
  11940. _this._receiveShadows = false;
  11941. _this.renderOutline = false;
  11942. _this.outlineColor = BABYLON.Color3.Red();
  11943. _this.outlineWidth = 0.02;
  11944. _this.renderOverlay = false;
  11945. _this.overlayColor = BABYLON.Color3.Red();
  11946. _this.overlayAlpha = 0.5;
  11947. _this._hasVertexAlpha = false;
  11948. _this._useVertexColors = true;
  11949. _this._computeBonesUsingShaders = true;
  11950. _this._numBoneInfluencers = 4;
  11951. _this._applyFog = true;
  11952. _this.scalingDeterminant = 1;
  11953. _this.useOctreeForRenderingSelection = true;
  11954. _this.useOctreeForPicking = true;
  11955. _this.useOctreeForCollisions = true;
  11956. _this._layerMask = 0x0FFFFFFF;
  11957. /**
  11958. * True if the mesh must be rendered in any case.
  11959. */
  11960. _this.alwaysSelectAsActiveMesh = false;
  11961. // Collisions
  11962. _this._checkCollisions = false;
  11963. _this._collisionMask = -1;
  11964. _this._collisionGroup = -1;
  11965. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11966. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11967. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11968. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11969. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11970. // Edges
  11971. _this.edgesWidth = 1;
  11972. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11973. // Cache
  11974. _this._localWorld = BABYLON.Matrix.Zero();
  11975. _this._worldMatrix = BABYLON.Matrix.Zero();
  11976. _this._absolutePosition = BABYLON.Vector3.Zero();
  11977. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11978. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11979. _this._isDirty = false;
  11980. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11981. _this._isDisposed = false;
  11982. _this._renderId = 0;
  11983. _this._intersectionsInProgress = new Array();
  11984. _this._isWorldMatrixFrozen = false;
  11985. _this._unIndexed = false;
  11986. _this._lightSources = new Array();
  11987. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11988. if (collidedMesh === void 0) { collidedMesh = null; }
  11989. //TODO move this to the collision coordinator!
  11990. if (_this.getScene().workerCollisions)
  11991. newPosition.multiplyInPlace(_this._collider.radius);
  11992. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11993. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11994. _this.position.addInPlace(_this._diffPositionForCollisions);
  11995. }
  11996. if (collidedMesh) {
  11997. _this.onCollideObservable.notifyObservers(collidedMesh);
  11998. }
  11999. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12000. };
  12001. _this.getScene().addMesh(_this);
  12002. _this._resyncLightSources();
  12003. return _this;
  12004. }
  12005. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12006. get: function () {
  12007. return AbstractMesh._BILLBOARDMODE_NONE;
  12008. },
  12009. enumerable: true,
  12010. configurable: true
  12011. });
  12012. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12013. get: function () {
  12014. return AbstractMesh._BILLBOARDMODE_X;
  12015. },
  12016. enumerable: true,
  12017. configurable: true
  12018. });
  12019. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12020. get: function () {
  12021. return AbstractMesh._BILLBOARDMODE_Y;
  12022. },
  12023. enumerable: true,
  12024. configurable: true
  12025. });
  12026. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12027. get: function () {
  12028. return AbstractMesh._BILLBOARDMODE_Z;
  12029. },
  12030. enumerable: true,
  12031. configurable: true
  12032. });
  12033. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12034. get: function () {
  12035. return AbstractMesh._BILLBOARDMODE_ALL;
  12036. },
  12037. enumerable: true,
  12038. configurable: true
  12039. });
  12040. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12041. /**
  12042. * Read-only : the number of facets in the mesh
  12043. */
  12044. get: function () {
  12045. return this._facetNb;
  12046. },
  12047. enumerable: true,
  12048. configurable: true
  12049. });
  12050. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12051. /**
  12052. * The number (integer) of subdivisions per axis in the partioning space
  12053. */
  12054. get: function () {
  12055. return this._partitioningSubdivisions;
  12056. },
  12057. set: function (nb) {
  12058. this._partitioningSubdivisions = nb;
  12059. },
  12060. enumerable: true,
  12061. configurable: true
  12062. });
  12063. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12064. /**
  12065. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12066. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12067. */
  12068. get: function () {
  12069. return this._partitioningBBoxRatio;
  12070. },
  12071. set: function (ratio) {
  12072. this._partitioningBBoxRatio = ratio;
  12073. },
  12074. enumerable: true,
  12075. configurable: true
  12076. });
  12077. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12078. /**
  12079. * Read-only boolean : is the feature facetData enabled ?
  12080. */
  12081. get: function () {
  12082. return this._facetDataEnabled;
  12083. },
  12084. enumerable: true,
  12085. configurable: true
  12086. });
  12087. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12088. set: function (callback) {
  12089. if (this._onCollideObserver) {
  12090. this.onCollideObservable.remove(this._onCollideObserver);
  12091. }
  12092. this._onCollideObserver = this.onCollideObservable.add(callback);
  12093. },
  12094. enumerable: true,
  12095. configurable: true
  12096. });
  12097. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12098. set: function (callback) {
  12099. if (this._onCollisionPositionChangeObserver) {
  12100. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12101. }
  12102. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12103. },
  12104. enumerable: true,
  12105. configurable: true
  12106. });
  12107. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12108. /**
  12109. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  12110. */
  12111. get: function () {
  12112. return this._isOccluded;
  12113. },
  12114. set: function (value) {
  12115. this._isOccluded = value;
  12116. },
  12117. enumerable: true,
  12118. configurable: true
  12119. });
  12120. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12121. /**
  12122. * Flag to check the progress status of the query
  12123. */
  12124. get: function () {
  12125. return this._isOcclusionQueryInProgress;
  12126. },
  12127. enumerable: true,
  12128. configurable: true
  12129. });
  12130. Object.defineProperty(AbstractMesh.prototype, "material", {
  12131. get: function () {
  12132. return this._material;
  12133. },
  12134. set: function (value) {
  12135. if (this._material === value) {
  12136. return;
  12137. }
  12138. this._material = value;
  12139. if (this.onMaterialChangedObservable.hasObservers) {
  12140. this.onMaterialChangedObservable.notifyObservers(this);
  12141. }
  12142. if (!this.subMeshes) {
  12143. return;
  12144. }
  12145. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12146. var subMesh = _a[_i];
  12147. subMesh.setEffect(null);
  12148. }
  12149. },
  12150. enumerable: true,
  12151. configurable: true
  12152. });
  12153. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12154. get: function () {
  12155. return this._receiveShadows;
  12156. },
  12157. set: function (value) {
  12158. if (this._receiveShadows === value) {
  12159. return;
  12160. }
  12161. this._receiveShadows = value;
  12162. this._markSubMeshesAsLightDirty();
  12163. },
  12164. enumerable: true,
  12165. configurable: true
  12166. });
  12167. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12168. get: function () {
  12169. return this._hasVertexAlpha;
  12170. },
  12171. set: function (value) {
  12172. if (this._hasVertexAlpha === value) {
  12173. return;
  12174. }
  12175. this._hasVertexAlpha = value;
  12176. this._markSubMeshesAsAttributesDirty();
  12177. },
  12178. enumerable: true,
  12179. configurable: true
  12180. });
  12181. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12182. get: function () {
  12183. return this._useVertexColors;
  12184. },
  12185. set: function (value) {
  12186. if (this._useVertexColors === value) {
  12187. return;
  12188. }
  12189. this._useVertexColors = value;
  12190. this._markSubMeshesAsAttributesDirty();
  12191. },
  12192. enumerable: true,
  12193. configurable: true
  12194. });
  12195. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12196. get: function () {
  12197. return this._computeBonesUsingShaders;
  12198. },
  12199. set: function (value) {
  12200. if (this._computeBonesUsingShaders === value) {
  12201. return;
  12202. }
  12203. this._computeBonesUsingShaders = value;
  12204. this._markSubMeshesAsAttributesDirty();
  12205. },
  12206. enumerable: true,
  12207. configurable: true
  12208. });
  12209. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12210. get: function () {
  12211. return this._numBoneInfluencers;
  12212. },
  12213. set: function (value) {
  12214. if (this._numBoneInfluencers === value) {
  12215. return;
  12216. }
  12217. this._numBoneInfluencers = value;
  12218. this._markSubMeshesAsAttributesDirty();
  12219. },
  12220. enumerable: true,
  12221. configurable: true
  12222. });
  12223. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12224. get: function () {
  12225. return this._applyFog;
  12226. },
  12227. set: function (value) {
  12228. if (this._applyFog === value) {
  12229. return;
  12230. }
  12231. this._applyFog = value;
  12232. this._markSubMeshesAsMiscDirty();
  12233. },
  12234. enumerable: true,
  12235. configurable: true
  12236. });
  12237. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12238. get: function () {
  12239. return this._layerMask;
  12240. },
  12241. set: function (value) {
  12242. if (value === this._layerMask) {
  12243. return;
  12244. }
  12245. this._layerMask = value;
  12246. this._resyncLightSources();
  12247. },
  12248. enumerable: true,
  12249. configurable: true
  12250. });
  12251. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12252. get: function () {
  12253. return this._collisionMask;
  12254. },
  12255. set: function (mask) {
  12256. this._collisionMask = !isNaN(mask) ? mask : -1;
  12257. },
  12258. enumerable: true,
  12259. configurable: true
  12260. });
  12261. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12262. get: function () {
  12263. return this._collisionGroup;
  12264. },
  12265. set: function (mask) {
  12266. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12267. },
  12268. enumerable: true,
  12269. configurable: true
  12270. });
  12271. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12272. get: function () {
  12273. return null;
  12274. },
  12275. enumerable: true,
  12276. configurable: true
  12277. });
  12278. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12279. get: function () {
  12280. return this._skeleton;
  12281. },
  12282. set: function (value) {
  12283. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12284. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12285. }
  12286. if (value && value.needInitialSkinMatrix) {
  12287. value._registerMeshWithPoseMatrix(this);
  12288. }
  12289. this._skeleton = value;
  12290. if (!this._skeleton) {
  12291. this._bonesTransformMatrices = null;
  12292. }
  12293. this._markSubMeshesAsAttributesDirty();
  12294. },
  12295. enumerable: true,
  12296. configurable: true
  12297. });
  12298. /**
  12299. * Boolean : true if the mesh has been disposed.
  12300. */
  12301. AbstractMesh.prototype.isDisposed = function () {
  12302. return this._isDisposed;
  12303. };
  12304. /**
  12305. * Returns the string "AbstractMesh"
  12306. */
  12307. AbstractMesh.prototype.getClassName = function () {
  12308. return "AbstractMesh";
  12309. };
  12310. /**
  12311. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12312. */
  12313. AbstractMesh.prototype.toString = function (fullDetails) {
  12314. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12315. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12316. if (this._skeleton) {
  12317. ret += ", skeleton: " + this._skeleton.name;
  12318. }
  12319. if (fullDetails) {
  12320. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12321. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12322. }
  12323. return ret;
  12324. };
  12325. AbstractMesh.prototype._rebuild = function () {
  12326. if (this._occlusionQuery) {
  12327. this._occlusionQuery = null;
  12328. }
  12329. if (!this.subMeshes) {
  12330. return;
  12331. }
  12332. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12333. var subMesh = _a[_i];
  12334. subMesh._rebuild();
  12335. }
  12336. };
  12337. AbstractMesh.prototype._resyncLightSources = function () {
  12338. this._lightSources.length = 0;
  12339. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12340. var light = _a[_i];
  12341. if (!light.isEnabled()) {
  12342. continue;
  12343. }
  12344. if (light.canAffectMesh(this)) {
  12345. this._lightSources.push(light);
  12346. }
  12347. }
  12348. this._markSubMeshesAsLightDirty();
  12349. };
  12350. AbstractMesh.prototype._resyncLighSource = function (light) {
  12351. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12352. var index = this._lightSources.indexOf(light);
  12353. if (index === -1) {
  12354. if (!isIn) {
  12355. return;
  12356. }
  12357. this._lightSources.push(light);
  12358. }
  12359. else {
  12360. if (isIn) {
  12361. return;
  12362. }
  12363. this._lightSources.splice(index, 1);
  12364. }
  12365. this._markSubMeshesAsLightDirty();
  12366. };
  12367. AbstractMesh.prototype._removeLightSource = function (light) {
  12368. var index = this._lightSources.indexOf(light);
  12369. if (index === -1) {
  12370. return;
  12371. }
  12372. this._lightSources.splice(index, 1);
  12373. };
  12374. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12375. if (!this.subMeshes) {
  12376. return;
  12377. }
  12378. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12379. var subMesh = _a[_i];
  12380. if (subMesh._materialDefines) {
  12381. func(subMesh._materialDefines);
  12382. }
  12383. }
  12384. };
  12385. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12386. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12387. };
  12388. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12389. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12390. };
  12391. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12392. if (!this.subMeshes) {
  12393. return;
  12394. }
  12395. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12396. var subMesh = _a[_i];
  12397. var material = subMesh.getMaterial();
  12398. if (material) {
  12399. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12400. }
  12401. }
  12402. };
  12403. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12404. /**
  12405. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12406. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12407. * Default : (0.0, 0.0, 0.0)
  12408. */
  12409. get: function () {
  12410. return this._rotation;
  12411. },
  12412. set: function (newRotation) {
  12413. this._rotation = newRotation;
  12414. },
  12415. enumerable: true,
  12416. configurable: true
  12417. });
  12418. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12419. /**
  12420. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12421. * Default : (1.0, 1.0, 1.0)
  12422. */
  12423. get: function () {
  12424. return this._scaling;
  12425. },
  12426. set: function (newScaling) {
  12427. this._scaling = newScaling;
  12428. if (this.physicsImpostor) {
  12429. this.physicsImpostor.forceUpdate();
  12430. }
  12431. },
  12432. enumerable: true,
  12433. configurable: true
  12434. });
  12435. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12436. /**
  12437. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12438. * It's null by default.
  12439. * 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)
  12440. */
  12441. get: function () {
  12442. return this._rotationQuaternion;
  12443. },
  12444. set: function (quaternion) {
  12445. this._rotationQuaternion = quaternion;
  12446. //reset the rotation vector.
  12447. if (quaternion && this.rotation.length()) {
  12448. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12449. }
  12450. },
  12451. enumerable: true,
  12452. configurable: true
  12453. });
  12454. // Methods
  12455. /**
  12456. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12457. * Returns the AbstractMesh.
  12458. */
  12459. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12460. this._poseMatrix.copyFrom(matrix);
  12461. return this;
  12462. };
  12463. /**
  12464. * Returns the mesh Pose matrix.
  12465. * Returned object : Matrix
  12466. */
  12467. AbstractMesh.prototype.getPoseMatrix = function () {
  12468. return this._poseMatrix;
  12469. };
  12470. /**
  12471. * Disables the mesh edger rendering mode.
  12472. * Returns the AbstractMesh.
  12473. */
  12474. AbstractMesh.prototype.disableEdgesRendering = function () {
  12475. if (this._edgesRenderer !== undefined) {
  12476. this._edgesRenderer.dispose();
  12477. this._edgesRenderer = undefined;
  12478. }
  12479. return this;
  12480. };
  12481. /**
  12482. * Enables the edge rendering mode on the mesh.
  12483. * This mode makes the mesh edges visible.
  12484. * Returns the AbstractMesh.
  12485. */
  12486. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12487. if (epsilon === void 0) { epsilon = 0.95; }
  12488. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12489. this.disableEdgesRendering();
  12490. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12491. return this;
  12492. };
  12493. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12494. /**
  12495. * Returns true if the mesh is blocked. Used by the class Mesh.
  12496. * Returns the boolean `false` by default.
  12497. */
  12498. get: function () {
  12499. return false;
  12500. },
  12501. enumerable: true,
  12502. configurable: true
  12503. });
  12504. /**
  12505. * Returns the mesh itself by default, used by the class Mesh.
  12506. * Returned type : AbstractMesh
  12507. */
  12508. AbstractMesh.prototype.getLOD = function (camera) {
  12509. return this;
  12510. };
  12511. /**
  12512. * Returns 0 by default, used by the class Mesh.
  12513. * Returns an integer.
  12514. */
  12515. AbstractMesh.prototype.getTotalVertices = function () {
  12516. return 0;
  12517. };
  12518. /**
  12519. * Returns null by default, used by the class Mesh.
  12520. * Returned type : integer array
  12521. */
  12522. AbstractMesh.prototype.getIndices = function () {
  12523. return null;
  12524. };
  12525. /**
  12526. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12527. * Returned type : float array or Float32Array
  12528. */
  12529. AbstractMesh.prototype.getVerticesData = function (kind) {
  12530. return null;
  12531. };
  12532. /**
  12533. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12534. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12535. * The `data` are either a numeric array either a Float32Array.
  12536. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12537. * 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).
  12538. * Note that a new underlying VertexBuffer object is created each call.
  12539. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12540. *
  12541. * Possible `kind` values :
  12542. * - BABYLON.VertexBuffer.PositionKind
  12543. * - BABYLON.VertexBuffer.UVKind
  12544. * - BABYLON.VertexBuffer.UV2Kind
  12545. * - BABYLON.VertexBuffer.UV3Kind
  12546. * - BABYLON.VertexBuffer.UV4Kind
  12547. * - BABYLON.VertexBuffer.UV5Kind
  12548. * - BABYLON.VertexBuffer.UV6Kind
  12549. * - BABYLON.VertexBuffer.ColorKind
  12550. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12551. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12552. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12553. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12554. *
  12555. * Returns the Mesh.
  12556. */
  12557. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12558. return null;
  12559. };
  12560. /**
  12561. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12562. * If the mesh has no geometry, it is simply returned as it is.
  12563. * The `data` are either a numeric array either a Float32Array.
  12564. * No new underlying VertexBuffer object is created.
  12565. * 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.
  12566. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12567. *
  12568. * Possible `kind` values :
  12569. * - BABYLON.VertexBuffer.PositionKind
  12570. * - BABYLON.VertexBuffer.UVKind
  12571. * - BABYLON.VertexBuffer.UV2Kind
  12572. * - BABYLON.VertexBuffer.UV3Kind
  12573. * - BABYLON.VertexBuffer.UV4Kind
  12574. * - BABYLON.VertexBuffer.UV5Kind
  12575. * - BABYLON.VertexBuffer.UV6Kind
  12576. * - BABYLON.VertexBuffer.ColorKind
  12577. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12578. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12579. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12580. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12581. *
  12582. * Returns the Mesh.
  12583. */
  12584. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12585. return null;
  12586. };
  12587. /**
  12588. * Sets the mesh indices.
  12589. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12590. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12591. * This method creates a new index buffer each call.
  12592. * Returns the Mesh.
  12593. */
  12594. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12595. return null;
  12596. };
  12597. /** Returns false by default, used by the class Mesh.
  12598. * Returns a boolean
  12599. */
  12600. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12601. return false;
  12602. };
  12603. /**
  12604. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12605. * Returns a BoundingInfo
  12606. */
  12607. AbstractMesh.prototype.getBoundingInfo = function () {
  12608. if (this._masterMesh) {
  12609. return this._masterMesh.getBoundingInfo();
  12610. }
  12611. if (!this._boundingInfo) {
  12612. this._updateBoundingInfo();
  12613. }
  12614. return this._boundingInfo;
  12615. };
  12616. /**
  12617. * Sets a mesh new object BoundingInfo.
  12618. * Returns the AbstractMesh.
  12619. */
  12620. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12621. this._boundingInfo = boundingInfo;
  12622. return this;
  12623. };
  12624. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12625. get: function () {
  12626. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12627. },
  12628. enumerable: true,
  12629. configurable: true
  12630. });
  12631. AbstractMesh.prototype._preActivate = function () {
  12632. };
  12633. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12634. };
  12635. AbstractMesh.prototype._activate = function (renderId) {
  12636. this._renderId = renderId;
  12637. };
  12638. /**
  12639. * Returns the last update of the World matrix
  12640. * Returns a Matrix.
  12641. */
  12642. AbstractMesh.prototype.getWorldMatrix = function () {
  12643. if (this._masterMesh) {
  12644. return this._masterMesh.getWorldMatrix();
  12645. }
  12646. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12647. this.computeWorldMatrix();
  12648. }
  12649. return this._worldMatrix;
  12650. };
  12651. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12652. /**
  12653. * Returns directly the last state of the mesh World matrix.
  12654. * A Matrix is returned.
  12655. */
  12656. get: function () {
  12657. return this._worldMatrix;
  12658. },
  12659. enumerable: true,
  12660. configurable: true
  12661. });
  12662. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12663. /**
  12664. * Returns the current mesh absolute position.
  12665. * Retuns a Vector3.
  12666. */
  12667. get: function () {
  12668. return this._absolutePosition;
  12669. },
  12670. enumerable: true,
  12671. configurable: true
  12672. });
  12673. /**
  12674. * Prevents the World matrix to be computed any longer.
  12675. * Returns the AbstractMesh.
  12676. */
  12677. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12678. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12679. this.computeWorldMatrix(true);
  12680. this._isWorldMatrixFrozen = true;
  12681. return this;
  12682. };
  12683. /**
  12684. * Allows back the World matrix computation.
  12685. * Returns the AbstractMesh.
  12686. */
  12687. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12688. this._isWorldMatrixFrozen = false;
  12689. this.computeWorldMatrix(true);
  12690. return this;
  12691. };
  12692. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12693. /**
  12694. * True if the World matrix has been frozen.
  12695. * Returns a boolean.
  12696. */
  12697. get: function () {
  12698. return this._isWorldMatrixFrozen;
  12699. },
  12700. enumerable: true,
  12701. configurable: true
  12702. });
  12703. /**
  12704. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12705. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12706. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12707. * The passed axis is also normalized.
  12708. * Returns the AbstractMesh.
  12709. */
  12710. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12711. axis.normalize();
  12712. if (!this.rotationQuaternion) {
  12713. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12714. this.rotation = BABYLON.Vector3.Zero();
  12715. }
  12716. var rotationQuaternion;
  12717. if (!space || space === BABYLON.Space.LOCAL) {
  12718. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12719. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12720. }
  12721. else {
  12722. if (this.parent) {
  12723. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12724. invertParentWorldMatrix.invert();
  12725. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12726. }
  12727. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12728. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12729. }
  12730. return this;
  12731. };
  12732. /**
  12733. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12734. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12735. * The passed axis is also normalized.
  12736. * Returns the AbstractMesh.
  12737. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12738. */
  12739. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12740. axis.normalize();
  12741. if (!this.rotationQuaternion) {
  12742. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12743. this.rotation.copyFromFloats(0, 0, 0);
  12744. }
  12745. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12746. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12747. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12748. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12749. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12750. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12751. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12752. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12753. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12754. return this;
  12755. };
  12756. /**
  12757. * Translates the mesh along the axis vector for the passed distance in the given space.
  12758. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12759. * Returns the AbstractMesh.
  12760. */
  12761. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12762. var displacementVector = axis.scale(distance);
  12763. if (!space || space === BABYLON.Space.LOCAL) {
  12764. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12765. this.setPositionWithLocalVector(tempV3);
  12766. }
  12767. else {
  12768. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12769. }
  12770. return this;
  12771. };
  12772. /**
  12773. * Adds a rotation step to the mesh current rotation.
  12774. * x, y, z are Euler angles expressed in radians.
  12775. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12776. * This means this rotation is made in the mesh local space only.
  12777. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12778. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12779. * ```javascript
  12780. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12781. * ```
  12782. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12783. * 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.
  12784. * Returns the AbstractMesh.
  12785. */
  12786. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12787. var rotationQuaternion;
  12788. if (this.rotationQuaternion) {
  12789. rotationQuaternion = this.rotationQuaternion;
  12790. }
  12791. else {
  12792. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12793. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12794. }
  12795. var accumulation = BABYLON.Tmp.Quaternion[0];
  12796. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12797. rotationQuaternion.multiplyInPlace(accumulation);
  12798. if (!this.rotationQuaternion) {
  12799. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12800. }
  12801. return this;
  12802. };
  12803. /**
  12804. * Retuns the mesh absolute position in the World.
  12805. * Returns a Vector3.
  12806. */
  12807. AbstractMesh.prototype.getAbsolutePosition = function () {
  12808. this.computeWorldMatrix();
  12809. return this._absolutePosition;
  12810. };
  12811. /**
  12812. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12813. * Returns the AbstractMesh.
  12814. */
  12815. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12816. if (!absolutePosition) {
  12817. return;
  12818. }
  12819. var absolutePositionX;
  12820. var absolutePositionY;
  12821. var absolutePositionZ;
  12822. if (absolutePosition.x === undefined) {
  12823. if (arguments.length < 3) {
  12824. return;
  12825. }
  12826. absolutePositionX = arguments[0];
  12827. absolutePositionY = arguments[1];
  12828. absolutePositionZ = arguments[2];
  12829. }
  12830. else {
  12831. absolutePositionX = absolutePosition.x;
  12832. absolutePositionY = absolutePosition.y;
  12833. absolutePositionZ = absolutePosition.z;
  12834. }
  12835. if (this.parent) {
  12836. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12837. invertParentWorldMatrix.invert();
  12838. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12839. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12840. }
  12841. else {
  12842. this.position.x = absolutePositionX;
  12843. this.position.y = absolutePositionY;
  12844. this.position.z = absolutePositionZ;
  12845. }
  12846. return this;
  12847. };
  12848. // ================================== Point of View Movement =================================
  12849. /**
  12850. * Perform relative position change from the point of view of behind the front of the mesh.
  12851. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12852. * Supports definition of mesh facing forward or backward.
  12853. * @param {number} amountRight
  12854. * @param {number} amountUp
  12855. * @param {number} amountForward
  12856. *
  12857. * Returns the AbstractMesh.
  12858. */
  12859. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12860. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12861. return this;
  12862. };
  12863. /**
  12864. * Calculate relative position change from the point of view of behind the front of the mesh.
  12865. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12866. * Supports definition of mesh facing forward or backward.
  12867. * @param {number} amountRight
  12868. * @param {number} amountUp
  12869. * @param {number} amountForward
  12870. *
  12871. * Returns a new Vector3.
  12872. */
  12873. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12874. var rotMatrix = new BABYLON.Matrix();
  12875. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12876. rotQuaternion.toRotationMatrix(rotMatrix);
  12877. var translationDelta = BABYLON.Vector3.Zero();
  12878. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12879. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12880. return translationDelta;
  12881. };
  12882. // ================================== Point of View Rotation =================================
  12883. /**
  12884. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12885. * Supports definition of mesh facing forward or backward.
  12886. * @param {number} flipBack
  12887. * @param {number} twirlClockwise
  12888. * @param {number} tiltRight
  12889. *
  12890. * Returns the AbstractMesh.
  12891. */
  12892. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12893. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12894. return this;
  12895. };
  12896. /**
  12897. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12898. * Supports definition of mesh facing forward or backward.
  12899. * @param {number} flipBack
  12900. * @param {number} twirlClockwise
  12901. * @param {number} tiltRight
  12902. *
  12903. * Returns a new Vector3.
  12904. */
  12905. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12906. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12907. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12908. };
  12909. /**
  12910. * Sets a new pivot matrix to the mesh.
  12911. * Returns the AbstractMesh.
  12912. */
  12913. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12914. this._pivotMatrix = matrix;
  12915. this._cache.pivotMatrixUpdated = true;
  12916. return this;
  12917. };
  12918. /**
  12919. * Returns the mesh pivot matrix.
  12920. * Default : Identity.
  12921. * A Matrix is returned.
  12922. */
  12923. AbstractMesh.prototype.getPivotMatrix = function () {
  12924. return this._pivotMatrix;
  12925. };
  12926. AbstractMesh.prototype._isSynchronized = function () {
  12927. if (this._isDirty) {
  12928. return false;
  12929. }
  12930. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12931. return false;
  12932. if (this._cache.pivotMatrixUpdated) {
  12933. return false;
  12934. }
  12935. if (this.infiniteDistance) {
  12936. return false;
  12937. }
  12938. if (!this._cache.position.equals(this.position))
  12939. return false;
  12940. if (this.rotationQuaternion) {
  12941. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12942. return false;
  12943. }
  12944. if (!this._cache.rotation.equals(this.rotation))
  12945. return false;
  12946. if (!this._cache.scaling.equals(this.scaling))
  12947. return false;
  12948. return true;
  12949. };
  12950. AbstractMesh.prototype._initCache = function () {
  12951. _super.prototype._initCache.call(this);
  12952. this._cache.localMatrixUpdated = false;
  12953. this._cache.position = BABYLON.Vector3.Zero();
  12954. this._cache.scaling = BABYLON.Vector3.Zero();
  12955. this._cache.rotation = BABYLON.Vector3.Zero();
  12956. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12957. this._cache.billboardMode = -1;
  12958. };
  12959. AbstractMesh.prototype.markAsDirty = function (property) {
  12960. if (property === "rotation") {
  12961. this.rotationQuaternion = null;
  12962. }
  12963. this._currentRenderId = Number.MAX_VALUE;
  12964. this._isDirty = true;
  12965. return this;
  12966. };
  12967. /**
  12968. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12969. * Returns the AbstractMesh.
  12970. */
  12971. AbstractMesh.prototype._updateBoundingInfo = function () {
  12972. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12973. this._boundingInfo.update(this.worldMatrixFromCache);
  12974. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12975. return this;
  12976. };
  12977. /**
  12978. * Update a mesh's children BoundingInfo objects only.
  12979. * Returns the AbstractMesh.
  12980. */
  12981. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12982. if (!this.subMeshes) {
  12983. return;
  12984. }
  12985. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12986. var subMesh = this.subMeshes[subIndex];
  12987. if (!subMesh.IsGlobal) {
  12988. subMesh.updateBoundingInfo(matrix);
  12989. }
  12990. }
  12991. return this;
  12992. };
  12993. /**
  12994. * Computes the mesh World matrix and returns it.
  12995. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12996. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12997. * If the parameter `force`is set to `true`, the actual computation is done.
  12998. * Returns the mesh World Matrix.
  12999. */
  13000. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13001. if (this._isWorldMatrixFrozen) {
  13002. return this._worldMatrix;
  13003. }
  13004. if (!force && this.isSynchronized(true)) {
  13005. this._currentRenderId = this.getScene().getRenderId();
  13006. return this._worldMatrix;
  13007. }
  13008. this._cache.position.copyFrom(this.position);
  13009. this._cache.scaling.copyFrom(this.scaling);
  13010. this._cache.pivotMatrixUpdated = false;
  13011. this._cache.billboardMode = this.billboardMode;
  13012. this._currentRenderId = this.getScene().getRenderId();
  13013. this._isDirty = false;
  13014. // Scaling
  13015. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13016. // Rotation
  13017. //rotate, if quaternion is set and rotation was used
  13018. if (this.rotationQuaternion) {
  13019. var len = this.rotation.length();
  13020. if (len) {
  13021. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13022. this.rotation.copyFromFloats(0, 0, 0);
  13023. }
  13024. }
  13025. if (this.rotationQuaternion) {
  13026. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13027. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13028. }
  13029. else {
  13030. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13031. this._cache.rotation.copyFrom(this.rotation);
  13032. }
  13033. // Translation
  13034. if (this.infiniteDistance && !this.parent) {
  13035. var camera = this.getScene().activeCamera;
  13036. if (camera) {
  13037. var cameraWorldMatrix = camera.getWorldMatrix();
  13038. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13039. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13040. }
  13041. }
  13042. else {
  13043. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13044. }
  13045. // Composing transformations
  13046. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13047. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13048. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13049. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13050. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13051. // Need to decompose each rotation here
  13052. var currentPosition = BABYLON.Tmp.Vector3[3];
  13053. if (this.parent && this.parent.getWorldMatrix) {
  13054. if (this._meshToBoneReferal) {
  13055. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13056. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13057. }
  13058. else {
  13059. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13060. }
  13061. }
  13062. else {
  13063. currentPosition.copyFrom(this.position);
  13064. }
  13065. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13066. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13067. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13068. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13069. }
  13070. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13071. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13072. }
  13073. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13074. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13075. }
  13076. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13077. }
  13078. else {
  13079. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13080. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13081. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13082. }
  13083. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13084. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13085. }
  13086. // Local world
  13087. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13088. // Parent
  13089. if (this.parent && this.parent.getWorldMatrix) {
  13090. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13091. if (this._meshToBoneReferal) {
  13092. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13093. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13094. }
  13095. else {
  13096. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13097. }
  13098. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13099. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13100. this._worldMatrix.copyFrom(this._localWorld);
  13101. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13102. }
  13103. else {
  13104. if (this._meshToBoneReferal) {
  13105. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13106. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13107. }
  13108. else {
  13109. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13110. }
  13111. }
  13112. this._markSyncedWithParent();
  13113. }
  13114. else {
  13115. this._worldMatrix.copyFrom(this._localWorld);
  13116. }
  13117. // Bounding info
  13118. this._updateBoundingInfo();
  13119. // Absolute position
  13120. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13121. // Callbacks
  13122. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13123. if (!this._poseMatrix) {
  13124. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13125. }
  13126. return this._worldMatrix;
  13127. };
  13128. /**
  13129. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13130. * @param func: callback function to add
  13131. *
  13132. * Returns the AbstractMesh.
  13133. */
  13134. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13135. this.onAfterWorldMatrixUpdateObservable.add(func);
  13136. return this;
  13137. };
  13138. /**
  13139. * Removes a registered callback function.
  13140. * Returns the AbstractMesh.
  13141. */
  13142. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13143. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13144. return this;
  13145. };
  13146. /**
  13147. * Sets the mesh position in its local space.
  13148. * Returns the AbstractMesh.
  13149. */
  13150. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13151. this.computeWorldMatrix();
  13152. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13153. return this;
  13154. };
  13155. /**
  13156. * Returns the mesh position in the local space from the current World matrix values.
  13157. * Returns a new Vector3.
  13158. */
  13159. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13160. this.computeWorldMatrix();
  13161. var invLocalWorldMatrix = this._localWorld.clone();
  13162. invLocalWorldMatrix.invert();
  13163. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13164. };
  13165. /**
  13166. * Translates the mesh along the passed Vector3 in its local space.
  13167. * Returns the AbstractMesh.
  13168. */
  13169. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13170. this.computeWorldMatrix(true);
  13171. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13172. return this;
  13173. };
  13174. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13175. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13176. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13177. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13178. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13179. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13180. /// <returns>Mesh oriented towards targetMesh</returns>
  13181. if (yawCor === void 0) { yawCor = 0; }
  13182. if (pitchCor === void 0) { pitchCor = 0; }
  13183. if (rollCor === void 0) { rollCor = 0; }
  13184. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13185. var dv = AbstractMesh._lookAtVectorCache;
  13186. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13187. targetPoint.subtractToRef(pos, dv);
  13188. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13189. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13190. var pitch = Math.atan2(dv.y, len);
  13191. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13192. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13193. return this;
  13194. };
  13195. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13196. this._meshToBoneReferal = affectedMesh;
  13197. this.parent = bone;
  13198. if (bone.getWorldMatrix().determinant() < 0) {
  13199. this.scalingDeterminant *= -1;
  13200. }
  13201. return this;
  13202. };
  13203. AbstractMesh.prototype.detachFromBone = function () {
  13204. if (this.parent.getWorldMatrix().determinant() < 0) {
  13205. this.scalingDeterminant *= -1;
  13206. }
  13207. this._meshToBoneReferal = null;
  13208. this.parent = null;
  13209. return this;
  13210. };
  13211. /**
  13212. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13213. * A mesh is in the frustum if its bounding box intersects the frustum.
  13214. * Boolean returned.
  13215. */
  13216. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13217. return this._boundingInfo.isInFrustum(frustumPlanes);
  13218. };
  13219. /**
  13220. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13221. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13222. * Boolean returned.
  13223. */
  13224. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13225. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13226. ;
  13227. };
  13228. /**
  13229. * True if the mesh intersects another mesh or a SolidParticle object.
  13230. * 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)
  13231. * Returns a boolean.
  13232. */
  13233. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13234. if (!this._boundingInfo || !mesh._boundingInfo) {
  13235. return false;
  13236. }
  13237. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13238. };
  13239. /**
  13240. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13241. * Returns a boolean.
  13242. */
  13243. AbstractMesh.prototype.intersectsPoint = function (point) {
  13244. if (!this._boundingInfo) {
  13245. return false;
  13246. }
  13247. return this._boundingInfo.intersectsPoint(point);
  13248. };
  13249. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13250. return this.physicsImpostor;
  13251. };
  13252. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13253. if (!camera) {
  13254. camera = this.getScene().activeCamera;
  13255. }
  13256. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13257. };
  13258. /**
  13259. * Returns the distance from the mesh to the active camera.
  13260. * Returns a float.
  13261. */
  13262. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13263. if (!camera) {
  13264. camera = this.getScene().activeCamera;
  13265. }
  13266. return this.absolutePosition.subtract(camera.position).length();
  13267. };
  13268. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13269. if (!this.physicsImpostor) {
  13270. return;
  13271. }
  13272. this.physicsImpostor.applyImpulse(force, contactPoint);
  13273. return this;
  13274. };
  13275. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13276. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13277. return;
  13278. }
  13279. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13280. mainPivot: pivot1,
  13281. connectedPivot: pivot2,
  13282. nativeParams: options
  13283. });
  13284. return this;
  13285. };
  13286. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13287. // Collisions
  13288. /**
  13289. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13290. * Default `false`.
  13291. */
  13292. get: function () {
  13293. return this._checkCollisions;
  13294. },
  13295. set: function (collisionEnabled) {
  13296. this._checkCollisions = collisionEnabled;
  13297. if (this.getScene().workerCollisions) {
  13298. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13299. }
  13300. },
  13301. enumerable: true,
  13302. configurable: true
  13303. });
  13304. AbstractMesh.prototype.moveWithCollisions = function (direction) {
  13305. var globalPosition = this.getAbsolutePosition();
  13306. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13307. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13308. if (!this._collider) {
  13309. this._collider = new BABYLON.Collider();
  13310. }
  13311. this._collider.radius = this.ellipsoid;
  13312. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, direction, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13313. return this;
  13314. };
  13315. // Submeshes octree
  13316. /**
  13317. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13318. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13319. * Returns an Octree of submeshes.
  13320. */
  13321. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13322. if (maxCapacity === void 0) { maxCapacity = 64; }
  13323. if (maxDepth === void 0) { maxDepth = 2; }
  13324. if (!this._submeshesOctree) {
  13325. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13326. }
  13327. this.computeWorldMatrix(true);
  13328. // Update octree
  13329. var bbox = this.getBoundingInfo().boundingBox;
  13330. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13331. return this._submeshesOctree;
  13332. };
  13333. // Collisions
  13334. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13335. this._generatePointsArray();
  13336. // Transformation
  13337. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13338. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13339. subMesh._lastColliderWorldVertices = [];
  13340. subMesh._trianglePlanes = [];
  13341. var start = subMesh.verticesStart;
  13342. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13343. for (var i = start; i < end; i++) {
  13344. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13345. }
  13346. }
  13347. // Collide
  13348. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13349. if (collider.collisionFound) {
  13350. collider.collidedMesh = this;
  13351. }
  13352. return this;
  13353. };
  13354. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13355. var subMeshes;
  13356. var len;
  13357. // Octrees
  13358. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13359. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13360. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13361. len = intersections.length;
  13362. subMeshes = intersections.data;
  13363. }
  13364. else {
  13365. subMeshes = this.subMeshes;
  13366. len = subMeshes.length;
  13367. }
  13368. for (var index = 0; index < len; index++) {
  13369. var subMesh = subMeshes[index];
  13370. // Bounding test
  13371. if (len > 1 && !subMesh._checkCollision(collider))
  13372. continue;
  13373. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13374. }
  13375. return this;
  13376. };
  13377. AbstractMesh.prototype._checkCollision = function (collider) {
  13378. // Bounding box test
  13379. if (!this._boundingInfo._checkCollision(collider))
  13380. return this;
  13381. // Transformation matrix
  13382. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13383. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13384. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13385. return this;
  13386. };
  13387. // Picking
  13388. AbstractMesh.prototype._generatePointsArray = function () {
  13389. return false;
  13390. };
  13391. /**
  13392. * Checks if the passed Ray intersects with the mesh.
  13393. * Returns an object PickingInfo.
  13394. */
  13395. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13396. var pickingInfo = new BABYLON.PickingInfo();
  13397. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13398. return pickingInfo;
  13399. }
  13400. if (!this._generatePointsArray()) {
  13401. return pickingInfo;
  13402. }
  13403. var intersectInfo = null;
  13404. // Octrees
  13405. var subMeshes;
  13406. var len;
  13407. if (this._submeshesOctree && this.useOctreeForPicking) {
  13408. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13409. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13410. len = intersections.length;
  13411. subMeshes = intersections.data;
  13412. }
  13413. else {
  13414. subMeshes = this.subMeshes;
  13415. len = subMeshes.length;
  13416. }
  13417. for (var index = 0; index < len; index++) {
  13418. var subMesh = subMeshes[index];
  13419. // Bounding test
  13420. if (len > 1 && !subMesh.canIntersects(ray))
  13421. continue;
  13422. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13423. if (currentIntersectInfo) {
  13424. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13425. intersectInfo = currentIntersectInfo;
  13426. intersectInfo.subMeshId = index;
  13427. if (fastCheck) {
  13428. break;
  13429. }
  13430. }
  13431. }
  13432. }
  13433. if (intersectInfo) {
  13434. // Get picked point
  13435. var world = this.getWorldMatrix();
  13436. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13437. var direction = ray.direction.clone();
  13438. direction = direction.scale(intersectInfo.distance);
  13439. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13440. var pickedPoint = worldOrigin.add(worldDirection);
  13441. // Return result
  13442. pickingInfo.hit = true;
  13443. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13444. pickingInfo.pickedPoint = pickedPoint;
  13445. pickingInfo.pickedMesh = this;
  13446. pickingInfo.bu = intersectInfo.bu;
  13447. pickingInfo.bv = intersectInfo.bv;
  13448. pickingInfo.faceId = intersectInfo.faceId;
  13449. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13450. return pickingInfo;
  13451. }
  13452. return pickingInfo;
  13453. };
  13454. /**
  13455. * Clones the mesh, used by the class Mesh.
  13456. * Just returns `null` for an AbstractMesh.
  13457. */
  13458. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13459. return null;
  13460. };
  13461. /**
  13462. * Disposes all the mesh submeshes.
  13463. * Returns the AbstractMesh.
  13464. */
  13465. AbstractMesh.prototype.releaseSubMeshes = function () {
  13466. if (this.subMeshes) {
  13467. while (this.subMeshes.length) {
  13468. this.subMeshes[0].dispose();
  13469. }
  13470. }
  13471. else {
  13472. this.subMeshes = new Array();
  13473. }
  13474. return this;
  13475. };
  13476. /**
  13477. * Disposes the AbstractMesh.
  13478. * Some internal references are kept for further use.
  13479. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13480. * Returns nothing.
  13481. */
  13482. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13483. var _this = this;
  13484. var index;
  13485. // Action manager
  13486. if (this.actionManager) {
  13487. this.actionManager.dispose();
  13488. this.actionManager = null;
  13489. }
  13490. // Skeleton
  13491. this.skeleton = null;
  13492. // Animations
  13493. this.getScene().stopAnimation(this);
  13494. // Physics
  13495. if (this.physicsImpostor) {
  13496. this.physicsImpostor.dispose();
  13497. }
  13498. // Intersections in progress
  13499. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13500. var other = this._intersectionsInProgress[index];
  13501. var pos = other._intersectionsInProgress.indexOf(this);
  13502. other._intersectionsInProgress.splice(pos, 1);
  13503. }
  13504. this._intersectionsInProgress = [];
  13505. // Lights
  13506. var lights = this.getScene().lights;
  13507. lights.forEach(function (light) {
  13508. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13509. if (meshIndex !== -1) {
  13510. light.includedOnlyMeshes.splice(meshIndex, 1);
  13511. }
  13512. meshIndex = light.excludedMeshes.indexOf(_this);
  13513. if (meshIndex !== -1) {
  13514. light.excludedMeshes.splice(meshIndex, 1);
  13515. }
  13516. // Shadow generators
  13517. var generator = light.getShadowGenerator();
  13518. if (generator) {
  13519. var shadowMap = generator.getShadowMap();
  13520. meshIndex = shadowMap.renderList.indexOf(_this);
  13521. if (meshIndex !== -1) {
  13522. shadowMap.renderList.splice(meshIndex, 1);
  13523. }
  13524. }
  13525. });
  13526. // Edges
  13527. if (this._edgesRenderer) {
  13528. this._edgesRenderer.dispose();
  13529. this._edgesRenderer = null;
  13530. }
  13531. // SubMeshes
  13532. if (this.getClassName() !== "InstancedMesh") {
  13533. this.releaseSubMeshes();
  13534. }
  13535. // Octree
  13536. var sceneOctree = this.getScene().selectionOctree;
  13537. if (sceneOctree) {
  13538. var index = sceneOctree.dynamicContent.indexOf(this);
  13539. if (index !== -1) {
  13540. sceneOctree.dynamicContent.splice(index, 1);
  13541. }
  13542. }
  13543. // Query
  13544. var engine = this.getScene().getEngine();
  13545. if (this._occlusionQuery) {
  13546. this._isOcclusionQueryInProgress = false;
  13547. engine.deleteQuery(this._occlusionQuery);
  13548. this._occlusionQuery = null;
  13549. }
  13550. // Engine
  13551. engine.wipeCaches();
  13552. // Remove from scene
  13553. this.getScene().removeMesh(this);
  13554. if (!doNotRecurse) {
  13555. // Particles
  13556. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13557. if (this.getScene().particleSystems[index].emitter === this) {
  13558. this.getScene().particleSystems[index].dispose();
  13559. index--;
  13560. }
  13561. }
  13562. // Children
  13563. var objects = this.getDescendants(true);
  13564. for (index = 0; index < objects.length; index++) {
  13565. objects[index].dispose();
  13566. }
  13567. }
  13568. else {
  13569. var childMeshes = this.getChildMeshes(true);
  13570. for (index = 0; index < childMeshes.length; index++) {
  13571. var child = childMeshes[index];
  13572. child.parent = null;
  13573. child.computeWorldMatrix(true);
  13574. }
  13575. }
  13576. // facet data
  13577. if (this._facetDataEnabled) {
  13578. this.disableFacetData();
  13579. }
  13580. this.onAfterWorldMatrixUpdateObservable.clear();
  13581. this.onCollideObservable.clear();
  13582. this.onCollisionPositionChangeObservable.clear();
  13583. this._isDisposed = true;
  13584. _super.prototype.dispose.call(this);
  13585. };
  13586. /**
  13587. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13588. * This Vector3 is expressed in the World space.
  13589. */
  13590. AbstractMesh.prototype.getDirection = function (localAxis) {
  13591. var result = BABYLON.Vector3.Zero();
  13592. this.getDirectionToRef(localAxis, result);
  13593. return result;
  13594. };
  13595. /**
  13596. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13597. * localAxis is expressed in the mesh local space.
  13598. * result is computed in the Wordl space from the mesh World matrix.
  13599. * Returns the AbstractMesh.
  13600. */
  13601. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13602. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13603. return this;
  13604. };
  13605. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13606. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13607. if (this.getScene().getRenderId() == 0) {
  13608. this.computeWorldMatrix(true);
  13609. }
  13610. var wm = this.getWorldMatrix();
  13611. if (space == BABYLON.Space.WORLD) {
  13612. var tmat = BABYLON.Tmp.Matrix[0];
  13613. wm.invertToRef(tmat);
  13614. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13615. }
  13616. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13617. this._pivotMatrix.m[12] = -point.x;
  13618. this._pivotMatrix.m[13] = -point.y;
  13619. this._pivotMatrix.m[14] = -point.z;
  13620. this._cache.pivotMatrixUpdated = true;
  13621. return this;
  13622. };
  13623. /**
  13624. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13625. */
  13626. AbstractMesh.prototype.getPivotPoint = function () {
  13627. var point = BABYLON.Vector3.Zero();
  13628. this.getPivotPointToRef(point);
  13629. return point;
  13630. };
  13631. /**
  13632. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13633. * Returns the AbstractMesh.
  13634. */
  13635. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13636. result.x = -this._pivotMatrix.m[12];
  13637. result.y = -this._pivotMatrix.m[13];
  13638. result.z = -this._pivotMatrix.m[14];
  13639. return this;
  13640. };
  13641. /**
  13642. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13643. */
  13644. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13645. var point = BABYLON.Vector3.Zero();
  13646. this.getAbsolutePivotPointToRef(point);
  13647. return point;
  13648. };
  13649. /**
  13650. * Defines the passed mesh as the parent of the current mesh.
  13651. * Returns the AbstractMesh.
  13652. */
  13653. AbstractMesh.prototype.setParent = function (mesh) {
  13654. var child = this;
  13655. var parent = mesh;
  13656. if (mesh == null) {
  13657. var rotation = BABYLON.Tmp.Quaternion[0];
  13658. var position = BABYLON.Tmp.Vector3[0];
  13659. var scale = BABYLON.Tmp.Vector3[1];
  13660. child.getWorldMatrix().decompose(scale, rotation, position);
  13661. if (child.rotationQuaternion) {
  13662. child.rotationQuaternion.copyFrom(rotation);
  13663. }
  13664. else {
  13665. rotation.toEulerAnglesToRef(child.rotation);
  13666. }
  13667. child.position.x = position.x;
  13668. child.position.y = position.y;
  13669. child.position.z = position.z;
  13670. }
  13671. else {
  13672. var rotation = BABYLON.Tmp.Quaternion[0];
  13673. var position = BABYLON.Tmp.Vector3[0];
  13674. var scale = BABYLON.Tmp.Vector3[1];
  13675. var m1 = BABYLON.Tmp.Matrix[0];
  13676. var m2 = BABYLON.Tmp.Matrix[1];
  13677. parent.getWorldMatrix().decompose(scale, rotation, position);
  13678. rotation.toRotationMatrix(m1);
  13679. m2.setTranslation(position);
  13680. m2.multiplyToRef(m1, m1);
  13681. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13682. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13683. m.decompose(scale, rotation, position);
  13684. if (child.rotationQuaternion) {
  13685. child.rotationQuaternion.copyFrom(rotation);
  13686. }
  13687. else {
  13688. rotation.toEulerAnglesToRef(child.rotation);
  13689. }
  13690. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13691. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13692. m.decompose(scale, rotation, position);
  13693. child.position.x = position.x;
  13694. child.position.y = position.y;
  13695. child.position.z = position.z;
  13696. }
  13697. child.parent = parent;
  13698. return this;
  13699. };
  13700. /**
  13701. * Adds the passed mesh as a child to the current mesh.
  13702. * Returns the AbstractMesh.
  13703. */
  13704. AbstractMesh.prototype.addChild = function (mesh) {
  13705. mesh.setParent(this);
  13706. return this;
  13707. };
  13708. /**
  13709. * Removes the passed mesh from the current mesh children list.
  13710. * Returns the AbstractMesh.
  13711. */
  13712. AbstractMesh.prototype.removeChild = function (mesh) {
  13713. mesh.setParent(null);
  13714. return this;
  13715. };
  13716. /**
  13717. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13718. * Returns the AbstractMesh.
  13719. */
  13720. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13721. result.x = this._pivotMatrix.m[12];
  13722. result.y = this._pivotMatrix.m[13];
  13723. result.z = this._pivotMatrix.m[14];
  13724. this.getPivotPointToRef(result);
  13725. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13726. return this;
  13727. };
  13728. // Facet data
  13729. /**
  13730. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13731. * Returns the AbstractMesh.
  13732. */
  13733. AbstractMesh.prototype._initFacetData = function () {
  13734. if (!this._facetNormals) {
  13735. this._facetNormals = new Array();
  13736. }
  13737. if (!this._facetPositions) {
  13738. this._facetPositions = new Array();
  13739. }
  13740. if (!this._facetPartitioning) {
  13741. this._facetPartitioning = new Array();
  13742. }
  13743. this._facetNb = this.getIndices().length / 3;
  13744. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13745. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13746. for (var f = 0; f < this._facetNb; f++) {
  13747. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13748. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13749. }
  13750. this._facetDataEnabled = true;
  13751. return this;
  13752. };
  13753. /**
  13754. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13755. * This method can be called within the render loop.
  13756. * 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.
  13757. * Returns the AbstractMesh.
  13758. */
  13759. AbstractMesh.prototype.updateFacetData = function () {
  13760. if (!this._facetDataEnabled) {
  13761. this._initFacetData();
  13762. }
  13763. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13764. var indices = this.getIndices();
  13765. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13766. var bInfo = this.getBoundingInfo();
  13767. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13768. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13769. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13770. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13771. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13772. this._subDiv.max = this._partitioningSubdivisions;
  13773. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13774. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13775. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13776. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13777. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13778. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13779. // set the parameters for ComputeNormals()
  13780. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13781. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13782. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13783. this._facetParameters.bInfo = bInfo;
  13784. this._facetParameters.bbSize = this._bbSize;
  13785. this._facetParameters.subDiv = this._subDiv;
  13786. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13787. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13788. return this;
  13789. };
  13790. /**
  13791. * Returns the facetLocalNormals array.
  13792. * The normals are expressed in the mesh local space.
  13793. */
  13794. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13795. if (!this._facetNormals) {
  13796. this.updateFacetData();
  13797. }
  13798. return this._facetNormals;
  13799. };
  13800. /**
  13801. * Returns the facetLocalPositions array.
  13802. * The facet positions are expressed in the mesh local space.
  13803. */
  13804. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13805. if (!this._facetPositions) {
  13806. this.updateFacetData();
  13807. }
  13808. return this._facetPositions;
  13809. };
  13810. /**
  13811. * Returns the facetLocalPartioning array.
  13812. */
  13813. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13814. if (!this._facetPartitioning) {
  13815. this.updateFacetData();
  13816. }
  13817. return this._facetPartitioning;
  13818. };
  13819. /**
  13820. * Returns the i-th facet position in the world system.
  13821. * This method allocates a new Vector3 per call.
  13822. */
  13823. AbstractMesh.prototype.getFacetPosition = function (i) {
  13824. var pos = BABYLON.Vector3.Zero();
  13825. this.getFacetPositionToRef(i, pos);
  13826. return pos;
  13827. };
  13828. /**
  13829. * Sets the reference Vector3 with the i-th facet position in the world system.
  13830. * Returns the AbstractMesh.
  13831. */
  13832. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13833. var localPos = (this.getFacetLocalPositions())[i];
  13834. var world = this.getWorldMatrix();
  13835. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13836. return this;
  13837. };
  13838. /**
  13839. * Returns the i-th facet normal in the world system.
  13840. * This method allocates a new Vector3 per call.
  13841. */
  13842. AbstractMesh.prototype.getFacetNormal = function (i) {
  13843. var norm = BABYLON.Vector3.Zero();
  13844. this.getFacetNormalToRef(i, norm);
  13845. return norm;
  13846. };
  13847. /**
  13848. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13849. * Returns the AbstractMesh.
  13850. */
  13851. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13852. var localNorm = (this.getFacetLocalNormals())[i];
  13853. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13854. return this;
  13855. };
  13856. /**
  13857. * 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).
  13858. */
  13859. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13860. var bInfo = this.getBoundingInfo();
  13861. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13862. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13863. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13864. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13865. return null;
  13866. }
  13867. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13868. };
  13869. /**
  13870. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13871. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13872. * 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.
  13873. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13874. * 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.
  13875. */
  13876. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13877. if (checkFace === void 0) { checkFace = false; }
  13878. if (facing === void 0) { facing = true; }
  13879. var world = this.getWorldMatrix();
  13880. var invMat = BABYLON.Tmp.Matrix[5];
  13881. world.invertToRef(invMat);
  13882. var invVect = BABYLON.Tmp.Vector3[8];
  13883. var closest = null;
  13884. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13885. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13886. if (projected) {
  13887. // tranform the local computed projected vector to world coordinates
  13888. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13889. }
  13890. return closest;
  13891. };
  13892. /**
  13893. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13894. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13895. * 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.
  13896. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13897. * 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.
  13898. */
  13899. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13900. if (checkFace === void 0) { checkFace = false; }
  13901. if (facing === void 0) { facing = true; }
  13902. var closest = null;
  13903. var tmpx = 0.0;
  13904. var tmpy = 0.0;
  13905. var tmpz = 0.0;
  13906. var d = 0.0; // tmp dot facet normal * facet position
  13907. var t0 = 0.0;
  13908. var projx = 0.0;
  13909. var projy = 0.0;
  13910. var projz = 0.0;
  13911. // Get all the facets in the same partitioning block than (x, y, z)
  13912. var facetPositions = this.getFacetLocalPositions();
  13913. var facetNormals = this.getFacetLocalNormals();
  13914. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13915. if (!facetsInBlock) {
  13916. return null;
  13917. }
  13918. // Get the closest facet to (x, y, z)
  13919. var shortest = Number.MAX_VALUE; // init distance vars
  13920. var tmpDistance = shortest;
  13921. var fib; // current facet in the block
  13922. var norm; // current facet normal
  13923. var p0; // current facet barycenter position
  13924. // loop on all the facets in the current partitioning block
  13925. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13926. fib = facetsInBlock[idx];
  13927. norm = facetNormals[fib];
  13928. p0 = facetPositions[fib];
  13929. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13930. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13931. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13932. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13933. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13934. projx = x + norm.x * t0;
  13935. projy = y + norm.y * t0;
  13936. projz = z + norm.z * t0;
  13937. tmpx = projx - x;
  13938. tmpy = projy - y;
  13939. tmpz = projz - z;
  13940. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13941. if (tmpDistance < shortest) {
  13942. shortest = tmpDistance;
  13943. closest = fib;
  13944. if (projected) {
  13945. projected.x = projx;
  13946. projected.y = projy;
  13947. projected.z = projz;
  13948. }
  13949. }
  13950. }
  13951. }
  13952. return closest;
  13953. };
  13954. /**
  13955. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13956. */
  13957. AbstractMesh.prototype.getFacetDataParameters = function () {
  13958. return this._facetParameters;
  13959. };
  13960. /**
  13961. * Disables the feature FacetData and frees the related memory.
  13962. * Returns the AbstractMesh.
  13963. */
  13964. AbstractMesh.prototype.disableFacetData = function () {
  13965. if (this._facetDataEnabled) {
  13966. this._facetDataEnabled = false;
  13967. this._facetPositions = null;
  13968. this._facetNormals = null;
  13969. this._facetPartitioning = null;
  13970. this._facetParameters = null;
  13971. }
  13972. return this;
  13973. };
  13974. /**
  13975. * Creates new normals data for the mesh.
  13976. * @param updatable.
  13977. */
  13978. AbstractMesh.prototype.createNormals = function (updatable) {
  13979. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13980. var indices = this.getIndices();
  13981. var normals;
  13982. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13983. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13984. }
  13985. else {
  13986. normals = [];
  13987. }
  13988. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13989. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13990. };
  13991. AbstractMesh.prototype.checkOcclusionQuery = function () {
  13992. var engine = this.getEngine();
  13993. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  13994. this._isOccluded = false;
  13995. return;
  13996. }
  13997. if (this.isOcclusionQueryInProgress) {
  13998. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  13999. if (isOcclusionQueryAvailable) {
  14000. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14001. this._isOcclusionQueryInProgress = false;
  14002. this._occlusionInternalRetryCounter = 0;
  14003. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14004. }
  14005. else {
  14006. this._occlusionInternalRetryCounter++;
  14007. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14008. this._isOcclusionQueryInProgress = false;
  14009. this._occlusionInternalRetryCounter = 0;
  14010. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14011. // if strict continue the last state of the object.
  14012. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14013. }
  14014. else {
  14015. return;
  14016. }
  14017. }
  14018. }
  14019. var scene = this.getScene();
  14020. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14021. if (!this._occlusionQuery) {
  14022. this._occlusionQuery = engine.createQuery();
  14023. }
  14024. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14025. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14026. engine.endQuery(this.occlusionQueryAlgorithmType);
  14027. this._isOcclusionQueryInProgress = true;
  14028. };
  14029. // Statics
  14030. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14031. AbstractMesh._BILLBOARDMODE_X = 1;
  14032. AbstractMesh._BILLBOARDMODE_Y = 2;
  14033. AbstractMesh._BILLBOARDMODE_Z = 4;
  14034. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14035. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14036. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14037. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14038. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14039. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14040. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14041. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14042. return AbstractMesh;
  14043. }(BABYLON.Node));
  14044. BABYLON.AbstractMesh = AbstractMesh;
  14045. })(BABYLON || (BABYLON = {}));
  14046. //# sourceMappingURL=babylon.abstractMesh.js.map
  14047. var BABYLON;
  14048. (function (BABYLON) {
  14049. var Light = (function (_super) {
  14050. __extends(Light, _super);
  14051. /**
  14052. * Creates a Light object in the scene.
  14053. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14054. */
  14055. function Light(name, scene) {
  14056. var _this = _super.call(this, name, scene) || this;
  14057. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14058. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14059. _this.intensity = 1.0;
  14060. _this.range = Number.MAX_VALUE;
  14061. /**
  14062. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14063. * of light.
  14064. */
  14065. _this._photometricScale = 1.0;
  14066. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14067. _this._radius = 0.00001;
  14068. _this.renderPriority = 0;
  14069. /**
  14070. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14071. * the current shadow generator.
  14072. */
  14073. _this.shadowEnabled = true;
  14074. _this._excludeWithLayerMask = 0;
  14075. _this._includeOnlyWithLayerMask = 0;
  14076. _this._lightmapMode = 0;
  14077. _this._excludedMeshesIds = new Array();
  14078. _this._includedOnlyMeshesIds = new Array();
  14079. _this.getScene().addLight(_this);
  14080. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14081. _this._buildUniformLayout();
  14082. _this.includedOnlyMeshes = new Array();
  14083. _this.excludedMeshes = new Array();
  14084. _this._resyncMeshes();
  14085. return _this;
  14086. }
  14087. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14088. /**
  14089. * If every light affecting the material is in this lightmapMode,
  14090. * material.lightmapTexture adds or multiplies
  14091. * (depends on material.useLightmapAsShadowmap)
  14092. * after every other light calculations.
  14093. */
  14094. get: function () {
  14095. return Light._LIGHTMAP_DEFAULT;
  14096. },
  14097. enumerable: true,
  14098. configurable: true
  14099. });
  14100. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14101. /**
  14102. * material.lightmapTexture as only diffuse lighting from this light
  14103. * adds pnly specular lighting from this light
  14104. * adds dynamic shadows
  14105. */
  14106. get: function () {
  14107. return Light._LIGHTMAP_SPECULAR;
  14108. },
  14109. enumerable: true,
  14110. configurable: true
  14111. });
  14112. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14113. /**
  14114. * material.lightmapTexture as only lighting
  14115. * no light calculation from this light
  14116. * only adds dynamic shadows from this light
  14117. */
  14118. get: function () {
  14119. return Light._LIGHTMAP_SHADOWSONLY;
  14120. },
  14121. enumerable: true,
  14122. configurable: true
  14123. });
  14124. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14125. /**
  14126. * Each light type uses the default quantity according to its type:
  14127. * point/spot lights use luminous intensity
  14128. * directional lights use illuminance
  14129. */
  14130. get: function () {
  14131. return Light._INTENSITYMODE_AUTOMATIC;
  14132. },
  14133. enumerable: true,
  14134. configurable: true
  14135. });
  14136. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14137. /**
  14138. * lumen (lm)
  14139. */
  14140. get: function () {
  14141. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14142. },
  14143. enumerable: true,
  14144. configurable: true
  14145. });
  14146. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14147. /**
  14148. * candela (lm/sr)
  14149. */
  14150. get: function () {
  14151. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14152. },
  14153. enumerable: true,
  14154. configurable: true
  14155. });
  14156. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14157. /**
  14158. * lux (lm/m^2)
  14159. */
  14160. get: function () {
  14161. return Light._INTENSITYMODE_ILLUMINANCE;
  14162. },
  14163. enumerable: true,
  14164. configurable: true
  14165. });
  14166. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14167. /**
  14168. * nit (cd/m^2)
  14169. */
  14170. get: function () {
  14171. return Light._INTENSITYMODE_LUMINANCE;
  14172. },
  14173. enumerable: true,
  14174. configurable: true
  14175. });
  14176. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14177. /**
  14178. * Light type const id of the point light.
  14179. */
  14180. get: function () {
  14181. return Light._LIGHTTYPEID_POINTLIGHT;
  14182. },
  14183. enumerable: true,
  14184. configurable: true
  14185. });
  14186. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14187. /**
  14188. * Light type const id of the directional light.
  14189. */
  14190. get: function () {
  14191. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14192. },
  14193. enumerable: true,
  14194. configurable: true
  14195. });
  14196. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14197. /**
  14198. * Light type const id of the spot light.
  14199. */
  14200. get: function () {
  14201. return Light._LIGHTTYPEID_SPOTLIGHT;
  14202. },
  14203. enumerable: true,
  14204. configurable: true
  14205. });
  14206. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14207. /**
  14208. * Light type const id of the hemispheric light.
  14209. */
  14210. get: function () {
  14211. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14212. },
  14213. enumerable: true,
  14214. configurable: true
  14215. });
  14216. Object.defineProperty(Light.prototype, "intensityMode", {
  14217. /**
  14218. * Gets the photometric scale used to interpret the intensity.
  14219. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14220. */
  14221. get: function () {
  14222. return this._intensityMode;
  14223. },
  14224. /**
  14225. * Sets the photometric scale used to interpret the intensity.
  14226. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14227. */
  14228. set: function (value) {
  14229. this._intensityMode = value;
  14230. this._computePhotometricScale();
  14231. },
  14232. enumerable: true,
  14233. configurable: true
  14234. });
  14235. ;
  14236. ;
  14237. Object.defineProperty(Light.prototype, "radius", {
  14238. /**
  14239. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14240. */
  14241. get: function () {
  14242. return this._radius;
  14243. },
  14244. /**
  14245. * sets the light radius used by PBR Materials to simulate soft area lights.
  14246. */
  14247. set: function (value) {
  14248. this._radius = value;
  14249. this._computePhotometricScale();
  14250. },
  14251. enumerable: true,
  14252. configurable: true
  14253. });
  14254. ;
  14255. ;
  14256. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14257. get: function () {
  14258. return this._includedOnlyMeshes;
  14259. },
  14260. set: function (value) {
  14261. this._includedOnlyMeshes = value;
  14262. this._hookArrayForIncludedOnly(value);
  14263. },
  14264. enumerable: true,
  14265. configurable: true
  14266. });
  14267. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14268. get: function () {
  14269. return this._excludedMeshes;
  14270. },
  14271. set: function (value) {
  14272. this._excludedMeshes = value;
  14273. this._hookArrayForExcluded(value);
  14274. },
  14275. enumerable: true,
  14276. configurable: true
  14277. });
  14278. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14279. get: function () {
  14280. return this._excludeWithLayerMask;
  14281. },
  14282. set: function (value) {
  14283. this._excludeWithLayerMask = value;
  14284. this._resyncMeshes();
  14285. },
  14286. enumerable: true,
  14287. configurable: true
  14288. });
  14289. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14290. get: function () {
  14291. return this._includeOnlyWithLayerMask;
  14292. },
  14293. set: function (value) {
  14294. this._includeOnlyWithLayerMask = value;
  14295. this._resyncMeshes();
  14296. },
  14297. enumerable: true,
  14298. configurable: true
  14299. });
  14300. Object.defineProperty(Light.prototype, "lightmapMode", {
  14301. get: function () {
  14302. return this._lightmapMode;
  14303. },
  14304. set: function (value) {
  14305. if (this._lightmapMode === value) {
  14306. return;
  14307. }
  14308. this._lightmapMode = value;
  14309. this._markMeshesAsLightDirty();
  14310. },
  14311. enumerable: true,
  14312. configurable: true
  14313. });
  14314. Light.prototype._buildUniformLayout = function () {
  14315. // Overridden
  14316. };
  14317. /**
  14318. * Returns the string "Light".
  14319. */
  14320. Light.prototype.getClassName = function () {
  14321. return "Light";
  14322. };
  14323. /**
  14324. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14325. */
  14326. Light.prototype.toString = function (fullDetails) {
  14327. var ret = "Name: " + this.name;
  14328. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14329. if (this.animations) {
  14330. for (var i = 0; i < this.animations.length; i++) {
  14331. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14332. }
  14333. }
  14334. if (fullDetails) {
  14335. }
  14336. return ret;
  14337. };
  14338. /**
  14339. * Set the enabled state of this node.
  14340. * @param {boolean} value - the new enabled state
  14341. * @see isEnabled
  14342. */
  14343. Light.prototype.setEnabled = function (value) {
  14344. _super.prototype.setEnabled.call(this, value);
  14345. this._resyncMeshes();
  14346. };
  14347. /**
  14348. * Returns the Light associated shadow generator.
  14349. */
  14350. Light.prototype.getShadowGenerator = function () {
  14351. return this._shadowGenerator;
  14352. };
  14353. /**
  14354. * Returns a Vector3, the absolute light position in the World.
  14355. */
  14356. Light.prototype.getAbsolutePosition = function () {
  14357. return BABYLON.Vector3.Zero();
  14358. };
  14359. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14360. };
  14361. Light.prototype._getWorldMatrix = function () {
  14362. return BABYLON.Matrix.Identity();
  14363. };
  14364. /**
  14365. * Boolean : True if the light will affect the passed mesh.
  14366. */
  14367. Light.prototype.canAffectMesh = function (mesh) {
  14368. if (!mesh) {
  14369. return true;
  14370. }
  14371. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14372. return false;
  14373. }
  14374. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14375. return false;
  14376. }
  14377. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14378. return false;
  14379. }
  14380. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14381. return false;
  14382. }
  14383. return true;
  14384. };
  14385. /**
  14386. * Returns the light World matrix.
  14387. */
  14388. Light.prototype.getWorldMatrix = function () {
  14389. this._currentRenderId = this.getScene().getRenderId();
  14390. var worldMatrix = this._getWorldMatrix();
  14391. if (this.parent && this.parent.getWorldMatrix) {
  14392. if (!this._parentedWorldMatrix) {
  14393. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14394. }
  14395. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14396. this._markSyncedWithParent();
  14397. return this._parentedWorldMatrix;
  14398. }
  14399. return worldMatrix;
  14400. };
  14401. /**
  14402. * Sort function to order lights for rendering.
  14403. * @param a First Light object to compare to second.
  14404. * @param b Second Light object to compare first.
  14405. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14406. */
  14407. Light.compareLightsPriority = function (a, b) {
  14408. //shadow-casting lights have priority over non-shadow-casting lights
  14409. //the renderPrioirty is a secondary sort criterion
  14410. if (a.shadowEnabled !== b.shadowEnabled) {
  14411. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14412. }
  14413. return b.renderPriority - a.renderPriority;
  14414. };
  14415. /**
  14416. * Disposes the light.
  14417. */
  14418. Light.prototype.dispose = function () {
  14419. if (this._shadowGenerator) {
  14420. this._shadowGenerator.dispose();
  14421. this._shadowGenerator = null;
  14422. }
  14423. // Animations
  14424. this.getScene().stopAnimation(this);
  14425. // Remove from meshes
  14426. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14427. var mesh = _a[_i];
  14428. mesh._removeLightSource(this);
  14429. }
  14430. this._uniformBuffer.dispose();
  14431. // Remove from scene
  14432. this.getScene().removeLight(this);
  14433. _super.prototype.dispose.call(this);
  14434. };
  14435. /**
  14436. * Returns the light type ID (integer).
  14437. */
  14438. Light.prototype.getTypeID = function () {
  14439. return 0;
  14440. };
  14441. /**
  14442. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14443. */
  14444. Light.prototype.getScaledIntensity = function () {
  14445. return this._photometricScale * this.intensity;
  14446. };
  14447. /**
  14448. * Returns a new Light object, named "name", from the current one.
  14449. */
  14450. Light.prototype.clone = function (name) {
  14451. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14452. };
  14453. /**
  14454. * Serializes the current light into a Serialization object.
  14455. * Returns the serialized object.
  14456. */
  14457. Light.prototype.serialize = function () {
  14458. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14459. // Type
  14460. serializationObject.type = this.getTypeID();
  14461. // Parent
  14462. if (this.parent) {
  14463. serializationObject.parentId = this.parent.id;
  14464. }
  14465. // Inclusion / exclusions
  14466. if (this.excludedMeshes.length > 0) {
  14467. serializationObject.excludedMeshesIds = [];
  14468. this.excludedMeshes.forEach(function (mesh) {
  14469. serializationObject.excludedMeshesIds.push(mesh.id);
  14470. });
  14471. }
  14472. if (this.includedOnlyMeshes.length > 0) {
  14473. serializationObject.includedOnlyMeshesIds = [];
  14474. this.includedOnlyMeshes.forEach(function (mesh) {
  14475. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14476. });
  14477. }
  14478. // Animations
  14479. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14480. serializationObject.ranges = this.serializeAnimationRanges();
  14481. return serializationObject;
  14482. };
  14483. /**
  14484. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14485. * This new light is named "name" and added to the passed scene.
  14486. */
  14487. Light.GetConstructorFromName = function (type, name, scene) {
  14488. switch (type) {
  14489. case 0:
  14490. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14491. case 1:
  14492. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14493. case 2:
  14494. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14495. case 3:
  14496. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14497. }
  14498. };
  14499. /**
  14500. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14501. */
  14502. Light.Parse = function (parsedLight, scene) {
  14503. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14504. // Inclusion / exclusions
  14505. if (parsedLight.excludedMeshesIds) {
  14506. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14507. }
  14508. if (parsedLight.includedOnlyMeshesIds) {
  14509. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14510. }
  14511. // Parent
  14512. if (parsedLight.parentId) {
  14513. light._waitingParentId = parsedLight.parentId;
  14514. }
  14515. // Animations
  14516. if (parsedLight.animations) {
  14517. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14518. var parsedAnimation = parsedLight.animations[animationIndex];
  14519. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14520. }
  14521. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14522. }
  14523. if (parsedLight.autoAnimate) {
  14524. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14525. }
  14526. return light;
  14527. };
  14528. Light.prototype._hookArrayForExcluded = function (array) {
  14529. var _this = this;
  14530. var oldPush = array.push;
  14531. array.push = function () {
  14532. var items = [];
  14533. for (var _i = 0; _i < arguments.length; _i++) {
  14534. items[_i] = arguments[_i];
  14535. }
  14536. var result = oldPush.apply(array, items);
  14537. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14538. var item = items_1[_a];
  14539. item._resyncLighSource(_this);
  14540. }
  14541. return result;
  14542. };
  14543. var oldSplice = array.splice;
  14544. array.splice = function (index, deleteCount) {
  14545. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14546. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14547. var item = deleted_1[_i];
  14548. item._resyncLighSource(_this);
  14549. }
  14550. return deleted;
  14551. };
  14552. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14553. var item = array_1[_i];
  14554. item._resyncLighSource(this);
  14555. }
  14556. };
  14557. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14558. var _this = this;
  14559. var oldPush = array.push;
  14560. array.push = function () {
  14561. var items = [];
  14562. for (var _i = 0; _i < arguments.length; _i++) {
  14563. items[_i] = arguments[_i];
  14564. }
  14565. var result = oldPush.apply(array, items);
  14566. _this._resyncMeshes();
  14567. return result;
  14568. };
  14569. var oldSplice = array.splice;
  14570. array.splice = function (index, deleteCount) {
  14571. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14572. _this._resyncMeshes();
  14573. return deleted;
  14574. };
  14575. this._resyncMeshes();
  14576. };
  14577. Light.prototype._resyncMeshes = function () {
  14578. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14579. var mesh = _a[_i];
  14580. mesh._resyncLighSource(this);
  14581. }
  14582. };
  14583. Light.prototype._markMeshesAsLightDirty = function () {
  14584. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14585. var mesh = _a[_i];
  14586. if (mesh._lightSources.indexOf(this) !== -1) {
  14587. mesh._markSubMeshesAsLightDirty();
  14588. }
  14589. }
  14590. };
  14591. /**
  14592. * Recomputes the cached photometric scale if needed.
  14593. */
  14594. Light.prototype._computePhotometricScale = function () {
  14595. this._photometricScale = this._getPhotometricScale();
  14596. this.getScene().resetCachedMaterial();
  14597. };
  14598. /**
  14599. * Returns the Photometric Scale according to the light type and intensity mode.
  14600. */
  14601. Light.prototype._getPhotometricScale = function () {
  14602. var photometricScale = 0.0;
  14603. var lightTypeID = this.getTypeID();
  14604. //get photometric mode
  14605. var photometricMode = this.intensityMode;
  14606. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14607. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14608. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14609. }
  14610. else {
  14611. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14612. }
  14613. }
  14614. //compute photometric scale
  14615. switch (lightTypeID) {
  14616. case Light.LIGHTTYPEID_POINTLIGHT:
  14617. case Light.LIGHTTYPEID_SPOTLIGHT:
  14618. switch (photometricMode) {
  14619. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14620. photometricScale = 1.0 / (4.0 * Math.PI);
  14621. break;
  14622. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14623. photometricScale = 1.0;
  14624. break;
  14625. case Light.INTENSITYMODE_LUMINANCE:
  14626. photometricScale = this.radius * this.radius;
  14627. break;
  14628. }
  14629. break;
  14630. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14631. switch (photometricMode) {
  14632. case Light.INTENSITYMODE_ILLUMINANCE:
  14633. photometricScale = 1.0;
  14634. break;
  14635. case Light.INTENSITYMODE_LUMINANCE:
  14636. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14637. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14638. var apexAngleRadians = this.radius;
  14639. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14640. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14641. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14642. photometricScale = solidAngle;
  14643. break;
  14644. }
  14645. break;
  14646. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14647. // No fall off in hemisperic light.
  14648. photometricScale = 1.0;
  14649. break;
  14650. }
  14651. return photometricScale;
  14652. };
  14653. Light.prototype._reorderLightsInScene = function () {
  14654. var scene = this.getScene();
  14655. if (this.renderPriority != 0) {
  14656. scene.requireLightSorting = true;
  14657. }
  14658. this.getScene().sortLightsByPriority();
  14659. };
  14660. //lightmapMode Consts
  14661. Light._LIGHTMAP_DEFAULT = 0;
  14662. Light._LIGHTMAP_SPECULAR = 1;
  14663. Light._LIGHTMAP_SHADOWSONLY = 2;
  14664. // Intensity Mode Consts
  14665. Light._INTENSITYMODE_AUTOMATIC = 0;
  14666. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14667. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14668. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14669. Light._INTENSITYMODE_LUMINANCE = 4;
  14670. // Light types ids const.
  14671. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14672. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14673. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14674. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14675. __decorate([
  14676. BABYLON.serializeAsColor3()
  14677. ], Light.prototype, "diffuse", void 0);
  14678. __decorate([
  14679. BABYLON.serializeAsColor3()
  14680. ], Light.prototype, "specular", void 0);
  14681. __decorate([
  14682. BABYLON.serialize()
  14683. ], Light.prototype, "intensity", void 0);
  14684. __decorate([
  14685. BABYLON.serialize()
  14686. ], Light.prototype, "range", void 0);
  14687. __decorate([
  14688. BABYLON.serialize()
  14689. ], Light.prototype, "intensityMode", null);
  14690. __decorate([
  14691. BABYLON.serialize()
  14692. ], Light.prototype, "radius", null);
  14693. __decorate([
  14694. BABYLON.serialize()
  14695. ], Light.prototype, "_renderPriority", void 0);
  14696. __decorate([
  14697. BABYLON.expandToProperty("_reorderLightsInScene")
  14698. ], Light.prototype, "renderPriority", void 0);
  14699. __decorate([
  14700. BABYLON.serialize()
  14701. ], Light.prototype, "shadowEnabled", void 0);
  14702. __decorate([
  14703. BABYLON.serialize("excludeWithLayerMask")
  14704. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14705. __decorate([
  14706. BABYLON.serialize("includeOnlyWithLayerMask")
  14707. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14708. __decorate([
  14709. BABYLON.serialize("lightmapMode")
  14710. ], Light.prototype, "_lightmapMode", void 0);
  14711. return Light;
  14712. }(BABYLON.Node));
  14713. BABYLON.Light = Light;
  14714. })(BABYLON || (BABYLON = {}));
  14715. //# sourceMappingURL=babylon.light.js.map
  14716. var BABYLON;
  14717. (function (BABYLON) {
  14718. var Camera = (function (_super) {
  14719. __extends(Camera, _super);
  14720. function Camera(name, position, scene) {
  14721. var _this = _super.call(this, name, scene) || this;
  14722. _this.upVector = BABYLON.Vector3.Up();
  14723. _this.orthoLeft = null;
  14724. _this.orthoRight = null;
  14725. _this.orthoBottom = null;
  14726. _this.orthoTop = null;
  14727. _this.fov = 0.8;
  14728. _this.minZ = 1;
  14729. _this.maxZ = 10000.0;
  14730. _this.inertia = 0.9;
  14731. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14732. _this.isIntermediate = false;
  14733. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14734. _this.layerMask = 0x0FFFFFFF;
  14735. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14736. // Camera rig members
  14737. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14738. _this._rigCameras = new Array();
  14739. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14740. _this.customRenderTargets = new Array();
  14741. // Observables
  14742. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14743. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14744. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  14745. // Cache
  14746. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14747. _this._projectionMatrix = new BABYLON.Matrix();
  14748. _this._doNotComputeProjectionMatrix = false;
  14749. _this._postProcesses = new Array();
  14750. _this._transformMatrix = BABYLON.Matrix.Zero();
  14751. _this._activeMeshes = new BABYLON.SmartArray(256);
  14752. _this._globalPosition = BABYLON.Vector3.Zero();
  14753. _this._refreshFrustumPlanes = true;
  14754. _this.getScene().addCamera(_this);
  14755. if (!_this.getScene().activeCamera) {
  14756. _this.getScene().activeCamera = _this;
  14757. }
  14758. _this.position = position;
  14759. return _this;
  14760. }
  14761. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14762. get: function () {
  14763. return Camera._PERSPECTIVE_CAMERA;
  14764. },
  14765. enumerable: true,
  14766. configurable: true
  14767. });
  14768. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14769. get: function () {
  14770. return Camera._ORTHOGRAPHIC_CAMERA;
  14771. },
  14772. enumerable: true,
  14773. configurable: true
  14774. });
  14775. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14776. get: function () {
  14777. return Camera._FOVMODE_VERTICAL_FIXED;
  14778. },
  14779. enumerable: true,
  14780. configurable: true
  14781. });
  14782. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14783. get: function () {
  14784. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14785. },
  14786. enumerable: true,
  14787. configurable: true
  14788. });
  14789. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14790. get: function () {
  14791. return Camera._RIG_MODE_NONE;
  14792. },
  14793. enumerable: true,
  14794. configurable: true
  14795. });
  14796. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14797. get: function () {
  14798. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14799. },
  14800. enumerable: true,
  14801. configurable: true
  14802. });
  14803. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14804. get: function () {
  14805. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14806. },
  14807. enumerable: true,
  14808. configurable: true
  14809. });
  14810. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14811. get: function () {
  14812. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14813. },
  14814. enumerable: true,
  14815. configurable: true
  14816. });
  14817. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14818. get: function () {
  14819. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14820. },
  14821. enumerable: true,
  14822. configurable: true
  14823. });
  14824. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14825. get: function () {
  14826. return Camera._RIG_MODE_VR;
  14827. },
  14828. enumerable: true,
  14829. configurable: true
  14830. });
  14831. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14832. get: function () {
  14833. return Camera._RIG_MODE_WEBVR;
  14834. },
  14835. enumerable: true,
  14836. configurable: true
  14837. });
  14838. Camera.prototype.getClassName = function () {
  14839. return "Camera";
  14840. };
  14841. /**
  14842. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14843. */
  14844. Camera.prototype.toString = function (fullDetails) {
  14845. var ret = "Name: " + this.name;
  14846. ret += ", type: " + this.getClassName();
  14847. if (this.animations) {
  14848. for (var i = 0; i < this.animations.length; i++) {
  14849. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14850. }
  14851. }
  14852. if (fullDetails) {
  14853. }
  14854. return ret;
  14855. };
  14856. Object.defineProperty(Camera.prototype, "globalPosition", {
  14857. get: function () {
  14858. return this._globalPosition;
  14859. },
  14860. enumerable: true,
  14861. configurable: true
  14862. });
  14863. Camera.prototype.getActiveMeshes = function () {
  14864. return this._activeMeshes;
  14865. };
  14866. Camera.prototype.isActiveMesh = function (mesh) {
  14867. return (this._activeMeshes.indexOf(mesh) !== -1);
  14868. };
  14869. //Cache
  14870. Camera.prototype._initCache = function () {
  14871. _super.prototype._initCache.call(this);
  14872. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14873. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14874. this._cache.mode = undefined;
  14875. this._cache.minZ = undefined;
  14876. this._cache.maxZ = undefined;
  14877. this._cache.fov = undefined;
  14878. this._cache.fovMode = undefined;
  14879. this._cache.aspectRatio = undefined;
  14880. this._cache.orthoLeft = undefined;
  14881. this._cache.orthoRight = undefined;
  14882. this._cache.orthoBottom = undefined;
  14883. this._cache.orthoTop = undefined;
  14884. this._cache.renderWidth = undefined;
  14885. this._cache.renderHeight = undefined;
  14886. };
  14887. Camera.prototype._updateCache = function (ignoreParentClass) {
  14888. if (!ignoreParentClass) {
  14889. _super.prototype._updateCache.call(this);
  14890. }
  14891. var engine = this.getEngine();
  14892. this._cache.position.copyFrom(this.position);
  14893. this._cache.upVector.copyFrom(this.upVector);
  14894. this._cache.mode = this.mode;
  14895. this._cache.minZ = this.minZ;
  14896. this._cache.maxZ = this.maxZ;
  14897. this._cache.fov = this.fov;
  14898. this._cache.fovMode = this.fovMode;
  14899. this._cache.aspectRatio = engine.getAspectRatio(this);
  14900. this._cache.orthoLeft = this.orthoLeft;
  14901. this._cache.orthoRight = this.orthoRight;
  14902. this._cache.orthoBottom = this.orthoBottom;
  14903. this._cache.orthoTop = this.orthoTop;
  14904. this._cache.renderWidth = engine.getRenderWidth();
  14905. this._cache.renderHeight = engine.getRenderHeight();
  14906. };
  14907. Camera.prototype._updateFromScene = function () {
  14908. this.updateCache();
  14909. this.update();
  14910. };
  14911. // Synchronized
  14912. Camera.prototype._isSynchronized = function () {
  14913. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14914. };
  14915. Camera.prototype._isSynchronizedViewMatrix = function () {
  14916. if (!_super.prototype._isSynchronized.call(this))
  14917. return false;
  14918. return this._cache.position.equals(this.position)
  14919. && this._cache.upVector.equals(this.upVector)
  14920. && this.isSynchronizedWithParent();
  14921. };
  14922. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14923. var check = this._cache.mode === this.mode
  14924. && this._cache.minZ === this.minZ
  14925. && this._cache.maxZ === this.maxZ;
  14926. if (!check) {
  14927. return false;
  14928. }
  14929. var engine = this.getEngine();
  14930. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14931. check = this._cache.fov === this.fov
  14932. && this._cache.fovMode === this.fovMode
  14933. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14934. }
  14935. else {
  14936. check = this._cache.orthoLeft === this.orthoLeft
  14937. && this._cache.orthoRight === this.orthoRight
  14938. && this._cache.orthoBottom === this.orthoBottom
  14939. && this._cache.orthoTop === this.orthoTop
  14940. && this._cache.renderWidth === engine.getRenderWidth()
  14941. && this._cache.renderHeight === engine.getRenderHeight();
  14942. }
  14943. return check;
  14944. };
  14945. // Controls
  14946. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14947. };
  14948. Camera.prototype.detachControl = function (element) {
  14949. };
  14950. Camera.prototype.update = function () {
  14951. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14952. this._updateRigCameras();
  14953. }
  14954. this._checkInputs();
  14955. };
  14956. Camera.prototype._checkInputs = function () {
  14957. this.onAfterCheckInputsObservable.notifyObservers(this);
  14958. };
  14959. Object.defineProperty(Camera.prototype, "rigCameras", {
  14960. get: function () {
  14961. return this._rigCameras;
  14962. },
  14963. enumerable: true,
  14964. configurable: true
  14965. });
  14966. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14967. get: function () {
  14968. return this._rigPostProcess;
  14969. },
  14970. enumerable: true,
  14971. configurable: true
  14972. });
  14973. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14974. // invalidate framebuffer
  14975. if (this._postProcesses.length > 0) {
  14976. this._postProcesses[0].markTextureDirty();
  14977. }
  14978. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14979. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14980. var cam = this._rigCameras[i];
  14981. var rigPostProcess = cam._rigPostProcess;
  14982. // for VR rig, there does not have to be a post process
  14983. if (rigPostProcess) {
  14984. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14985. if (isPass) {
  14986. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14987. cam.isIntermediate = this._postProcesses.length === 0;
  14988. }
  14989. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14990. rigPostProcess.markTextureDirty();
  14991. }
  14992. else {
  14993. cam._postProcesses = this._postProcesses.slice(0);
  14994. }
  14995. }
  14996. };
  14997. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14998. if (insertAt === void 0) { insertAt = null; }
  14999. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15000. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15001. return 0;
  15002. }
  15003. if (insertAt == null || insertAt < 0) {
  15004. this._postProcesses.push(postProcess);
  15005. }
  15006. else {
  15007. this._postProcesses.splice(insertAt, 0, postProcess);
  15008. }
  15009. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15010. return this._postProcesses.indexOf(postProcess);
  15011. };
  15012. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15013. if (atIndices === void 0) { atIndices = null; }
  15014. var result = [];
  15015. var i;
  15016. var index;
  15017. if (!atIndices) {
  15018. var idx = this._postProcesses.indexOf(postProcess);
  15019. if (idx !== -1) {
  15020. this._postProcesses.splice(idx, 1);
  15021. }
  15022. }
  15023. else {
  15024. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15025. // iterate descending, so can just splice as we go
  15026. for (i = atIndices.length - 1; i >= 0; i--) {
  15027. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15028. result.push(i);
  15029. continue;
  15030. }
  15031. index = atIndices[i];
  15032. this._postProcesses.splice(index, 1);
  15033. }
  15034. }
  15035. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15036. return result;
  15037. };
  15038. Camera.prototype.getWorldMatrix = function () {
  15039. if (!this._worldMatrix) {
  15040. this._worldMatrix = BABYLON.Matrix.Identity();
  15041. }
  15042. var viewMatrix = this.getViewMatrix();
  15043. viewMatrix.invertToRef(this._worldMatrix);
  15044. return this._worldMatrix;
  15045. };
  15046. Camera.prototype._getViewMatrix = function () {
  15047. return BABYLON.Matrix.Identity();
  15048. };
  15049. Camera.prototype.getViewMatrix = function (force) {
  15050. if (!force && this._isSynchronizedViewMatrix()) {
  15051. return this._computedViewMatrix;
  15052. }
  15053. this._computedViewMatrix = this._getViewMatrix();
  15054. this._currentRenderId = this.getScene().getRenderId();
  15055. this._refreshFrustumPlanes = true;
  15056. if (!this.parent || !this.parent.getWorldMatrix) {
  15057. this._globalPosition.copyFrom(this.position);
  15058. }
  15059. else {
  15060. if (!this._worldMatrix) {
  15061. this._worldMatrix = BABYLON.Matrix.Identity();
  15062. }
  15063. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15064. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15065. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15066. this._computedViewMatrix.invert();
  15067. this._markSyncedWithParent();
  15068. }
  15069. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15070. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15071. }
  15072. this.onViewMatrixChangedObservable.notifyObservers(this);
  15073. return this._computedViewMatrix;
  15074. };
  15075. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15076. this._doNotComputeProjectionMatrix = true;
  15077. if (projection !== undefined) {
  15078. this._projectionMatrix = projection;
  15079. }
  15080. };
  15081. ;
  15082. Camera.prototype.unfreezeProjectionMatrix = function () {
  15083. this._doNotComputeProjectionMatrix = false;
  15084. };
  15085. ;
  15086. Camera.prototype.getProjectionMatrix = function (force) {
  15087. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15088. return this._projectionMatrix;
  15089. }
  15090. this._refreshFrustumPlanes = true;
  15091. var engine = this.getEngine();
  15092. var scene = this.getScene();
  15093. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15094. if (this.minZ <= 0) {
  15095. this.minZ = 0.1;
  15096. }
  15097. if (scene.useRightHandedSystem) {
  15098. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15099. }
  15100. else {
  15101. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15102. }
  15103. }
  15104. else {
  15105. var halfWidth = engine.getRenderWidth() / 2.0;
  15106. var halfHeight = engine.getRenderHeight() / 2.0;
  15107. if (scene.useRightHandedSystem) {
  15108. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15109. }
  15110. else {
  15111. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15112. }
  15113. }
  15114. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15115. return this._projectionMatrix;
  15116. };
  15117. Camera.prototype.getTranformationMatrix = function () {
  15118. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15119. return this._transformMatrix;
  15120. };
  15121. Camera.prototype.updateFrustumPlanes = function () {
  15122. if (!this._refreshFrustumPlanes) {
  15123. return;
  15124. }
  15125. this.getTranformationMatrix();
  15126. if (!this._frustumPlanes) {
  15127. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15128. }
  15129. else {
  15130. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15131. }
  15132. this._refreshFrustumPlanes = false;
  15133. };
  15134. Camera.prototype.isInFrustum = function (target) {
  15135. this.updateFrustumPlanes();
  15136. return target.isInFrustum(this._frustumPlanes);
  15137. };
  15138. Camera.prototype.isCompletelyInFrustum = function (target) {
  15139. this.updateFrustumPlanes();
  15140. return target.isCompletelyInFrustum(this._frustumPlanes);
  15141. };
  15142. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15143. if (length === void 0) { length = 100; }
  15144. if (!transform) {
  15145. transform = this.getWorldMatrix();
  15146. }
  15147. if (!origin) {
  15148. origin = this.position;
  15149. }
  15150. var forward = new BABYLON.Vector3(0, 0, 1);
  15151. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15152. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15153. return new BABYLON.Ray(origin, direction, length);
  15154. };
  15155. Camera.prototype.dispose = function () {
  15156. // Observables
  15157. this.onViewMatrixChangedObservable.clear();
  15158. this.onProjectionMatrixChangedObservable.clear();
  15159. this.onAfterCheckInputsObservable.clear();
  15160. // Inputs
  15161. if (this.inputs) {
  15162. this.inputs.clear();
  15163. }
  15164. // Animations
  15165. this.getScene().stopAnimation(this);
  15166. // Remove from scene
  15167. this.getScene().removeCamera(this);
  15168. while (this._rigCameras.length > 0) {
  15169. this._rigCameras.pop().dispose();
  15170. }
  15171. // Postprocesses
  15172. var i = this._postProcesses.length;
  15173. while (--i >= 0) {
  15174. this._postProcesses[i].dispose(this);
  15175. }
  15176. // Render targets
  15177. var i = this.customRenderTargets.length;
  15178. while (--i >= 0) {
  15179. this.customRenderTargets[i].dispose();
  15180. }
  15181. this.customRenderTargets = [];
  15182. // Active Meshes
  15183. this._activeMeshes.dispose();
  15184. _super.prototype.dispose.call(this);
  15185. };
  15186. Object.defineProperty(Camera.prototype, "leftCamera", {
  15187. // ---- Camera rigs section ----
  15188. get: function () {
  15189. if (this._rigCameras.length < 1) {
  15190. return undefined;
  15191. }
  15192. return this._rigCameras[0];
  15193. },
  15194. enumerable: true,
  15195. configurable: true
  15196. });
  15197. Object.defineProperty(Camera.prototype, "rightCamera", {
  15198. get: function () {
  15199. if (this._rigCameras.length < 2) {
  15200. return undefined;
  15201. }
  15202. return this._rigCameras[1];
  15203. },
  15204. enumerable: true,
  15205. configurable: true
  15206. });
  15207. Camera.prototype.getLeftTarget = function () {
  15208. if (this._rigCameras.length < 1) {
  15209. return undefined;
  15210. }
  15211. return this._rigCameras[0].getTarget();
  15212. };
  15213. Camera.prototype.getRightTarget = function () {
  15214. if (this._rigCameras.length < 2) {
  15215. return undefined;
  15216. }
  15217. return this._rigCameras[1].getTarget();
  15218. };
  15219. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15220. while (this._rigCameras.length > 0) {
  15221. this._rigCameras.pop().dispose();
  15222. }
  15223. this.cameraRigMode = mode;
  15224. this._cameraRigParams = {};
  15225. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15226. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15227. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15228. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15229. // create the rig cameras, unless none
  15230. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15231. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15232. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15233. }
  15234. switch (this.cameraRigMode) {
  15235. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15236. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15237. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15238. break;
  15239. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15240. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15241. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15242. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15243. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15244. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15245. break;
  15246. case Camera.RIG_MODE_VR:
  15247. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15248. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15249. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15250. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15251. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15252. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15253. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15254. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15255. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15256. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15257. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15258. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15259. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15260. if (metrics.compensateDistortion) {
  15261. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15262. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15263. }
  15264. break;
  15265. case Camera.RIG_MODE_WEBVR:
  15266. if (rigParams.vrDisplay) {
  15267. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15268. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15269. //Left eye
  15270. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15271. this._rigCameras[0].setCameraRigParameter("left", true);
  15272. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15273. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15274. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15275. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15276. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15277. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15278. this._rigCameras[0].parent = this;
  15279. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15280. //Right eye
  15281. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15282. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15283. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15284. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15285. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15286. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15287. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15288. this._rigCameras[1].parent = this;
  15289. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15290. }
  15291. break;
  15292. }
  15293. this._cascadePostProcessesToRigCams();
  15294. this.
  15295. update();
  15296. };
  15297. Camera.prototype._getVRProjectionMatrix = function () {
  15298. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15299. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15300. return this._projectionMatrix;
  15301. };
  15302. Camera.prototype._updateCameraRotationMatrix = function () {
  15303. //Here for WebVR
  15304. };
  15305. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15306. //Here for WebVR
  15307. };
  15308. /**
  15309. * This function MUST be overwritten by the different WebVR cameras available.
  15310. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15311. */
  15312. Camera.prototype._getWebVRProjectionMatrix = function () {
  15313. return BABYLON.Matrix.Identity();
  15314. };
  15315. /**
  15316. * This function MUST be overwritten by the different WebVR cameras available.
  15317. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15318. */
  15319. Camera.prototype._getWebVRViewMatrix = function () {
  15320. return BABYLON.Matrix.Identity();
  15321. };
  15322. Camera.prototype.setCameraRigParameter = function (name, value) {
  15323. if (!this._cameraRigParams) {
  15324. this._cameraRigParams = {};
  15325. }
  15326. this._cameraRigParams[name] = value;
  15327. //provisionnally:
  15328. if (name === "interaxialDistance") {
  15329. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15330. }
  15331. };
  15332. /**
  15333. * needs to be overridden by children so sub has required properties to be copied
  15334. */
  15335. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15336. return null;
  15337. };
  15338. /**
  15339. * May need to be overridden by children
  15340. */
  15341. Camera.prototype._updateRigCameras = function () {
  15342. for (var i = 0; i < this._rigCameras.length; i++) {
  15343. this._rigCameras[i].minZ = this.minZ;
  15344. this._rigCameras[i].maxZ = this.maxZ;
  15345. this._rigCameras[i].fov = this.fov;
  15346. }
  15347. // only update viewport when ANAGLYPH
  15348. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15349. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15350. }
  15351. };
  15352. Camera.prototype._setupInputs = function () {
  15353. };
  15354. Camera.prototype.serialize = function () {
  15355. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15356. // Type
  15357. serializationObject.type = this.getClassName();
  15358. // Parent
  15359. if (this.parent) {
  15360. serializationObject.parentId = this.parent.id;
  15361. }
  15362. if (this.inputs) {
  15363. this.inputs.serialize(serializationObject);
  15364. }
  15365. // Animations
  15366. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15367. serializationObject.ranges = this.serializeAnimationRanges();
  15368. return serializationObject;
  15369. };
  15370. Camera.prototype.clone = function (name) {
  15371. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15372. };
  15373. Camera.prototype.getDirection = function (localAxis) {
  15374. var result = BABYLON.Vector3.Zero();
  15375. this.getDirectionToRef(localAxis, result);
  15376. return result;
  15377. };
  15378. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15379. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15380. };
  15381. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15382. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15383. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15384. switch (type) {
  15385. case "ArcRotateCamera":
  15386. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15387. case "DeviceOrientationCamera":
  15388. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15389. case "FollowCamera":
  15390. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15391. case "ArcFollowCamera":
  15392. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15393. case "GamepadCamera":
  15394. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15395. case "TouchCamera":
  15396. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15397. case "VirtualJoysticksCamera":
  15398. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15399. case "WebVRFreeCamera":
  15400. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15401. case "WebVRGamepadCamera":
  15402. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15403. case "VRDeviceOrientationFreeCamera":
  15404. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15405. case "VRDeviceOrientationGamepadCamera":
  15406. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15407. case "AnaglyphArcRotateCamera":
  15408. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15409. case "AnaglyphFreeCamera":
  15410. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15411. case "AnaglyphGamepadCamera":
  15412. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15413. case "AnaglyphUniversalCamera":
  15414. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15415. case "StereoscopicArcRotateCamera":
  15416. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15417. case "StereoscopicFreeCamera":
  15418. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15419. case "StereoscopicGamepadCamera":
  15420. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15421. case "StereoscopicUniversalCamera":
  15422. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15423. case "FreeCamera":// Forcing Universal here
  15424. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15425. default:// Universal Camera is the default value
  15426. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15427. }
  15428. };
  15429. Camera.Parse = function (parsedCamera, scene) {
  15430. var type = parsedCamera.type;
  15431. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15432. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15433. // Parent
  15434. if (parsedCamera.parentId) {
  15435. camera._waitingParentId = parsedCamera.parentId;
  15436. }
  15437. //If camera has an input manager, let it parse inputs settings
  15438. if (camera.inputs) {
  15439. camera.inputs.parse(parsedCamera);
  15440. camera._setupInputs();
  15441. }
  15442. if (camera.setPosition) {
  15443. camera.position.copyFromFloats(0, 0, 0);
  15444. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15445. }
  15446. // Target
  15447. if (parsedCamera.target) {
  15448. if (camera.setTarget) {
  15449. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15450. }
  15451. }
  15452. // Apply 3d rig, when found
  15453. if (parsedCamera.cameraRigMode) {
  15454. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15455. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15456. }
  15457. // Animations
  15458. if (parsedCamera.animations) {
  15459. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15460. var parsedAnimation = parsedCamera.animations[animationIndex];
  15461. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15462. }
  15463. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15464. }
  15465. if (parsedCamera.autoAnimate) {
  15466. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15467. }
  15468. return camera;
  15469. };
  15470. // Statics
  15471. Camera._PERSPECTIVE_CAMERA = 0;
  15472. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15473. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15474. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15475. Camera._RIG_MODE_NONE = 0;
  15476. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15477. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15478. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15479. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15480. Camera._RIG_MODE_VR = 20;
  15481. Camera._RIG_MODE_WEBVR = 21;
  15482. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15483. __decorate([
  15484. BABYLON.serializeAsVector3()
  15485. ], Camera.prototype, "position", void 0);
  15486. __decorate([
  15487. BABYLON.serializeAsVector3()
  15488. ], Camera.prototype, "upVector", void 0);
  15489. __decorate([
  15490. BABYLON.serialize()
  15491. ], Camera.prototype, "orthoLeft", void 0);
  15492. __decorate([
  15493. BABYLON.serialize()
  15494. ], Camera.prototype, "orthoRight", void 0);
  15495. __decorate([
  15496. BABYLON.serialize()
  15497. ], Camera.prototype, "orthoBottom", void 0);
  15498. __decorate([
  15499. BABYLON.serialize()
  15500. ], Camera.prototype, "orthoTop", void 0);
  15501. __decorate([
  15502. BABYLON.serialize()
  15503. ], Camera.prototype, "fov", void 0);
  15504. __decorate([
  15505. BABYLON.serialize()
  15506. ], Camera.prototype, "minZ", void 0);
  15507. __decorate([
  15508. BABYLON.serialize()
  15509. ], Camera.prototype, "maxZ", void 0);
  15510. __decorate([
  15511. BABYLON.serialize()
  15512. ], Camera.prototype, "inertia", void 0);
  15513. __decorate([
  15514. BABYLON.serialize()
  15515. ], Camera.prototype, "mode", void 0);
  15516. __decorate([
  15517. BABYLON.serialize()
  15518. ], Camera.prototype, "layerMask", void 0);
  15519. __decorate([
  15520. BABYLON.serialize()
  15521. ], Camera.prototype, "fovMode", void 0);
  15522. __decorate([
  15523. BABYLON.serialize()
  15524. ], Camera.prototype, "cameraRigMode", void 0);
  15525. __decorate([
  15526. BABYLON.serialize()
  15527. ], Camera.prototype, "interaxialDistance", void 0);
  15528. __decorate([
  15529. BABYLON.serialize()
  15530. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15531. return Camera;
  15532. }(BABYLON.Node));
  15533. BABYLON.Camera = Camera;
  15534. })(BABYLON || (BABYLON = {}));
  15535. //# sourceMappingURL=babylon.camera.js.map
  15536. var BABYLON;
  15537. (function (BABYLON) {
  15538. var RenderingManager = (function () {
  15539. function RenderingManager(scene) {
  15540. this._renderingGroups = new Array();
  15541. this._autoClearDepthStencil = {};
  15542. this._customOpaqueSortCompareFn = {};
  15543. this._customAlphaTestSortCompareFn = {};
  15544. this._customTransparentSortCompareFn = {};
  15545. this._renderinGroupInfo = null;
  15546. this._scene = scene;
  15547. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15548. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15549. }
  15550. }
  15551. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15552. if (depth === void 0) { depth = true; }
  15553. if (stencil === void 0) { stencil = true; }
  15554. if (this._depthStencilBufferAlreadyCleaned) {
  15555. return;
  15556. }
  15557. this._scene.getEngine().clear(null, false, depth, stencil);
  15558. this._depthStencilBufferAlreadyCleaned = true;
  15559. };
  15560. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15561. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15562. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15563. var info = null;
  15564. if (observable) {
  15565. if (!this._renderinGroupInfo) {
  15566. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15567. }
  15568. info = this._renderinGroupInfo;
  15569. info.scene = this._scene;
  15570. info.camera = this._scene.activeCamera;
  15571. }
  15572. // Dispatch sprites
  15573. if (renderSprites) {
  15574. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15575. var manager = this._scene.spriteManagers[index];
  15576. this.dispatchSprites(manager);
  15577. }
  15578. }
  15579. // Render
  15580. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15581. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15582. var renderingGroup = this._renderingGroups[index];
  15583. if (!renderingGroup && !observable)
  15584. continue;
  15585. this._currentIndex = index;
  15586. var renderingGroupMask = 0;
  15587. // Fire PRECLEAR stage
  15588. if (observable) {
  15589. renderingGroupMask = Math.pow(2, index);
  15590. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15591. info.renderingGroupId = index;
  15592. observable.notifyObservers(info, renderingGroupMask);
  15593. }
  15594. // Clear depth/stencil if needed
  15595. if (RenderingManager.AUTOCLEAR) {
  15596. var autoClear = this._autoClearDepthStencil[index];
  15597. if (autoClear && autoClear.autoClear) {
  15598. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15599. }
  15600. }
  15601. if (observable) {
  15602. // Fire PREOPAQUE stage
  15603. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15604. observable.notifyObservers(info, renderingGroupMask);
  15605. // Fire PRETRANSPARENT stage
  15606. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15607. observable.notifyObservers(info, renderingGroupMask);
  15608. }
  15609. if (renderingGroup)
  15610. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15611. // Fire POSTTRANSPARENT stage
  15612. if (observable) {
  15613. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15614. observable.notifyObservers(info, renderingGroupMask);
  15615. }
  15616. }
  15617. };
  15618. RenderingManager.prototype.reset = function () {
  15619. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15620. var renderingGroup = this._renderingGroups[index];
  15621. if (renderingGroup) {
  15622. renderingGroup.prepare();
  15623. }
  15624. }
  15625. };
  15626. RenderingManager.prototype.dispose = function () {
  15627. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15628. var renderingGroup = this._renderingGroups[index];
  15629. if (renderingGroup) {
  15630. renderingGroup.dispose();
  15631. }
  15632. }
  15633. this._renderingGroups.length = 0;
  15634. };
  15635. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15636. if (!this._renderingGroups[renderingGroupId]) {
  15637. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15638. }
  15639. };
  15640. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15641. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15642. this._prepareRenderingGroup(renderingGroupId);
  15643. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15644. };
  15645. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15646. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15647. this._prepareRenderingGroup(renderingGroupId);
  15648. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15649. };
  15650. RenderingManager.prototype.dispatch = function (subMesh) {
  15651. var mesh = subMesh.getMesh();
  15652. var renderingGroupId = mesh.renderingGroupId || 0;
  15653. this._prepareRenderingGroup(renderingGroupId);
  15654. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15655. };
  15656. /**
  15657. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15658. * This allowed control for front to back rendering or reversly depending of the special needs.
  15659. *
  15660. * @param renderingGroupId The rendering group id corresponding to its index
  15661. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15662. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15663. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15664. */
  15665. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15666. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15667. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15668. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15669. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15670. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15671. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15672. if (this._renderingGroups[renderingGroupId]) {
  15673. var group = this._renderingGroups[renderingGroupId];
  15674. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15675. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15676. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15677. }
  15678. };
  15679. /**
  15680. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15681. *
  15682. * @param renderingGroupId The rendering group id corresponding to its index
  15683. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15684. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15685. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15686. */
  15687. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15688. if (depth === void 0) { depth = true; }
  15689. if (stencil === void 0) { stencil = true; }
  15690. this._autoClearDepthStencil[renderingGroupId] = {
  15691. autoClear: autoClearDepthStencil,
  15692. depth: depth,
  15693. stencil: stencil
  15694. };
  15695. };
  15696. /**
  15697. * The max id used for rendering groups (not included)
  15698. */
  15699. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15700. /**
  15701. * The min id used for rendering groups (included)
  15702. */
  15703. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15704. /**
  15705. * Used to globally prevent autoclearing scenes.
  15706. */
  15707. RenderingManager.AUTOCLEAR = true;
  15708. return RenderingManager;
  15709. }());
  15710. BABYLON.RenderingManager = RenderingManager;
  15711. })(BABYLON || (BABYLON = {}));
  15712. //# sourceMappingURL=babylon.renderingManager.js.map
  15713. var BABYLON;
  15714. (function (BABYLON) {
  15715. var RenderingGroup = (function () {
  15716. /**
  15717. * Creates a new rendering group.
  15718. * @param index The rendering group index
  15719. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15720. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15721. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15722. */
  15723. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15724. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15725. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15726. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15727. this.index = index;
  15728. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15729. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15730. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15731. this._particleSystems = new BABYLON.SmartArray(256);
  15732. this._spriteManagers = new BABYLON.SmartArray(256);
  15733. this._edgesRenderers = new BABYLON.SmartArray(16);
  15734. this._scene = scene;
  15735. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15736. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15737. this.transparentSortCompareFn = transparentSortCompareFn;
  15738. }
  15739. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15740. /**
  15741. * Set the opaque sort comparison function.
  15742. * If null the sub meshes will be render in the order they were created
  15743. */
  15744. set: function (value) {
  15745. this._opaqueSortCompareFn = value;
  15746. if (value) {
  15747. this._renderOpaque = this.renderOpaqueSorted;
  15748. }
  15749. else {
  15750. this._renderOpaque = RenderingGroup.renderUnsorted;
  15751. }
  15752. },
  15753. enumerable: true,
  15754. configurable: true
  15755. });
  15756. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15757. /**
  15758. * Set the alpha test sort comparison function.
  15759. * If null the sub meshes will be render in the order they were created
  15760. */
  15761. set: function (value) {
  15762. this._alphaTestSortCompareFn = value;
  15763. if (value) {
  15764. this._renderAlphaTest = this.renderAlphaTestSorted;
  15765. }
  15766. else {
  15767. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15768. }
  15769. },
  15770. enumerable: true,
  15771. configurable: true
  15772. });
  15773. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15774. /**
  15775. * Set the transparent sort comparison function.
  15776. * If null the sub meshes will be render in the order they were created
  15777. */
  15778. set: function (value) {
  15779. if (value) {
  15780. this._transparentSortCompareFn = value;
  15781. }
  15782. else {
  15783. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15784. }
  15785. this._renderTransparent = this.renderTransparentSorted;
  15786. },
  15787. enumerable: true,
  15788. configurable: true
  15789. });
  15790. /**
  15791. * Render all the sub meshes contained in the group.
  15792. * @param customRenderFunction Used to override the default render behaviour of the group.
  15793. * @returns true if rendered some submeshes.
  15794. */
  15795. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  15796. if (customRenderFunction) {
  15797. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15798. return;
  15799. }
  15800. var engine = this._scene.getEngine();
  15801. // Opaque
  15802. if (this._opaqueSubMeshes.length !== 0) {
  15803. this._renderOpaque(this._opaqueSubMeshes);
  15804. }
  15805. // Alpha test
  15806. if (this._alphaTestSubMeshes.length !== 0) {
  15807. engine.setAlphaTesting(true);
  15808. this._renderAlphaTest(this._alphaTestSubMeshes);
  15809. engine.setAlphaTesting(false);
  15810. }
  15811. var stencilState = engine.getStencilBuffer();
  15812. engine.setStencilBuffer(false);
  15813. // Sprites
  15814. if (renderSprites) {
  15815. this._renderSprites();
  15816. }
  15817. // Particles
  15818. if (renderParticles) {
  15819. this._renderParticles(activeMeshes);
  15820. }
  15821. if (this.onBeforeTransparentRendering) {
  15822. this.onBeforeTransparentRendering();
  15823. }
  15824. // Transparent
  15825. if (this._transparentSubMeshes.length !== 0) {
  15826. this._renderTransparent(this._transparentSubMeshes);
  15827. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15828. }
  15829. // Set back stencil to false in case it changes before the edge renderer.
  15830. engine.setStencilBuffer(false);
  15831. // Edges
  15832. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15833. this._edgesRenderers.data[edgesRendererIndex].render();
  15834. }
  15835. // Restore Stencil state.
  15836. engine.setStencilBuffer(stencilState);
  15837. };
  15838. /**
  15839. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15840. * @param subMeshes The submeshes to render
  15841. */
  15842. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15843. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15844. };
  15845. /**
  15846. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15847. * @param subMeshes The submeshes to render
  15848. */
  15849. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15850. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15851. };
  15852. /**
  15853. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15854. * @param subMeshes The submeshes to render
  15855. */
  15856. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15857. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15858. };
  15859. /**
  15860. * Renders the submeshes in a specified order.
  15861. * @param subMeshes The submeshes to sort before render
  15862. * @param sortCompareFn The comparison function use to sort
  15863. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15864. * @param transparent Specifies to activate blending if true
  15865. */
  15866. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15867. var subIndex = 0;
  15868. var subMesh;
  15869. for (; subIndex < subMeshes.length; subIndex++) {
  15870. subMesh = subMeshes.data[subIndex];
  15871. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15872. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15873. }
  15874. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15875. sortedArray.sort(sortCompareFn);
  15876. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15877. subMesh = sortedArray[subIndex];
  15878. subMesh.render(transparent);
  15879. }
  15880. };
  15881. /**
  15882. * Renders the submeshes in the order they were dispatched (no sort applied).
  15883. * @param subMeshes The submeshes to render
  15884. */
  15885. RenderingGroup.renderUnsorted = function (subMeshes) {
  15886. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15887. var submesh = subMeshes.data[subIndex];
  15888. submesh.render(false);
  15889. }
  15890. };
  15891. /**
  15892. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15893. * are rendered back to front if in the same alpha index.
  15894. *
  15895. * @param a The first submesh
  15896. * @param b The second submesh
  15897. * @returns The result of the comparison
  15898. */
  15899. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15900. // Alpha index first
  15901. if (a._alphaIndex > b._alphaIndex) {
  15902. return 1;
  15903. }
  15904. if (a._alphaIndex < b._alphaIndex) {
  15905. return -1;
  15906. }
  15907. // Then distance to camera
  15908. return RenderingGroup.backToFrontSortCompare(a, b);
  15909. };
  15910. /**
  15911. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15912. * are rendered back to front.
  15913. *
  15914. * @param a The first submesh
  15915. * @param b The second submesh
  15916. * @returns The result of the comparison
  15917. */
  15918. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15919. // Then distance to camera
  15920. if (a._distanceToCamera < b._distanceToCamera) {
  15921. return 1;
  15922. }
  15923. if (a._distanceToCamera > b._distanceToCamera) {
  15924. return -1;
  15925. }
  15926. return 0;
  15927. };
  15928. /**
  15929. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15930. * are rendered front to back (prevent overdraw).
  15931. *
  15932. * @param a The first submesh
  15933. * @param b The second submesh
  15934. * @returns The result of the comparison
  15935. */
  15936. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15937. // Then distance to camera
  15938. if (a._distanceToCamera < b._distanceToCamera) {
  15939. return -1;
  15940. }
  15941. if (a._distanceToCamera > b._distanceToCamera) {
  15942. return 1;
  15943. }
  15944. return 0;
  15945. };
  15946. /**
  15947. * Resets the different lists of submeshes to prepare a new frame.
  15948. */
  15949. RenderingGroup.prototype.prepare = function () {
  15950. this._opaqueSubMeshes.reset();
  15951. this._transparentSubMeshes.reset();
  15952. this._alphaTestSubMeshes.reset();
  15953. this._particleSystems.reset();
  15954. this._spriteManagers.reset();
  15955. this._edgesRenderers.reset();
  15956. };
  15957. RenderingGroup.prototype.dispose = function () {
  15958. this._opaqueSubMeshes.dispose();
  15959. this._transparentSubMeshes.dispose();
  15960. this._alphaTestSubMeshes.dispose();
  15961. this._particleSystems.dispose();
  15962. this._spriteManagers.dispose();
  15963. this._edgesRenderers.dispose();
  15964. };
  15965. /**
  15966. * Inserts the submesh in its correct queue depending on its material.
  15967. * @param subMesh The submesh to dispatch
  15968. */
  15969. RenderingGroup.prototype.dispatch = function (subMesh) {
  15970. var material = subMesh.getMaterial();
  15971. var mesh = subMesh.getMesh();
  15972. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15973. this._transparentSubMeshes.push(subMesh);
  15974. }
  15975. else if (material.needAlphaTesting()) {
  15976. this._alphaTestSubMeshes.push(subMesh);
  15977. }
  15978. else {
  15979. this._opaqueSubMeshes.push(subMesh); // Opaque
  15980. }
  15981. if (mesh._edgesRenderer) {
  15982. this._edgesRenderers.push(mesh._edgesRenderer);
  15983. }
  15984. };
  15985. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15986. this._spriteManagers.push(spriteManager);
  15987. };
  15988. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15989. this._particleSystems.push(particleSystem);
  15990. };
  15991. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15992. if (this._particleSystems.length === 0) {
  15993. return;
  15994. }
  15995. // Particles
  15996. var activeCamera = this._scene.activeCamera;
  15997. this._scene._particlesDuration.beginMonitoring();
  15998. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15999. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16000. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16001. continue;
  16002. }
  16003. var emitter = particleSystem.emitter;
  16004. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16005. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16006. }
  16007. }
  16008. this._scene._particlesDuration.endMonitoring(false);
  16009. };
  16010. RenderingGroup.prototype._renderSprites = function () {
  16011. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16012. return;
  16013. }
  16014. // Sprites
  16015. var activeCamera = this._scene.activeCamera;
  16016. this._scene._spritesDuration.beginMonitoring();
  16017. for (var id = 0; id < this._spriteManagers.length; id++) {
  16018. var spriteManager = this._spriteManagers.data[id];
  16019. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16020. spriteManager.render();
  16021. }
  16022. }
  16023. this._scene._spritesDuration.endMonitoring(false);
  16024. };
  16025. return RenderingGroup;
  16026. }());
  16027. BABYLON.RenderingGroup = RenderingGroup;
  16028. })(BABYLON || (BABYLON = {}));
  16029. //# sourceMappingURL=babylon.renderingGroup.js.map
  16030. var BABYLON;
  16031. (function (BABYLON) {
  16032. var ClickInfo = (function () {
  16033. function ClickInfo() {
  16034. this._singleClick = false;
  16035. this._doubleClick = false;
  16036. this._hasSwiped = false;
  16037. this._ignore = false;
  16038. }
  16039. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16040. get: function () {
  16041. return this._singleClick;
  16042. },
  16043. set: function (b) {
  16044. this._singleClick = b;
  16045. },
  16046. enumerable: true,
  16047. configurable: true
  16048. });
  16049. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16050. get: function () {
  16051. return this._doubleClick;
  16052. },
  16053. set: function (b) {
  16054. this._doubleClick = b;
  16055. },
  16056. enumerable: true,
  16057. configurable: true
  16058. });
  16059. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16060. get: function () {
  16061. return this._hasSwiped;
  16062. },
  16063. set: function (b) {
  16064. this._hasSwiped = b;
  16065. },
  16066. enumerable: true,
  16067. configurable: true
  16068. });
  16069. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16070. get: function () {
  16071. return this._ignore;
  16072. },
  16073. set: function (b) {
  16074. this._ignore = b;
  16075. },
  16076. enumerable: true,
  16077. configurable: true
  16078. });
  16079. return ClickInfo;
  16080. }());
  16081. var PointerEventTypes = (function () {
  16082. function PointerEventTypes() {
  16083. }
  16084. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16085. get: function () {
  16086. return PointerEventTypes._POINTERDOWN;
  16087. },
  16088. enumerable: true,
  16089. configurable: true
  16090. });
  16091. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16092. get: function () {
  16093. return PointerEventTypes._POINTERUP;
  16094. },
  16095. enumerable: true,
  16096. configurable: true
  16097. });
  16098. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16099. get: function () {
  16100. return PointerEventTypes._POINTERMOVE;
  16101. },
  16102. enumerable: true,
  16103. configurable: true
  16104. });
  16105. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16106. get: function () {
  16107. return PointerEventTypes._POINTERWHEEL;
  16108. },
  16109. enumerable: true,
  16110. configurable: true
  16111. });
  16112. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16113. get: function () {
  16114. return PointerEventTypes._POINTERPICK;
  16115. },
  16116. enumerable: true,
  16117. configurable: true
  16118. });
  16119. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  16120. get: function () {
  16121. return PointerEventTypes._POINTERTAP;
  16122. },
  16123. enumerable: true,
  16124. configurable: true
  16125. });
  16126. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  16127. get: function () {
  16128. return PointerEventTypes._POINTERDOUBLETAP;
  16129. },
  16130. enumerable: true,
  16131. configurable: true
  16132. });
  16133. PointerEventTypes._POINTERDOWN = 0x01;
  16134. PointerEventTypes._POINTERUP = 0x02;
  16135. PointerEventTypes._POINTERMOVE = 0x04;
  16136. PointerEventTypes._POINTERWHEEL = 0x08;
  16137. PointerEventTypes._POINTERPICK = 0x10;
  16138. PointerEventTypes._POINTERTAP = 0x20;
  16139. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  16140. return PointerEventTypes;
  16141. }());
  16142. BABYLON.PointerEventTypes = PointerEventTypes;
  16143. var PointerInfoBase = (function () {
  16144. function PointerInfoBase(type, event) {
  16145. this.type = type;
  16146. this.event = event;
  16147. }
  16148. return PointerInfoBase;
  16149. }());
  16150. BABYLON.PointerInfoBase = PointerInfoBase;
  16151. /**
  16152. * This class is used to store pointer related info for the onPrePointerObservable event.
  16153. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16154. */
  16155. var PointerInfoPre = (function (_super) {
  16156. __extends(PointerInfoPre, _super);
  16157. function PointerInfoPre(type, event, localX, localY) {
  16158. var _this = _super.call(this, type, event) || this;
  16159. _this.skipOnPointerObservable = false;
  16160. _this.localPosition = new BABYLON.Vector2(localX, localY);
  16161. return _this;
  16162. }
  16163. return PointerInfoPre;
  16164. }(PointerInfoBase));
  16165. BABYLON.PointerInfoPre = PointerInfoPre;
  16166. /**
  16167. * This type contains all the data related to a pointer event in Babylon.js.
  16168. * 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.
  16169. */
  16170. var PointerInfo = (function (_super) {
  16171. __extends(PointerInfo, _super);
  16172. function PointerInfo(type, event, pickInfo) {
  16173. var _this = _super.call(this, type, event) || this;
  16174. _this.pickInfo = pickInfo;
  16175. return _this;
  16176. }
  16177. return PointerInfo;
  16178. }(PointerInfoBase));
  16179. BABYLON.PointerInfo = PointerInfo;
  16180. /**
  16181. * This class is used by the onRenderingGroupObservable
  16182. */
  16183. var RenderingGroupInfo = (function () {
  16184. function RenderingGroupInfo() {
  16185. }
  16186. /**
  16187. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16188. * This stage will be fired no matter what
  16189. */
  16190. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16191. /**
  16192. * Called before opaque object are rendered.
  16193. * This stage will be fired only if there's 3D Opaque content to render
  16194. */
  16195. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16196. /**
  16197. * Called after the opaque objects are rendered and before the transparent ones
  16198. * This stage will be fired only if there's 3D transparent content to render
  16199. */
  16200. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16201. /**
  16202. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16203. * This stage will be fired no matter what
  16204. */
  16205. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16206. return RenderingGroupInfo;
  16207. }());
  16208. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16209. /**
  16210. * Represents a scene to be rendered by the engine.
  16211. * @see http://doc.babylonjs.com/page.php?p=21911
  16212. */
  16213. var Scene = (function () {
  16214. /**
  16215. * @constructor
  16216. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16217. */
  16218. function Scene(engine) {
  16219. // Members
  16220. this.autoClear = true;
  16221. this.autoClearDepthAndStencil = true;
  16222. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16223. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16224. this.forceWireframe = false;
  16225. this._forcePointsCloud = false;
  16226. this.forceShowBoundingBoxes = false;
  16227. this.animationsEnabled = true;
  16228. this.constantlyUpdateMeshUnderPointer = false;
  16229. this.hoverCursor = "pointer";
  16230. this.defaultCursor = "";
  16231. // Metadata
  16232. this.metadata = null;
  16233. // Events
  16234. /**
  16235. * An event triggered when the scene is disposed.
  16236. * @type {BABYLON.Observable}
  16237. */
  16238. this.onDisposeObservable = new BABYLON.Observable();
  16239. /**
  16240. * An event triggered before rendering the scene
  16241. * @type {BABYLON.Observable}
  16242. */
  16243. this.onBeforeRenderObservable = new BABYLON.Observable();
  16244. /**
  16245. * An event triggered after rendering the scene
  16246. * @type {BABYLON.Observable}
  16247. */
  16248. this.onAfterRenderObservable = new BABYLON.Observable();
  16249. /**
  16250. * An event triggered when the scene is ready
  16251. * @type {BABYLON.Observable}
  16252. */
  16253. this.onReadyObservable = new BABYLON.Observable();
  16254. /**
  16255. * An event triggered before rendering a camera
  16256. * @type {BABYLON.Observable}
  16257. */
  16258. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16259. /**
  16260. * An event triggered after rendering a camera
  16261. * @type {BABYLON.Observable}
  16262. */
  16263. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16264. /**
  16265. * An event triggered when a camera is created
  16266. * @type {BABYLON.Observable}
  16267. */
  16268. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16269. /**
  16270. * An event triggered when a camera is removed
  16271. * @type {BABYLON.Observable}
  16272. */
  16273. this.onCameraRemovedObservable = new BABYLON.Observable();
  16274. /**
  16275. * An event triggered when a light is created
  16276. * @type {BABYLON.Observable}
  16277. */
  16278. this.onNewLightAddedObservable = new BABYLON.Observable();
  16279. /**
  16280. * An event triggered when a light is removed
  16281. * @type {BABYLON.Observable}
  16282. */
  16283. this.onLightRemovedObservable = new BABYLON.Observable();
  16284. /**
  16285. * An event triggered when a geometry is created
  16286. * @type {BABYLON.Observable}
  16287. */
  16288. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16289. /**
  16290. * An event triggered when a geometry is removed
  16291. * @type {BABYLON.Observable}
  16292. */
  16293. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16294. /**
  16295. * An event triggered when a mesh is created
  16296. * @type {BABYLON.Observable}
  16297. */
  16298. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16299. /**
  16300. * An event triggered when a mesh is removed
  16301. * @type {BABYLON.Observable}
  16302. */
  16303. this.onMeshRemovedObservable = new BABYLON.Observable();
  16304. /**
  16305. * An event triggered before calculating deterministic simulation step
  16306. * @type {BABYLON.Observable}
  16307. */
  16308. this.onBeforeStepObservable = new BABYLON.Observable();
  16309. /**
  16310. * An event triggered after calculating deterministic simulation step
  16311. * @type {BABYLON.Observable}
  16312. */
  16313. this.onAfterStepObservable = new BABYLON.Observable();
  16314. /**
  16315. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16316. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16317. * 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)
  16318. */
  16319. this.onRenderingGroupObservable = new BABYLON.Observable();
  16320. // Animations
  16321. this.animations = [];
  16322. /**
  16323. * 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).
  16324. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16325. */
  16326. this.onPrePointerObservable = new BABYLON.Observable();
  16327. /**
  16328. * Observable event triggered each time an input event is received from the rendering canvas
  16329. */
  16330. this.onPointerObservable = new BABYLON.Observable();
  16331. this._meshPickProceed = false;
  16332. this._previousHasSwiped = false;
  16333. this._currentPickResult = null;
  16334. this._previousPickResult = null;
  16335. this._isButtonPressed = false;
  16336. this._doubleClickOccured = false;
  16337. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16338. this.cameraToUseForPointers = null;
  16339. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16340. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16341. this._startingPointerTime = 0;
  16342. this._previousStartingPointerTime = 0;
  16343. // Deterministic lockstep
  16344. this._timeAccumulator = 0;
  16345. this._currentStepId = 0;
  16346. this._currentInternalStep = 0;
  16347. // Coordinate system
  16348. /**
  16349. * use right-handed coordinate system on this scene.
  16350. * @type {boolean}
  16351. */
  16352. this._useRightHandedSystem = false;
  16353. // Fog
  16354. this._fogEnabled = true;
  16355. this._fogMode = Scene.FOGMODE_NONE;
  16356. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16357. this.fogDensity = 0.1;
  16358. this.fogStart = 0;
  16359. this.fogEnd = 1000.0;
  16360. // Lights
  16361. /**
  16362. * is shadow enabled on this scene.
  16363. * @type {boolean}
  16364. */
  16365. this._shadowsEnabled = true;
  16366. /**
  16367. * is light enabled on this scene.
  16368. * @type {boolean}
  16369. */
  16370. this._lightsEnabled = true;
  16371. /**
  16372. * All of the lights added to this scene.
  16373. * @see BABYLON.Light
  16374. * @type {BABYLON.Light[]}
  16375. */
  16376. this.lights = new Array();
  16377. // Cameras
  16378. /** All of the cameras added to this scene. */
  16379. this.cameras = new Array();
  16380. /** All of the active cameras added to this scene. */
  16381. this.activeCameras = new Array();
  16382. // Meshes
  16383. /**
  16384. * All of the (abstract) meshes added to this scene.
  16385. * @see BABYLON.AbstractMesh
  16386. * @type {BABYLON.AbstractMesh[]}
  16387. */
  16388. this.meshes = new Array();
  16389. // Geometries
  16390. this._geometries = new Array();
  16391. this.materials = new Array();
  16392. this.multiMaterials = new Array();
  16393. // Textures
  16394. this._texturesEnabled = true;
  16395. this.textures = new Array();
  16396. // Particles
  16397. this.particlesEnabled = true;
  16398. this.particleSystems = new Array();
  16399. // Sprites
  16400. this.spritesEnabled = true;
  16401. this.spriteManagers = new Array();
  16402. // Layers
  16403. this.layers = new Array();
  16404. this.highlightLayers = new Array();
  16405. // Skeletons
  16406. this._skeletonsEnabled = true;
  16407. this.skeletons = new Array();
  16408. // Morph targets
  16409. this.morphTargetManagers = new Array();
  16410. // Lens flares
  16411. this.lensFlaresEnabled = true;
  16412. this.lensFlareSystems = new Array();
  16413. // Collisions
  16414. this.collisionsEnabled = true;
  16415. /** Defines the gravity applied to this scene */
  16416. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16417. // Postprocesses
  16418. this.postProcesses = new Array();
  16419. this.postProcessesEnabled = true;
  16420. // Customs render targets
  16421. this.renderTargetsEnabled = true;
  16422. this.dumpNextRenderTargets = false;
  16423. this.customRenderTargets = new Array();
  16424. // Imported meshes
  16425. this.importedMeshesFiles = new Array();
  16426. // Probes
  16427. this.probesEnabled = true;
  16428. this.reflectionProbes = new Array();
  16429. this._actionManagers = new Array();
  16430. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16431. // Procedural textures
  16432. this.proceduralTexturesEnabled = true;
  16433. this._proceduralTextures = new Array();
  16434. this.soundTracks = new Array();
  16435. this._audioEnabled = true;
  16436. this._headphone = false;
  16437. // Performance counters
  16438. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16439. this._totalLightsCounter = new BABYLON.PerfCounter();
  16440. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16441. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16442. this._totalVertices = new BABYLON.PerfCounter();
  16443. this._activeIndices = new BABYLON.PerfCounter();
  16444. this._activeParticles = new BABYLON.PerfCounter();
  16445. this._lastFrameDuration = new BABYLON.PerfCounter();
  16446. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16447. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16448. this._particlesDuration = new BABYLON.PerfCounter();
  16449. this._renderDuration = new BABYLON.PerfCounter();
  16450. this._spritesDuration = new BABYLON.PerfCounter();
  16451. this._activeBones = new BABYLON.PerfCounter();
  16452. this._animationTime = 0;
  16453. this.animationTimeScale = 1;
  16454. this._renderId = 0;
  16455. this._executeWhenReadyTimeoutId = -1;
  16456. this._intermediateRendering = false;
  16457. this._viewUpdateFlag = -1;
  16458. this._projectionUpdateFlag = -1;
  16459. this._toBeDisposed = new BABYLON.SmartArray(256);
  16460. this._pendingData = []; //ANY
  16461. this._activeMeshes = new BABYLON.SmartArray(256);
  16462. this._processedMaterials = new BABYLON.SmartArray(256);
  16463. this._renderTargets = new BABYLON.SmartArray(256);
  16464. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16465. this._activeSkeletons = new BABYLON.SmartArray(32);
  16466. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16467. this._activeAnimatables = new Array();
  16468. this._transformMatrix = BABYLON.Matrix.Zero();
  16469. this.requireLightSorting = false;
  16470. this._uniqueIdCounter = 0;
  16471. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16472. this._engine.scenes.push(this);
  16473. this._uid = null;
  16474. this._renderingManager = new BABYLON.RenderingManager(this);
  16475. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16476. if (BABYLON.OutlineRenderer) {
  16477. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16478. }
  16479. this.attachControl();
  16480. if (BABYLON.SoundTrack) {
  16481. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16482. }
  16483. //simplification queue
  16484. if (BABYLON.SimplificationQueue) {
  16485. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16486. }
  16487. //collision coordinator initialization. For now legacy per default.
  16488. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16489. // Uniform Buffer
  16490. this._createUbo();
  16491. // Default Image processing definition.
  16492. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16493. }
  16494. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16495. /** The fog is deactivated */
  16496. get: function () {
  16497. return Scene._FOGMODE_NONE;
  16498. },
  16499. enumerable: true,
  16500. configurable: true
  16501. });
  16502. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16503. /** The fog density is following an exponential function */
  16504. get: function () {
  16505. return Scene._FOGMODE_EXP;
  16506. },
  16507. enumerable: true,
  16508. configurable: true
  16509. });
  16510. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16511. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16512. get: function () {
  16513. return Scene._FOGMODE_EXP2;
  16514. },
  16515. enumerable: true,
  16516. configurable: true
  16517. });
  16518. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16519. /** The fog density is following a linear function. */
  16520. get: function () {
  16521. return Scene._FOGMODE_LINEAR;
  16522. },
  16523. enumerable: true,
  16524. configurable: true
  16525. });
  16526. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16527. /**
  16528. * Texture used in all pbr material as the reflection texture.
  16529. * As in the majority of the scene they are the same (exception for multi room and so on),
  16530. * this is easier to reference from here than from all the materials.
  16531. */
  16532. get: function () {
  16533. return this._environmentTexture;
  16534. },
  16535. /**
  16536. * Texture used in all pbr material as the reflection texture.
  16537. * As in the majority of the scene they are the same (exception for multi room and so on),
  16538. * this is easier to set here than in all the materials.
  16539. */
  16540. set: function (value) {
  16541. this._environmentTexture = value;
  16542. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16543. },
  16544. enumerable: true,
  16545. configurable: true
  16546. });
  16547. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16548. /**
  16549. * Default image processing configuration used either in the rendering
  16550. * Forward main pass or through the imageProcessingPostProcess if present.
  16551. * As in the majority of the scene they are the same (exception for multi camera),
  16552. * this is easier to reference from here than from all the materials and post process.
  16553. *
  16554. * No setter as we it is a shared configuration, you can set the values instead.
  16555. */
  16556. get: function () {
  16557. return this._imageProcessingConfiguration;
  16558. },
  16559. enumerable: true,
  16560. configurable: true
  16561. });
  16562. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16563. get: function () {
  16564. return this._forcePointsCloud;
  16565. },
  16566. set: function (value) {
  16567. if (this._forcePointsCloud === value) {
  16568. return;
  16569. }
  16570. this._forcePointsCloud = value;
  16571. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16572. },
  16573. enumerable: true,
  16574. configurable: true
  16575. });
  16576. Object.defineProperty(Scene.prototype, "onDispose", {
  16577. /** A function to be executed when this scene is disposed. */
  16578. set: function (callback) {
  16579. if (this._onDisposeObserver) {
  16580. this.onDisposeObservable.remove(this._onDisposeObserver);
  16581. }
  16582. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16583. },
  16584. enumerable: true,
  16585. configurable: true
  16586. });
  16587. Object.defineProperty(Scene.prototype, "beforeRender", {
  16588. /** A function to be executed before rendering this scene */
  16589. set: function (callback) {
  16590. if (this._onBeforeRenderObserver) {
  16591. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16592. }
  16593. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16594. },
  16595. enumerable: true,
  16596. configurable: true
  16597. });
  16598. Object.defineProperty(Scene.prototype, "afterRender", {
  16599. /** A function to be executed after rendering this scene */
  16600. set: function (callback) {
  16601. if (this._onAfterRenderObserver) {
  16602. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16603. }
  16604. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16605. },
  16606. enumerable: true,
  16607. configurable: true
  16608. });
  16609. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16610. set: function (callback) {
  16611. if (this._onBeforeCameraRenderObserver) {
  16612. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16613. }
  16614. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16615. },
  16616. enumerable: true,
  16617. configurable: true
  16618. });
  16619. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16620. set: function (callback) {
  16621. if (this._onAfterCameraRenderObserver) {
  16622. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16623. }
  16624. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16625. },
  16626. enumerable: true,
  16627. configurable: true
  16628. });
  16629. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16630. get: function () {
  16631. if (!this._gamepadManager) {
  16632. this._gamepadManager = new BABYLON.GamepadManager();
  16633. }
  16634. return this._gamepadManager;
  16635. },
  16636. enumerable: true,
  16637. configurable: true
  16638. });
  16639. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16640. get: function () {
  16641. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16642. },
  16643. enumerable: true,
  16644. configurable: true
  16645. });
  16646. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16647. get: function () {
  16648. return this._useRightHandedSystem;
  16649. },
  16650. set: function (value) {
  16651. if (this._useRightHandedSystem === value) {
  16652. return;
  16653. }
  16654. this._useRightHandedSystem = value;
  16655. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16656. },
  16657. enumerable: true,
  16658. configurable: true
  16659. });
  16660. Scene.prototype.setStepId = function (newStepId) {
  16661. this._currentStepId = newStepId;
  16662. };
  16663. ;
  16664. Scene.prototype.getStepId = function () {
  16665. return this._currentStepId;
  16666. };
  16667. ;
  16668. Scene.prototype.getInternalStep = function () {
  16669. return this._currentInternalStep;
  16670. };
  16671. ;
  16672. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16673. get: function () {
  16674. return this._fogEnabled;
  16675. },
  16676. /**
  16677. * is fog enabled on this scene.
  16678. */
  16679. set: function (value) {
  16680. if (this._fogEnabled === value) {
  16681. return;
  16682. }
  16683. this._fogEnabled = value;
  16684. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16685. },
  16686. enumerable: true,
  16687. configurable: true
  16688. });
  16689. Object.defineProperty(Scene.prototype, "fogMode", {
  16690. get: function () {
  16691. return this._fogMode;
  16692. },
  16693. set: function (value) {
  16694. if (this._fogMode === value) {
  16695. return;
  16696. }
  16697. this._fogMode = value;
  16698. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16699. },
  16700. enumerable: true,
  16701. configurable: true
  16702. });
  16703. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16704. get: function () {
  16705. return this._shadowsEnabled;
  16706. },
  16707. set: function (value) {
  16708. if (this._shadowsEnabled === value) {
  16709. return;
  16710. }
  16711. this._shadowsEnabled = value;
  16712. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16713. },
  16714. enumerable: true,
  16715. configurable: true
  16716. });
  16717. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16718. get: function () {
  16719. return this._lightsEnabled;
  16720. },
  16721. set: function (value) {
  16722. if (this._lightsEnabled === value) {
  16723. return;
  16724. }
  16725. this._lightsEnabled = value;
  16726. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16727. },
  16728. enumerable: true,
  16729. configurable: true
  16730. });
  16731. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16732. /** The default material used on meshes when no material is affected */
  16733. get: function () {
  16734. if (!this._defaultMaterial) {
  16735. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16736. }
  16737. return this._defaultMaterial;
  16738. },
  16739. /** The default material used on meshes when no material is affected */
  16740. set: function (value) {
  16741. this._defaultMaterial = value;
  16742. },
  16743. enumerable: true,
  16744. configurable: true
  16745. });
  16746. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16747. get: function () {
  16748. return this._texturesEnabled;
  16749. },
  16750. set: function (value) {
  16751. if (this._texturesEnabled === value) {
  16752. return;
  16753. }
  16754. this._texturesEnabled = value;
  16755. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16756. },
  16757. enumerable: true,
  16758. configurable: true
  16759. });
  16760. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16761. get: function () {
  16762. return this._skeletonsEnabled;
  16763. },
  16764. set: function (value) {
  16765. if (this._skeletonsEnabled === value) {
  16766. return;
  16767. }
  16768. this._skeletonsEnabled = value;
  16769. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16770. },
  16771. enumerable: true,
  16772. configurable: true
  16773. });
  16774. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16775. get: function () {
  16776. if (!this._postProcessRenderPipelineManager) {
  16777. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16778. }
  16779. return this._postProcessRenderPipelineManager;
  16780. },
  16781. enumerable: true,
  16782. configurable: true
  16783. });
  16784. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16785. get: function () {
  16786. return this._frustumPlanes;
  16787. },
  16788. enumerable: true,
  16789. configurable: true
  16790. });
  16791. Object.defineProperty(Scene.prototype, "debugLayer", {
  16792. // Properties
  16793. get: function () {
  16794. if (!this._debugLayer) {
  16795. this._debugLayer = new BABYLON.DebugLayer(this);
  16796. }
  16797. return this._debugLayer;
  16798. },
  16799. enumerable: true,
  16800. configurable: true
  16801. });
  16802. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16803. get: function () {
  16804. return this._workerCollisions;
  16805. },
  16806. set: function (enabled) {
  16807. if (!BABYLON.CollisionCoordinatorLegacy) {
  16808. return;
  16809. }
  16810. enabled = (enabled && !!Worker);
  16811. this._workerCollisions = enabled;
  16812. if (this.collisionCoordinator) {
  16813. this.collisionCoordinator.destroy();
  16814. }
  16815. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16816. this.collisionCoordinator.init(this);
  16817. },
  16818. enumerable: true,
  16819. configurable: true
  16820. });
  16821. Object.defineProperty(Scene.prototype, "selectionOctree", {
  16822. get: function () {
  16823. return this._selectionOctree;
  16824. },
  16825. enumerable: true,
  16826. configurable: true
  16827. });
  16828. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16829. /**
  16830. * The mesh that is currently under the pointer.
  16831. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16832. */
  16833. get: function () {
  16834. return this._pointerOverMesh;
  16835. },
  16836. enumerable: true,
  16837. configurable: true
  16838. });
  16839. Object.defineProperty(Scene.prototype, "pointerX", {
  16840. /**
  16841. * Current on-screen X position of the pointer
  16842. * @return {number} X position of the pointer
  16843. */
  16844. get: function () {
  16845. return this._pointerX;
  16846. },
  16847. enumerable: true,
  16848. configurable: true
  16849. });
  16850. Object.defineProperty(Scene.prototype, "pointerY", {
  16851. /**
  16852. * Current on-screen Y position of the pointer
  16853. * @return {number} Y position of the pointer
  16854. */
  16855. get: function () {
  16856. return this._pointerY;
  16857. },
  16858. enumerable: true,
  16859. configurable: true
  16860. });
  16861. Scene.prototype.getCachedMaterial = function () {
  16862. return this._cachedMaterial;
  16863. };
  16864. Scene.prototype.getCachedEffect = function () {
  16865. return this._cachedEffect;
  16866. };
  16867. Scene.prototype.getCachedVisibility = function () {
  16868. return this._cachedVisibility;
  16869. };
  16870. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  16871. if (visibility === void 0) { visibility = 1; }
  16872. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16873. };
  16874. Scene.prototype.getBoundingBoxRenderer = function () {
  16875. if (!this._boundingBoxRenderer) {
  16876. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16877. }
  16878. return this._boundingBoxRenderer;
  16879. };
  16880. Scene.prototype.getOutlineRenderer = function () {
  16881. return this._outlineRenderer;
  16882. };
  16883. Scene.prototype.getEngine = function () {
  16884. return this._engine;
  16885. };
  16886. Scene.prototype.getTotalVertices = function () {
  16887. return this._totalVertices.current;
  16888. };
  16889. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16890. get: function () {
  16891. return this._totalVertices;
  16892. },
  16893. enumerable: true,
  16894. configurable: true
  16895. });
  16896. Scene.prototype.getActiveIndices = function () {
  16897. return this._activeIndices.current;
  16898. };
  16899. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16900. get: function () {
  16901. return this._activeIndices;
  16902. },
  16903. enumerable: true,
  16904. configurable: true
  16905. });
  16906. Scene.prototype.getActiveParticles = function () {
  16907. return this._activeParticles.current;
  16908. };
  16909. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16910. get: function () {
  16911. return this._activeParticles;
  16912. },
  16913. enumerable: true,
  16914. configurable: true
  16915. });
  16916. Scene.prototype.getActiveBones = function () {
  16917. return this._activeBones.current;
  16918. };
  16919. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16920. get: function () {
  16921. return this._activeBones;
  16922. },
  16923. enumerable: true,
  16924. configurable: true
  16925. });
  16926. // Stats
  16927. Scene.prototype.getLastFrameDuration = function () {
  16928. return this._lastFrameDuration.current;
  16929. };
  16930. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16931. get: function () {
  16932. return this._lastFrameDuration;
  16933. },
  16934. enumerable: true,
  16935. configurable: true
  16936. });
  16937. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16938. return this._evaluateActiveMeshesDuration.current;
  16939. };
  16940. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16941. get: function () {
  16942. return this._evaluateActiveMeshesDuration;
  16943. },
  16944. enumerable: true,
  16945. configurable: true
  16946. });
  16947. Scene.prototype.getActiveMeshes = function () {
  16948. return this._activeMeshes;
  16949. };
  16950. Scene.prototype.getRenderTargetsDuration = function () {
  16951. return this._renderTargetsDuration.current;
  16952. };
  16953. Scene.prototype.getRenderDuration = function () {
  16954. return this._renderDuration.current;
  16955. };
  16956. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16957. get: function () {
  16958. return this._renderDuration;
  16959. },
  16960. enumerable: true,
  16961. configurable: true
  16962. });
  16963. Scene.prototype.getParticlesDuration = function () {
  16964. return this._particlesDuration.current;
  16965. };
  16966. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16967. get: function () {
  16968. return this._particlesDuration;
  16969. },
  16970. enumerable: true,
  16971. configurable: true
  16972. });
  16973. Scene.prototype.getSpritesDuration = function () {
  16974. return this._spritesDuration.current;
  16975. };
  16976. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16977. get: function () {
  16978. return this._spritesDuration;
  16979. },
  16980. enumerable: true,
  16981. configurable: true
  16982. });
  16983. Scene.prototype.getAnimationRatio = function () {
  16984. return this._animationRatio;
  16985. };
  16986. Scene.prototype.getRenderId = function () {
  16987. return this._renderId;
  16988. };
  16989. Scene.prototype.incrementRenderId = function () {
  16990. this._renderId++;
  16991. };
  16992. Scene.prototype._updatePointerPosition = function (evt) {
  16993. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16994. this._pointerX = evt.clientX - canvasRect.left;
  16995. this._pointerY = evt.clientY - canvasRect.top;
  16996. this._unTranslatedPointerX = this._pointerX;
  16997. this._unTranslatedPointerY = this._pointerY;
  16998. };
  16999. Scene.prototype._createUbo = function () {
  17000. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17001. this._sceneUbo.addUniform("viewProjection", 16);
  17002. this._sceneUbo.addUniform("view", 16);
  17003. };
  17004. // Pointers handling
  17005. /**
  17006. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17007. * @param attachUp defines if you want to attach events to pointerup
  17008. * @param attachDown defines if you want to attach events to pointerdown
  17009. * @param attachMove defines if you want to attach events to pointermove
  17010. */
  17011. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17012. var _this = this;
  17013. if (attachUp === void 0) { attachUp = true; }
  17014. if (attachDown === void 0) { attachDown = true; }
  17015. if (attachMove === void 0) { attachMove = true; }
  17016. this._initActionManager = function (act, clickInfo) {
  17017. if (!_this._meshPickProceed) {
  17018. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17019. _this._currentPickResult = pickResult;
  17020. if (pickResult) {
  17021. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17022. }
  17023. _this._meshPickProceed = true;
  17024. }
  17025. return act;
  17026. };
  17027. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17028. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17029. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17030. btn !== _this._previousButtonPressed) {
  17031. _this._doubleClickOccured = false;
  17032. clickInfo.singleClick = true;
  17033. clickInfo.ignore = false;
  17034. cb(clickInfo, _this._currentPickResult);
  17035. }
  17036. };
  17037. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17038. var clickInfo = new ClickInfo();
  17039. _this._currentPickResult = null;
  17040. var act;
  17041. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  17042. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  17043. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17044. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17045. act = _this._initActionManager(act, clickInfo);
  17046. if (act)
  17047. checkPicking = act.hasPickTriggers;
  17048. }
  17049. if (checkPicking) {
  17050. var btn = evt.button;
  17051. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17052. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17053. if (!clickInfo.hasSwiped) {
  17054. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17055. if (!checkSingleClickImmediately) {
  17056. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  17057. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17058. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17059. act = _this._initActionManager(act, clickInfo);
  17060. if (act)
  17061. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17062. }
  17063. }
  17064. if (checkSingleClickImmediately) {
  17065. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17066. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17067. btn !== _this._previousButtonPressed) {
  17068. clickInfo.singleClick = true;
  17069. cb(clickInfo, _this._currentPickResult);
  17070. }
  17071. }
  17072. else {
  17073. // wait that no double click has been raised during the double click delay
  17074. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17075. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17076. }
  17077. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  17078. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17079. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17080. act = _this._initActionManager(act, clickInfo);
  17081. if (act)
  17082. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17083. }
  17084. if (checkDoubleClick) {
  17085. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17086. if (btn === _this._previousButtonPressed &&
  17087. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17088. !_this._doubleClickOccured) {
  17089. // pointer has not moved for 2 clicks, it's a double click
  17090. if (!clickInfo.hasSwiped &&
  17091. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17092. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17093. _this._previousStartingPointerTime = 0;
  17094. _this._doubleClickOccured = true;
  17095. clickInfo.doubleClick = true;
  17096. clickInfo.ignore = false;
  17097. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17098. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17099. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17100. cb(clickInfo, _this._currentPickResult);
  17101. }
  17102. else {
  17103. _this._doubleClickOccured = false;
  17104. _this._previousStartingPointerTime = _this._startingPointerTime;
  17105. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17106. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17107. _this._previousButtonPressed = btn;
  17108. _this._previousHasSwiped = clickInfo.hasSwiped;
  17109. if (Scene.ExclusiveDoubleClickMode) {
  17110. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17111. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17112. }
  17113. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17114. cb(clickInfo, _this._previousPickResult);
  17115. }
  17116. else {
  17117. cb(clickInfo, _this._currentPickResult);
  17118. }
  17119. }
  17120. }
  17121. else {
  17122. _this._doubleClickOccured = false;
  17123. _this._previousStartingPointerTime = _this._startingPointerTime;
  17124. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17125. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17126. _this._previousButtonPressed = btn;
  17127. _this._previousHasSwiped = clickInfo.hasSwiped;
  17128. }
  17129. }
  17130. }
  17131. }
  17132. clickInfo.ignore = true;
  17133. cb(clickInfo, _this._currentPickResult);
  17134. };
  17135. var spritePredicate = function (sprite) {
  17136. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17137. };
  17138. this._onPointerMove = function (evt) {
  17139. _this._updatePointerPosition(evt);
  17140. // PreObservable support
  17141. if (_this.onPrePointerObservable.hasObservers()) {
  17142. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17143. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17144. _this.onPrePointerObservable.notifyObservers(pi, type);
  17145. if (pi.skipOnPointerObservable) {
  17146. return;
  17147. }
  17148. }
  17149. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17150. return;
  17151. }
  17152. var canvas = _this._engine.getRenderingCanvas();
  17153. if (!_this.pointerMovePredicate) {
  17154. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17155. }
  17156. // Meshes
  17157. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17158. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17159. _this.setPointerOverSprite(null);
  17160. _this.setPointerOverMesh(pickResult.pickedMesh);
  17161. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17162. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17163. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17164. }
  17165. else {
  17166. canvas.style.cursor = _this.hoverCursor;
  17167. }
  17168. }
  17169. else {
  17170. canvas.style.cursor = _this.defaultCursor;
  17171. }
  17172. }
  17173. else {
  17174. _this.setPointerOverMesh(null);
  17175. // Sprites
  17176. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17177. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17178. _this.setPointerOverSprite(pickResult.pickedSprite);
  17179. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17180. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17181. }
  17182. else {
  17183. canvas.style.cursor = _this.hoverCursor;
  17184. }
  17185. }
  17186. else {
  17187. _this.setPointerOverSprite(null);
  17188. // Restore pointer
  17189. canvas.style.cursor = _this.defaultCursor;
  17190. }
  17191. }
  17192. if (_this.onPointerMove) {
  17193. _this.onPointerMove(evt, pickResult);
  17194. }
  17195. if (_this.onPointerObservable.hasObservers()) {
  17196. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17197. var pi = new PointerInfo(type, evt, pickResult);
  17198. _this.onPointerObservable.notifyObservers(pi, type);
  17199. }
  17200. };
  17201. this._onPointerDown = function (evt) {
  17202. _this._isButtonPressed = true;
  17203. _this._pickedDownMesh = null;
  17204. _this._meshPickProceed = false;
  17205. _this._updatePointerPosition(evt);
  17206. // PreObservable support
  17207. if (_this.onPrePointerObservable.hasObservers()) {
  17208. var type = PointerEventTypes.POINTERDOWN;
  17209. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17210. _this.onPrePointerObservable.notifyObservers(pi, type);
  17211. if (pi.skipOnPointerObservable) {
  17212. return;
  17213. }
  17214. }
  17215. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17216. return;
  17217. }
  17218. _this._startingPointerPosition.x = _this._pointerX;
  17219. _this._startingPointerPosition.y = _this._pointerY;
  17220. _this._startingPointerTime = new Date().getTime();
  17221. if (!_this.pointerDownPredicate) {
  17222. _this.pointerDownPredicate = function (mesh) {
  17223. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17224. };
  17225. }
  17226. // Meshes
  17227. _this._pickedDownMesh = null;
  17228. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17229. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17230. _this._pickedDownMesh = pickResult.pickedMesh;
  17231. var actionManager = pickResult.pickedMesh.actionManager;
  17232. if (actionManager) {
  17233. if (actionManager.hasPickTriggers) {
  17234. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17235. switch (evt.button) {
  17236. case 0:
  17237. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17238. break;
  17239. case 1:
  17240. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17241. break;
  17242. case 2:
  17243. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17244. break;
  17245. }
  17246. }
  17247. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17248. window.setTimeout((function () {
  17249. var _this = this;
  17250. 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);
  17251. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17252. if (this._isButtonPressed &&
  17253. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17254. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17255. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17256. this._startingPointerTime = 0;
  17257. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17258. }
  17259. }
  17260. }).bind(_this), Scene.LongPressDelay);
  17261. }
  17262. }
  17263. }
  17264. if (_this.onPointerDown) {
  17265. _this.onPointerDown(evt, pickResult);
  17266. }
  17267. if (_this.onPointerObservable.hasObservers()) {
  17268. var type = PointerEventTypes.POINTERDOWN;
  17269. var pi = new PointerInfo(type, evt, pickResult);
  17270. _this.onPointerObservable.notifyObservers(pi, type);
  17271. }
  17272. // Sprites
  17273. _this._pickedDownSprite = null;
  17274. if (_this.spriteManagers.length > 0) {
  17275. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17276. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17277. if (pickResult.pickedSprite.actionManager) {
  17278. _this._pickedDownSprite = pickResult.pickedSprite;
  17279. switch (evt.button) {
  17280. case 0:
  17281. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17282. break;
  17283. case 1:
  17284. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17285. break;
  17286. case 2:
  17287. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17288. break;
  17289. }
  17290. if (pickResult.pickedSprite.actionManager) {
  17291. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17292. }
  17293. }
  17294. }
  17295. }
  17296. };
  17297. this._onPointerUp = function (evt) {
  17298. _this._isButtonPressed = false;
  17299. _this._pickedUpMesh = null;
  17300. _this._meshPickProceed = false;
  17301. _this._updatePointerPosition(evt);
  17302. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17303. // PreObservable support
  17304. if (this.onPrePointerObservable.hasObservers()) {
  17305. if (!clickInfo.ignore) {
  17306. if (!clickInfo.hasSwiped) {
  17307. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17308. var type = PointerEventTypes.POINTERTAP;
  17309. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17310. this.onPrePointerObservable.notifyObservers(pi, type);
  17311. if (pi.skipOnPointerObservable) {
  17312. return;
  17313. }
  17314. }
  17315. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17316. var type = PointerEventTypes.POINTERDOUBLETAP;
  17317. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17318. this.onPrePointerObservable.notifyObservers(pi, type);
  17319. if (pi.skipOnPointerObservable) {
  17320. return;
  17321. }
  17322. }
  17323. }
  17324. }
  17325. else {
  17326. var type = PointerEventTypes.POINTERUP;
  17327. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17328. this.onPrePointerObservable.notifyObservers(pi, type);
  17329. if (pi.skipOnPointerObservable) {
  17330. return;
  17331. }
  17332. }
  17333. }
  17334. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17335. return;
  17336. }
  17337. if (!this.pointerUpPredicate) {
  17338. this.pointerUpPredicate = function (mesh) {
  17339. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17340. };
  17341. }
  17342. // Meshes
  17343. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17344. this._initActionManager(null, clickInfo);
  17345. }
  17346. if (!pickResult) {
  17347. pickResult = this._currentPickResult;
  17348. }
  17349. if (pickResult && pickResult && pickResult.pickedMesh) {
  17350. this._pickedUpMesh = pickResult.pickedMesh;
  17351. if (this._pickedDownMesh === this._pickedUpMesh) {
  17352. if (this.onPointerPick) {
  17353. this.onPointerPick(evt, pickResult);
  17354. }
  17355. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17356. var type = PointerEventTypes.POINTERPICK;
  17357. var pi = new PointerInfo(type, evt, pickResult);
  17358. this.onPointerObservable.notifyObservers(pi, type);
  17359. }
  17360. }
  17361. if (pickResult.pickedMesh.actionManager) {
  17362. if (clickInfo.ignore) {
  17363. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17364. }
  17365. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17366. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17367. }
  17368. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17369. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17370. }
  17371. }
  17372. }
  17373. if (this._pickedDownMesh &&
  17374. this._pickedDownMesh.actionManager &&
  17375. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17376. this._pickedDownMesh !== this._pickedUpMesh) {
  17377. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17378. }
  17379. if (this.onPointerUp) {
  17380. this.onPointerUp(evt, pickResult);
  17381. }
  17382. if (this.onPointerObservable.hasObservers()) {
  17383. if (!clickInfo.ignore) {
  17384. if (!clickInfo.hasSwiped) {
  17385. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17386. var type = PointerEventTypes.POINTERTAP;
  17387. var pi = new PointerInfo(type, evt, pickResult);
  17388. this.onPointerObservable.notifyObservers(pi, type);
  17389. }
  17390. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17391. var type = PointerEventTypes.POINTERDOUBLETAP;
  17392. var pi = new PointerInfo(type, evt, pickResult);
  17393. this.onPointerObservable.notifyObservers(pi, type);
  17394. }
  17395. }
  17396. }
  17397. else {
  17398. var type = PointerEventTypes.POINTERUP;
  17399. var pi = new PointerInfo(type, evt, pickResult);
  17400. this.onPointerObservable.notifyObservers(pi, type);
  17401. }
  17402. }
  17403. // Sprites
  17404. if (this.spriteManagers.length > 0) {
  17405. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  17406. if (pickResult.hit && pickResult.pickedSprite) {
  17407. if (pickResult.pickedSprite.actionManager) {
  17408. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17409. if (pickResult.pickedSprite.actionManager) {
  17410. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17411. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17412. }
  17413. }
  17414. }
  17415. }
  17416. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17417. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17418. }
  17419. }
  17420. this._previousPickResult = this._currentPickResult;
  17421. }).bind(_this));
  17422. };
  17423. this._onKeyDown = function (evt) {
  17424. if (_this.actionManager) {
  17425. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17426. }
  17427. };
  17428. this._onKeyUp = function (evt) {
  17429. if (_this.actionManager) {
  17430. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17431. }
  17432. };
  17433. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17434. var canvas = this._engine.getRenderingCanvas();
  17435. if (attachMove) {
  17436. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17437. // Wheel
  17438. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17439. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17440. }
  17441. if (attachDown) {
  17442. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17443. }
  17444. if (attachUp) {
  17445. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17446. }
  17447. canvas.tabIndex = 1;
  17448. canvas.addEventListener("keydown", this._onKeyDown, false);
  17449. canvas.addEventListener("keyup", this._onKeyUp, false);
  17450. };
  17451. Scene.prototype.detachControl = function () {
  17452. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17453. var canvas = this._engine.getRenderingCanvas();
  17454. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17455. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17456. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17457. // Wheel
  17458. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17459. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17460. canvas.removeEventListener("keydown", this._onKeyDown);
  17461. canvas.removeEventListener("keyup", this._onKeyUp);
  17462. };
  17463. // Ready
  17464. Scene.prototype.isReady = function () {
  17465. if (this._pendingData.length > 0) {
  17466. return false;
  17467. }
  17468. var index;
  17469. // Geometries
  17470. for (index = 0; index < this._geometries.length; index++) {
  17471. var geometry = this._geometries[index];
  17472. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17473. return false;
  17474. }
  17475. }
  17476. // Meshes
  17477. for (index = 0; index < this.meshes.length; index++) {
  17478. var mesh = this.meshes[index];
  17479. if (!mesh.isEnabled()) {
  17480. continue;
  17481. }
  17482. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17483. continue;
  17484. }
  17485. if (!mesh.isReady()) {
  17486. return false;
  17487. }
  17488. var mat = mesh.material;
  17489. if (mat) {
  17490. if (!mat.isReady(mesh)) {
  17491. return false;
  17492. }
  17493. }
  17494. }
  17495. return true;
  17496. };
  17497. Scene.prototype.resetCachedMaterial = function () {
  17498. this._cachedMaterial = null;
  17499. this._cachedEffect = null;
  17500. this._cachedVisibility = null;
  17501. };
  17502. Scene.prototype.registerBeforeRender = function (func) {
  17503. this.onBeforeRenderObservable.add(func);
  17504. };
  17505. Scene.prototype.unregisterBeforeRender = function (func) {
  17506. this.onBeforeRenderObservable.removeCallback(func);
  17507. };
  17508. Scene.prototype.registerAfterRender = function (func) {
  17509. this.onAfterRenderObservable.add(func);
  17510. };
  17511. Scene.prototype.unregisterAfterRender = function (func) {
  17512. this.onAfterRenderObservable.removeCallback(func);
  17513. };
  17514. Scene.prototype._addPendingData = function (data) {
  17515. this._pendingData.push(data);
  17516. };
  17517. Scene.prototype._removePendingData = function (data) {
  17518. var index = this._pendingData.indexOf(data);
  17519. if (index !== -1) {
  17520. this._pendingData.splice(index, 1);
  17521. }
  17522. };
  17523. Scene.prototype.getWaitingItemsCount = function () {
  17524. return this._pendingData.length;
  17525. };
  17526. /**
  17527. * Registers a function to be executed when the scene is ready.
  17528. * @param {Function} func - the function to be executed.
  17529. */
  17530. Scene.prototype.executeWhenReady = function (func) {
  17531. var _this = this;
  17532. this.onReadyObservable.add(func);
  17533. if (this._executeWhenReadyTimeoutId !== -1) {
  17534. return;
  17535. }
  17536. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17537. _this._checkIsReady();
  17538. }, 150);
  17539. };
  17540. Scene.prototype._checkIsReady = function () {
  17541. var _this = this;
  17542. if (this.isReady()) {
  17543. this.onReadyObservable.notifyObservers(this);
  17544. this.onReadyObservable.clear();
  17545. this._executeWhenReadyTimeoutId = -1;
  17546. return;
  17547. }
  17548. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17549. _this._checkIsReady();
  17550. }, 150);
  17551. };
  17552. // Animations
  17553. /**
  17554. * Will start the animation sequence of a given target
  17555. * @param target - the target
  17556. * @param {number} from - from which frame should animation start
  17557. * @param {number} to - till which frame should animation run.
  17558. * @param {boolean} [loop] - should the animation loop
  17559. * @param {number} [speedRatio] - the speed in which to run the animation
  17560. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17561. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17562. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17563. * See BABYLON.Animatable
  17564. */
  17565. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17566. if (speedRatio === void 0) { speedRatio = 1.0; }
  17567. if (from > to && speedRatio > 0) {
  17568. speedRatio *= -1;
  17569. }
  17570. this.stopAnimation(target);
  17571. if (!animatable) {
  17572. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17573. }
  17574. // Local animations
  17575. if (target.animations) {
  17576. animatable.appendAnimations(target, target.animations);
  17577. }
  17578. // Children animations
  17579. if (target.getAnimatables) {
  17580. var animatables = target.getAnimatables();
  17581. for (var index = 0; index < animatables.length; index++) {
  17582. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17583. }
  17584. }
  17585. animatable.reset();
  17586. return animatable;
  17587. };
  17588. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17589. if (speedRatio === undefined) {
  17590. speedRatio = 1.0;
  17591. }
  17592. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17593. return animatable;
  17594. };
  17595. Scene.prototype.getAnimatableByTarget = function (target) {
  17596. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17597. if (this._activeAnimatables[index].target === target) {
  17598. return this._activeAnimatables[index];
  17599. }
  17600. }
  17601. return null;
  17602. };
  17603. Object.defineProperty(Scene.prototype, "Animatables", {
  17604. get: function () {
  17605. return this._activeAnimatables;
  17606. },
  17607. enumerable: true,
  17608. configurable: true
  17609. });
  17610. /**
  17611. * Will stop the animation of the given target
  17612. * @param target - the target
  17613. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17614. * @see beginAnimation
  17615. */
  17616. Scene.prototype.stopAnimation = function (target, animationName) {
  17617. var animatable = this.getAnimatableByTarget(target);
  17618. if (animatable) {
  17619. animatable.stop(animationName);
  17620. }
  17621. };
  17622. Scene.prototype._animate = function () {
  17623. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17624. return;
  17625. }
  17626. // Getting time
  17627. var now = BABYLON.Tools.Now;
  17628. if (!this._animationTimeLast) {
  17629. if (this._pendingData.length > 0) {
  17630. return;
  17631. }
  17632. this._animationTimeLast = now;
  17633. }
  17634. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17635. this._animationTime += deltaTime;
  17636. this._animationTimeLast = now;
  17637. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17638. this._activeAnimatables[index]._animate(this._animationTime);
  17639. }
  17640. };
  17641. // Matrix
  17642. Scene.prototype.getViewMatrix = function () {
  17643. return this._viewMatrix;
  17644. };
  17645. Scene.prototype.getProjectionMatrix = function () {
  17646. return this._projectionMatrix;
  17647. };
  17648. Scene.prototype.getTransformMatrix = function () {
  17649. return this._transformMatrix;
  17650. };
  17651. Scene.prototype.setTransformMatrix = function (view, projection) {
  17652. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17653. return;
  17654. }
  17655. this._viewUpdateFlag = view.updateFlag;
  17656. this._projectionUpdateFlag = projection.updateFlag;
  17657. this._viewMatrix = view;
  17658. this._projectionMatrix = projection;
  17659. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17660. // Update frustum
  17661. if (!this._frustumPlanes) {
  17662. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17663. }
  17664. else {
  17665. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17666. }
  17667. if (this._sceneUbo.useUbo) {
  17668. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17669. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17670. this._sceneUbo.update();
  17671. }
  17672. };
  17673. Scene.prototype.getSceneUniformBuffer = function () {
  17674. return this._sceneUbo;
  17675. };
  17676. // Methods
  17677. Scene.prototype.getUniqueId = function () {
  17678. var result = this._uniqueIdCounter;
  17679. this._uniqueIdCounter++;
  17680. return result;
  17681. };
  17682. Scene.prototype.addMesh = function (newMesh) {
  17683. newMesh.uniqueId = this.getUniqueId();
  17684. var position = this.meshes.push(newMesh);
  17685. //notify the collision coordinator
  17686. if (this.collisionCoordinator) {
  17687. this.collisionCoordinator.onMeshAdded(newMesh);
  17688. }
  17689. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17690. };
  17691. Scene.prototype.removeMesh = function (toRemove) {
  17692. var index = this.meshes.indexOf(toRemove);
  17693. if (index !== -1) {
  17694. // Remove from the scene if mesh found
  17695. this.meshes.splice(index, 1);
  17696. }
  17697. //notify the collision coordinator
  17698. if (this.collisionCoordinator) {
  17699. this.collisionCoordinator.onMeshRemoved(toRemove);
  17700. }
  17701. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17702. return index;
  17703. };
  17704. Scene.prototype.removeSkeleton = function (toRemove) {
  17705. var index = this.skeletons.indexOf(toRemove);
  17706. if (index !== -1) {
  17707. // Remove from the scene if found
  17708. this.skeletons.splice(index, 1);
  17709. }
  17710. return index;
  17711. };
  17712. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17713. var index = this.morphTargetManagers.indexOf(toRemove);
  17714. if (index !== -1) {
  17715. // Remove from the scene if found
  17716. this.morphTargetManagers.splice(index, 1);
  17717. }
  17718. return index;
  17719. };
  17720. Scene.prototype.removeLight = function (toRemove) {
  17721. var index = this.lights.indexOf(toRemove);
  17722. if (index !== -1) {
  17723. // Remove from the scene if mesh found
  17724. this.lights.splice(index, 1);
  17725. this.sortLightsByPriority();
  17726. }
  17727. this.onLightRemovedObservable.notifyObservers(toRemove);
  17728. return index;
  17729. };
  17730. Scene.prototype.removeCamera = function (toRemove) {
  17731. var index = this.cameras.indexOf(toRemove);
  17732. if (index !== -1) {
  17733. // Remove from the scene if mesh found
  17734. this.cameras.splice(index, 1);
  17735. }
  17736. // Remove from activeCameras
  17737. var index2 = this.activeCameras.indexOf(toRemove);
  17738. if (index2 !== -1) {
  17739. // Remove from the scene if mesh found
  17740. this.activeCameras.splice(index2, 1);
  17741. }
  17742. // Reset the activeCamera
  17743. if (this.activeCamera === toRemove) {
  17744. if (this.cameras.length > 0) {
  17745. this.activeCamera = this.cameras[0];
  17746. }
  17747. else {
  17748. this.activeCamera = null;
  17749. }
  17750. }
  17751. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17752. return index;
  17753. };
  17754. Scene.prototype.addLight = function (newLight) {
  17755. newLight.uniqueId = this.getUniqueId();
  17756. this.lights.push(newLight);
  17757. this.sortLightsByPriority();
  17758. this.onNewLightAddedObservable.notifyObservers(newLight);
  17759. };
  17760. Scene.prototype.sortLightsByPriority = function () {
  17761. if (this.requireLightSorting) {
  17762. this.lights.sort(BABYLON.Light.compareLightsPriority);
  17763. }
  17764. };
  17765. Scene.prototype.addCamera = function (newCamera) {
  17766. newCamera.uniqueId = this.getUniqueId();
  17767. var position = this.cameras.push(newCamera);
  17768. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17769. };
  17770. /**
  17771. * Switch active camera
  17772. * @param {Camera} newCamera - new active camera
  17773. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17774. */
  17775. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17776. if (attachControl === void 0) { attachControl = true; }
  17777. var canvas = this._engine.getRenderingCanvas();
  17778. this.activeCamera.detachControl(canvas);
  17779. this.activeCamera = newCamera;
  17780. if (attachControl) {
  17781. newCamera.attachControl(canvas);
  17782. }
  17783. };
  17784. /**
  17785. * sets the active camera of the scene using its ID
  17786. * @param {string} id - the camera's ID
  17787. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17788. * @see activeCamera
  17789. */
  17790. Scene.prototype.setActiveCameraByID = function (id) {
  17791. var camera = this.getCameraByID(id);
  17792. if (camera) {
  17793. this.activeCamera = camera;
  17794. return camera;
  17795. }
  17796. return null;
  17797. };
  17798. /**
  17799. * sets the active camera of the scene using its name
  17800. * @param {string} name - the camera's name
  17801. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17802. * @see activeCamera
  17803. */
  17804. Scene.prototype.setActiveCameraByName = function (name) {
  17805. var camera = this.getCameraByName(name);
  17806. if (camera) {
  17807. this.activeCamera = camera;
  17808. return camera;
  17809. }
  17810. return null;
  17811. };
  17812. /**
  17813. * get a material using its id
  17814. * @param {string} the material's ID
  17815. * @return {BABYLON.Material|null} the material or null if none found.
  17816. */
  17817. Scene.prototype.getMaterialByID = function (id) {
  17818. for (var index = 0; index < this.materials.length; index++) {
  17819. if (this.materials[index].id === id) {
  17820. return this.materials[index];
  17821. }
  17822. }
  17823. return null;
  17824. };
  17825. /**
  17826. * get a material using its name
  17827. * @param {string} the material's name
  17828. * @return {BABYLON.Material|null} the material or null if none found.
  17829. */
  17830. Scene.prototype.getMaterialByName = function (name) {
  17831. for (var index = 0; index < this.materials.length; index++) {
  17832. if (this.materials[index].name === name) {
  17833. return this.materials[index];
  17834. }
  17835. }
  17836. return null;
  17837. };
  17838. Scene.prototype.getLensFlareSystemByName = function (name) {
  17839. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17840. if (this.lensFlareSystems[index].name === name) {
  17841. return this.lensFlareSystems[index];
  17842. }
  17843. }
  17844. return null;
  17845. };
  17846. Scene.prototype.getLensFlareSystemByID = function (id) {
  17847. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17848. if (this.lensFlareSystems[index].id === id) {
  17849. return this.lensFlareSystems[index];
  17850. }
  17851. }
  17852. return null;
  17853. };
  17854. Scene.prototype.getCameraByID = function (id) {
  17855. for (var index = 0; index < this.cameras.length; index++) {
  17856. if (this.cameras[index].id === id) {
  17857. return this.cameras[index];
  17858. }
  17859. }
  17860. return null;
  17861. };
  17862. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17863. for (var index = 0; index < this.cameras.length; index++) {
  17864. if (this.cameras[index].uniqueId === uniqueId) {
  17865. return this.cameras[index];
  17866. }
  17867. }
  17868. return null;
  17869. };
  17870. /**
  17871. * get a camera using its name
  17872. * @param {string} the camera's name
  17873. * @return {BABYLON.Camera|null} the camera or null if none found.
  17874. */
  17875. Scene.prototype.getCameraByName = function (name) {
  17876. for (var index = 0; index < this.cameras.length; index++) {
  17877. if (this.cameras[index].name === name) {
  17878. return this.cameras[index];
  17879. }
  17880. }
  17881. return null;
  17882. };
  17883. /**
  17884. * get a bone using its id
  17885. * @param {string} the bone's id
  17886. * @return {BABYLON.Bone|null} the bone or null if not found
  17887. */
  17888. Scene.prototype.getBoneByID = function (id) {
  17889. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17890. var skeleton = this.skeletons[skeletonIndex];
  17891. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17892. if (skeleton.bones[boneIndex].id === id) {
  17893. return skeleton.bones[boneIndex];
  17894. }
  17895. }
  17896. }
  17897. return null;
  17898. };
  17899. /**
  17900. * get a bone using its id
  17901. * @param {string} the bone's name
  17902. * @return {BABYLON.Bone|null} the bone or null if not found
  17903. */
  17904. Scene.prototype.getBoneByName = function (name) {
  17905. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17906. var skeleton = this.skeletons[skeletonIndex];
  17907. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17908. if (skeleton.bones[boneIndex].name === name) {
  17909. return skeleton.bones[boneIndex];
  17910. }
  17911. }
  17912. }
  17913. return null;
  17914. };
  17915. /**
  17916. * get a light node using its name
  17917. * @param {string} the light's name
  17918. * @return {BABYLON.Light|null} the light or null if none found.
  17919. */
  17920. Scene.prototype.getLightByName = function (name) {
  17921. for (var index = 0; index < this.lights.length; index++) {
  17922. if (this.lights[index].name === name) {
  17923. return this.lights[index];
  17924. }
  17925. }
  17926. return null;
  17927. };
  17928. /**
  17929. * get a light node using its ID
  17930. * @param {string} the light's id
  17931. * @return {BABYLON.Light|null} the light or null if none found.
  17932. */
  17933. Scene.prototype.getLightByID = function (id) {
  17934. for (var index = 0; index < this.lights.length; index++) {
  17935. if (this.lights[index].id === id) {
  17936. return this.lights[index];
  17937. }
  17938. }
  17939. return null;
  17940. };
  17941. /**
  17942. * get a light node using its scene-generated unique ID
  17943. * @param {number} the light's unique id
  17944. * @return {BABYLON.Light|null} the light or null if none found.
  17945. */
  17946. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17947. for (var index = 0; index < this.lights.length; index++) {
  17948. if (this.lights[index].uniqueId === uniqueId) {
  17949. return this.lights[index];
  17950. }
  17951. }
  17952. return null;
  17953. };
  17954. /**
  17955. * get a particle system by id
  17956. * @param id {number} the particle system id
  17957. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  17958. */
  17959. Scene.prototype.getParticleSystemByID = function (id) {
  17960. for (var index = 0; index < this.particleSystems.length; index++) {
  17961. if (this.particleSystems[index].id === id) {
  17962. return this.particleSystems[index];
  17963. }
  17964. }
  17965. return null;
  17966. };
  17967. /**
  17968. * get a geometry using its ID
  17969. * @param {string} the geometry's id
  17970. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17971. */
  17972. Scene.prototype.getGeometryByID = function (id) {
  17973. for (var index = 0; index < this._geometries.length; index++) {
  17974. if (this._geometries[index].id === id) {
  17975. return this._geometries[index];
  17976. }
  17977. }
  17978. return null;
  17979. };
  17980. /**
  17981. * add a new geometry to this scene.
  17982. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17983. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17984. * @return {boolean} was the geometry added or not
  17985. */
  17986. Scene.prototype.pushGeometry = function (geometry, force) {
  17987. if (!force && this.getGeometryByID(geometry.id)) {
  17988. return false;
  17989. }
  17990. this._geometries.push(geometry);
  17991. //notify the collision coordinator
  17992. if (this.collisionCoordinator) {
  17993. this.collisionCoordinator.onGeometryAdded(geometry);
  17994. }
  17995. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17996. return true;
  17997. };
  17998. /**
  17999. * Removes an existing geometry
  18000. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18001. * @return {boolean} was the geometry removed or not
  18002. */
  18003. Scene.prototype.removeGeometry = function (geometry) {
  18004. var index = this._geometries.indexOf(geometry);
  18005. if (index > -1) {
  18006. this._geometries.splice(index, 1);
  18007. //notify the collision coordinator
  18008. if (this.collisionCoordinator) {
  18009. this.collisionCoordinator.onGeometryDeleted(geometry);
  18010. }
  18011. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18012. return true;
  18013. }
  18014. return false;
  18015. };
  18016. Scene.prototype.getGeometries = function () {
  18017. return this._geometries;
  18018. };
  18019. /**
  18020. * Get the first added mesh found of a given ID
  18021. * @param {string} id - the id to search for
  18022. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18023. */
  18024. Scene.prototype.getMeshByID = function (id) {
  18025. for (var index = 0; index < this.meshes.length; index++) {
  18026. if (this.meshes[index].id === id) {
  18027. return this.meshes[index];
  18028. }
  18029. }
  18030. return null;
  18031. };
  18032. Scene.prototype.getMeshesByID = function (id) {
  18033. return this.meshes.filter(function (m) {
  18034. return m.id === id;
  18035. });
  18036. };
  18037. /**
  18038. * Get a mesh with its auto-generated unique id
  18039. * @param {number} uniqueId - the unique id to search for
  18040. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18041. */
  18042. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18043. for (var index = 0; index < this.meshes.length; index++) {
  18044. if (this.meshes[index].uniqueId === uniqueId) {
  18045. return this.meshes[index];
  18046. }
  18047. }
  18048. return null;
  18049. };
  18050. /**
  18051. * Get a the last added mesh found of a given ID
  18052. * @param {string} id - the id to search for
  18053. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18054. */
  18055. Scene.prototype.getLastMeshByID = function (id) {
  18056. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18057. if (this.meshes[index].id === id) {
  18058. return this.meshes[index];
  18059. }
  18060. }
  18061. return null;
  18062. };
  18063. /**
  18064. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18065. * @param {string} id - the id to search for
  18066. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18067. */
  18068. Scene.prototype.getLastEntryByID = function (id) {
  18069. var index;
  18070. for (index = this.meshes.length - 1; index >= 0; index--) {
  18071. if (this.meshes[index].id === id) {
  18072. return this.meshes[index];
  18073. }
  18074. }
  18075. for (index = this.cameras.length - 1; index >= 0; index--) {
  18076. if (this.cameras[index].id === id) {
  18077. return this.cameras[index];
  18078. }
  18079. }
  18080. for (index = this.lights.length - 1; index >= 0; index--) {
  18081. if (this.lights[index].id === id) {
  18082. return this.lights[index];
  18083. }
  18084. }
  18085. return null;
  18086. };
  18087. Scene.prototype.getNodeByID = function (id) {
  18088. var mesh = this.getMeshByID(id);
  18089. if (mesh) {
  18090. return mesh;
  18091. }
  18092. var light = this.getLightByID(id);
  18093. if (light) {
  18094. return light;
  18095. }
  18096. var camera = this.getCameraByID(id);
  18097. if (camera) {
  18098. return camera;
  18099. }
  18100. var bone = this.getBoneByID(id);
  18101. return bone;
  18102. };
  18103. Scene.prototype.getNodeByName = function (name) {
  18104. var mesh = this.getMeshByName(name);
  18105. if (mesh) {
  18106. return mesh;
  18107. }
  18108. var light = this.getLightByName(name);
  18109. if (light) {
  18110. return light;
  18111. }
  18112. var camera = this.getCameraByName(name);
  18113. if (camera) {
  18114. return camera;
  18115. }
  18116. var bone = this.getBoneByName(name);
  18117. return bone;
  18118. };
  18119. Scene.prototype.getMeshByName = function (name) {
  18120. for (var index = 0; index < this.meshes.length; index++) {
  18121. if (this.meshes[index].name === name) {
  18122. return this.meshes[index];
  18123. }
  18124. }
  18125. return null;
  18126. };
  18127. Scene.prototype.getSoundByName = function (name) {
  18128. var index;
  18129. if (BABYLON.AudioEngine) {
  18130. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18131. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18132. return this.mainSoundTrack.soundCollection[index];
  18133. }
  18134. }
  18135. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18136. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18137. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18138. return this.soundTracks[sdIndex].soundCollection[index];
  18139. }
  18140. }
  18141. }
  18142. }
  18143. return null;
  18144. };
  18145. Scene.prototype.getLastSkeletonByID = function (id) {
  18146. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18147. if (this.skeletons[index].id === id) {
  18148. return this.skeletons[index];
  18149. }
  18150. }
  18151. return null;
  18152. };
  18153. Scene.prototype.getSkeletonById = function (id) {
  18154. for (var index = 0; index < this.skeletons.length; index++) {
  18155. if (this.skeletons[index].id === id) {
  18156. return this.skeletons[index];
  18157. }
  18158. }
  18159. return null;
  18160. };
  18161. Scene.prototype.getSkeletonByName = function (name) {
  18162. for (var index = 0; index < this.skeletons.length; index++) {
  18163. if (this.skeletons[index].name === name) {
  18164. return this.skeletons[index];
  18165. }
  18166. }
  18167. return null;
  18168. };
  18169. Scene.prototype.getMorphTargetManagerById = function (id) {
  18170. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18171. if (this.morphTargetManagers[index].uniqueId === id) {
  18172. return this.morphTargetManagers[index];
  18173. }
  18174. }
  18175. return null;
  18176. };
  18177. Scene.prototype.isActiveMesh = function (mesh) {
  18178. return (this._activeMeshes.indexOf(mesh) !== -1);
  18179. };
  18180. /**
  18181. * Return a the first highlight layer of the scene with a given name.
  18182. * @param name The name of the highlight layer to look for.
  18183. * @return The highlight layer if found otherwise null.
  18184. */
  18185. Scene.prototype.getHighlightLayerByName = function (name) {
  18186. for (var index = 0; index < this.highlightLayers.length; index++) {
  18187. if (this.highlightLayers[index].name === name) {
  18188. return this.highlightLayers[index];
  18189. }
  18190. }
  18191. return null;
  18192. };
  18193. Object.defineProperty(Scene.prototype, "uid", {
  18194. /**
  18195. * Return a unique id as a string which can serve as an identifier for the scene
  18196. */
  18197. get: function () {
  18198. if (!this._uid) {
  18199. this._uid = BABYLON.Tools.RandomId();
  18200. }
  18201. return this._uid;
  18202. },
  18203. enumerable: true,
  18204. configurable: true
  18205. });
  18206. /**
  18207. * Add an externaly attached data from its key.
  18208. * This method call will fail and return false, if such key already exists.
  18209. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18210. * @param key the unique key that identifies the data
  18211. * @param data the data object to associate to the key for this Engine instance
  18212. * @return true if no such key were already present and the data was added successfully, false otherwise
  18213. */
  18214. Scene.prototype.addExternalData = function (key, data) {
  18215. if (!this._externalData) {
  18216. this._externalData = new BABYLON.StringDictionary();
  18217. }
  18218. return this._externalData.add(key, data);
  18219. };
  18220. /**
  18221. * Get an externaly attached data from its key
  18222. * @param key the unique key that identifies the data
  18223. * @return the associated data, if present (can be null), or undefined if not present
  18224. */
  18225. Scene.prototype.getExternalData = function (key) {
  18226. if (!this._externalData) {
  18227. return null;
  18228. }
  18229. return this._externalData.get(key);
  18230. };
  18231. /**
  18232. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18233. * @param key the unique key that identifies the data
  18234. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18235. * @return the associated data, can be null if the factory returned null.
  18236. */
  18237. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18238. if (!this._externalData) {
  18239. this._externalData = new BABYLON.StringDictionary();
  18240. }
  18241. return this._externalData.getOrAddWithFactory(key, factory);
  18242. };
  18243. /**
  18244. * Remove an externaly attached data from the Engine instance
  18245. * @param key the unique key that identifies the data
  18246. * @return true if the data was successfully removed, false if it doesn't exist
  18247. */
  18248. Scene.prototype.removeExternalData = function (key) {
  18249. return this._externalData.remove(key);
  18250. };
  18251. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18252. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18253. var material = subMesh.getMaterial();
  18254. if (mesh.showSubMeshesBoundingBox) {
  18255. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18256. }
  18257. if (material) {
  18258. // Render targets
  18259. if (material.getRenderTargetTextures) {
  18260. if (this._processedMaterials.indexOf(material) === -1) {
  18261. this._processedMaterials.push(material);
  18262. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18263. }
  18264. }
  18265. // Dispatch
  18266. this._activeIndices.addCount(subMesh.indexCount, false);
  18267. this._renderingManager.dispatch(subMesh);
  18268. }
  18269. }
  18270. };
  18271. Scene.prototype._isInIntermediateRendering = function () {
  18272. return this._intermediateRendering;
  18273. };
  18274. Scene.prototype._evaluateActiveMeshes = function () {
  18275. this.activeCamera._activeMeshes.reset();
  18276. this._activeMeshes.reset();
  18277. this._renderingManager.reset();
  18278. this._processedMaterials.reset();
  18279. this._activeParticleSystems.reset();
  18280. this._activeSkeletons.reset();
  18281. this._softwareSkinnedMeshes.reset();
  18282. if (this._boundingBoxRenderer) {
  18283. this._boundingBoxRenderer.reset();
  18284. }
  18285. // Meshes
  18286. var meshes;
  18287. var len;
  18288. if (this._selectionOctree) {
  18289. var selection = this._selectionOctree.select(this._frustumPlanes);
  18290. meshes = selection.data;
  18291. len = selection.length;
  18292. }
  18293. else {
  18294. len = this.meshes.length;
  18295. meshes = this.meshes;
  18296. }
  18297. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18298. var mesh = meshes[meshIndex];
  18299. if (mesh.isBlocked) {
  18300. continue;
  18301. }
  18302. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18303. if (!mesh.isReady() || !mesh.isEnabled()) {
  18304. continue;
  18305. }
  18306. mesh.computeWorldMatrix();
  18307. // Intersections
  18308. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18309. this._meshesForIntersections.pushNoDuplicate(mesh);
  18310. }
  18311. // Switch to current LOD
  18312. var meshLOD = mesh.getLOD(this.activeCamera);
  18313. if (!meshLOD) {
  18314. continue;
  18315. }
  18316. mesh._preActivate();
  18317. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18318. this._activeMeshes.push(mesh);
  18319. this.activeCamera._activeMeshes.push(mesh);
  18320. mesh._activate(this._renderId);
  18321. if (meshLOD !== mesh) {
  18322. meshLOD._activate(this._renderId);
  18323. }
  18324. this._activeMesh(mesh, meshLOD);
  18325. }
  18326. }
  18327. // Particle systems
  18328. this._particlesDuration.beginMonitoring();
  18329. var beforeParticlesDate = BABYLON.Tools.Now;
  18330. if (this.particlesEnabled) {
  18331. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18332. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18333. var particleSystem = this.particleSystems[particleIndex];
  18334. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18335. continue;
  18336. }
  18337. var emitter = particleSystem.emitter;
  18338. if (!emitter.position || emitter.isEnabled()) {
  18339. this._activeParticleSystems.push(particleSystem);
  18340. particleSystem.animate();
  18341. this._renderingManager.dispatchParticles(particleSystem);
  18342. }
  18343. }
  18344. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18345. }
  18346. this._particlesDuration.endMonitoring(false);
  18347. };
  18348. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18349. if (mesh.skeleton && this.skeletonsEnabled) {
  18350. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18351. mesh.skeleton.prepare();
  18352. }
  18353. if (!mesh.computeBonesUsingShaders) {
  18354. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18355. }
  18356. }
  18357. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18358. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18359. }
  18360. if (mesh && mesh.subMeshes) {
  18361. // Submeshes Octrees
  18362. var len;
  18363. var subMeshes;
  18364. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18365. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18366. len = intersections.length;
  18367. subMeshes = intersections.data;
  18368. }
  18369. else {
  18370. subMeshes = mesh.subMeshes;
  18371. len = subMeshes.length;
  18372. }
  18373. for (var subIndex = 0; subIndex < len; subIndex++) {
  18374. var subMesh = subMeshes[subIndex];
  18375. this._evaluateSubMesh(subMesh, mesh);
  18376. }
  18377. }
  18378. };
  18379. Scene.prototype.updateTransformMatrix = function (force) {
  18380. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18381. };
  18382. Scene.prototype._renderForCamera = function (camera) {
  18383. var engine = this._engine;
  18384. var startTime = BABYLON.Tools.Now;
  18385. this.activeCamera = camera;
  18386. if (!this.activeCamera)
  18387. throw new Error("Active camera not set");
  18388. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18389. // Viewport
  18390. engine.setViewport(this.activeCamera.viewport);
  18391. // Camera
  18392. this.resetCachedMaterial();
  18393. this._renderId++;
  18394. this.updateTransformMatrix();
  18395. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18396. // Meshes
  18397. this._evaluateActiveMeshesDuration.beginMonitoring();
  18398. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18399. this._evaluateActiveMeshes();
  18400. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18401. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18402. // Software skinning
  18403. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18404. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18405. mesh.applySkeleton(mesh.skeleton);
  18406. }
  18407. // Render targets
  18408. this._renderTargetsDuration.beginMonitoring();
  18409. var needsRestoreFrameBuffer = false;
  18410. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18411. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18412. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18413. }
  18414. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18415. this._intermediateRendering = true;
  18416. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18417. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18418. var renderTarget = this._renderTargets.data[renderIndex];
  18419. if (renderTarget._shouldRender()) {
  18420. this._renderId++;
  18421. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18422. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18423. }
  18424. }
  18425. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18426. this._intermediateRendering = false;
  18427. this._renderId++;
  18428. needsRestoreFrameBuffer = true; // Restore back buffer
  18429. }
  18430. // Render HighlightLayer Texture
  18431. var stencilState = this._engine.getStencilBuffer();
  18432. var renderhighlights = false;
  18433. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18434. this._intermediateRendering = true;
  18435. for (var i = 0; i < this.highlightLayers.length; i++) {
  18436. var highlightLayer = this.highlightLayers[i];
  18437. if (highlightLayer.shouldRender() &&
  18438. (!highlightLayer.camera ||
  18439. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18440. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18441. renderhighlights = true;
  18442. var renderTarget = highlightLayer._mainTexture;
  18443. if (renderTarget._shouldRender()) {
  18444. this._renderId++;
  18445. renderTarget.render(false, false);
  18446. needsRestoreFrameBuffer = true;
  18447. }
  18448. }
  18449. }
  18450. this._intermediateRendering = false;
  18451. this._renderId++;
  18452. }
  18453. if (needsRestoreFrameBuffer) {
  18454. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18455. }
  18456. this._renderTargetsDuration.endMonitoring(false);
  18457. // Prepare Frame
  18458. this.postProcessManager._prepareFrame();
  18459. this._renderDuration.beginMonitoring();
  18460. // Backgrounds
  18461. var layerIndex;
  18462. var layer;
  18463. if (this.layers.length) {
  18464. engine.setDepthBuffer(false);
  18465. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18466. layer = this.layers[layerIndex];
  18467. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18468. layer.render();
  18469. }
  18470. }
  18471. engine.setDepthBuffer(true);
  18472. }
  18473. // Render
  18474. BABYLON.Tools.StartPerformanceCounter("Main render");
  18475. // Activate HighlightLayer stencil
  18476. if (renderhighlights) {
  18477. this._engine.setStencilBuffer(true);
  18478. }
  18479. this._renderingManager.render(null, null, true, true);
  18480. // Restore HighlightLayer stencil
  18481. if (renderhighlights) {
  18482. this._engine.setStencilBuffer(stencilState);
  18483. }
  18484. BABYLON.Tools.EndPerformanceCounter("Main render");
  18485. // Bounding boxes
  18486. if (this._boundingBoxRenderer) {
  18487. this._boundingBoxRenderer.render();
  18488. }
  18489. // Lens flares
  18490. if (this.lensFlaresEnabled) {
  18491. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18492. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18493. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18494. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18495. lensFlareSystem.render();
  18496. }
  18497. }
  18498. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18499. }
  18500. // Foregrounds
  18501. if (this.layers.length) {
  18502. engine.setDepthBuffer(false);
  18503. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18504. layer = this.layers[layerIndex];
  18505. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18506. layer.render();
  18507. }
  18508. }
  18509. engine.setDepthBuffer(true);
  18510. }
  18511. // Highlight Layer
  18512. if (renderhighlights) {
  18513. engine.setDepthBuffer(false);
  18514. for (var i = 0; i < this.highlightLayers.length; i++) {
  18515. if (this.highlightLayers[i].shouldRender()) {
  18516. this.highlightLayers[i].render();
  18517. }
  18518. }
  18519. engine.setDepthBuffer(true);
  18520. }
  18521. this._renderDuration.endMonitoring(false);
  18522. // Finalize frame
  18523. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18524. // Update camera
  18525. this.activeCamera._updateFromScene();
  18526. // Reset some special arrays
  18527. this._renderTargets.reset();
  18528. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18529. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18530. };
  18531. Scene.prototype._processSubCameras = function (camera) {
  18532. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18533. this._renderForCamera(camera);
  18534. return;
  18535. }
  18536. // rig cameras
  18537. for (var index = 0; index < camera._rigCameras.length; index++) {
  18538. this._renderForCamera(camera._rigCameras[index]);
  18539. }
  18540. this.activeCamera = camera;
  18541. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18542. // Update camera
  18543. this.activeCamera._updateFromScene();
  18544. };
  18545. Scene.prototype._checkIntersections = function () {
  18546. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18547. var sourceMesh = this._meshesForIntersections.data[index];
  18548. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18549. var action = sourceMesh.actionManager.actions[actionIndex];
  18550. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18551. var parameters = action.getTriggerParameter();
  18552. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18553. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18554. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18555. if (areIntersecting && currentIntersectionInProgress === -1) {
  18556. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18557. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18558. sourceMesh._intersectionsInProgress.push(otherMesh);
  18559. }
  18560. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18561. sourceMesh._intersectionsInProgress.push(otherMesh);
  18562. }
  18563. }
  18564. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18565. //They intersected, and now they don't.
  18566. //is this trigger an exit trigger? execute an event.
  18567. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18568. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18569. }
  18570. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18571. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18572. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18573. }
  18574. }
  18575. }
  18576. }
  18577. }
  18578. };
  18579. Scene.prototype.render = function () {
  18580. if (this.isDisposed) {
  18581. return;
  18582. }
  18583. this._lastFrameDuration.beginMonitoring();
  18584. this._particlesDuration.fetchNewFrame();
  18585. this._spritesDuration.fetchNewFrame();
  18586. this._activeParticles.fetchNewFrame();
  18587. this._renderDuration.fetchNewFrame();
  18588. this._renderTargetsDuration.fetchNewFrame();
  18589. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18590. this._totalVertices.fetchNewFrame();
  18591. this._activeIndices.fetchNewFrame();
  18592. this._activeBones.fetchNewFrame();
  18593. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18594. this._meshesForIntersections.reset();
  18595. this.resetCachedMaterial();
  18596. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18597. // Actions
  18598. if (this.actionManager) {
  18599. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18600. }
  18601. //Simplification Queue
  18602. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18603. this.simplificationQueue.executeNext();
  18604. }
  18605. if (this._engine.isDeterministicLockStep()) {
  18606. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18607. var defaultTimeStep = (60.0 / 1000.0);
  18608. if (this._physicsEngine) {
  18609. defaultTimeStep = this._physicsEngine.getTimeStep();
  18610. }
  18611. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18612. this._timeAccumulator += deltaTime;
  18613. // compute the amount of fixed steps we should have taken since the last step
  18614. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18615. internalSteps = Math.min(internalSteps, maxSubSteps);
  18616. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  18617. this.onBeforeStepObservable.notifyObservers(this);
  18618. // Animations
  18619. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  18620. this._animate();
  18621. // Physics
  18622. if (this._physicsEngine) {
  18623. BABYLON.Tools.StartPerformanceCounter("Physics");
  18624. this._physicsEngine._step(defaultTimeStep);
  18625. BABYLON.Tools.EndPerformanceCounter("Physics");
  18626. }
  18627. this._timeAccumulator -= defaultTimeStep;
  18628. this.onAfterStepObservable.notifyObservers(this);
  18629. this._currentStepId++;
  18630. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  18631. // Q: can this be optimized by putting some code in the afterStep callback?
  18632. // I had to put this code here, otherwise mesh attached to bones of another mesh skeleton,
  18633. // would return incorrect positions for internal stepIds (non-rendered steps)
  18634. this._evaluateActiveMeshes();
  18635. }
  18636. }
  18637. }
  18638. else {
  18639. // Animations
  18640. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18641. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18642. this._animate();
  18643. // Physics
  18644. if (this._physicsEngine) {
  18645. BABYLON.Tools.StartPerformanceCounter("Physics");
  18646. this._physicsEngine._step(deltaTime / 1000.0);
  18647. BABYLON.Tools.EndPerformanceCounter("Physics");
  18648. }
  18649. }
  18650. // Before render
  18651. this.onBeforeRenderObservable.notifyObservers(this);
  18652. // Customs render targets
  18653. this._renderTargetsDuration.beginMonitoring();
  18654. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18655. var engine = this.getEngine();
  18656. var currentActiveCamera = this.activeCamera;
  18657. if (this.renderTargetsEnabled) {
  18658. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18659. this._intermediateRendering = true;
  18660. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18661. var renderTarget = this.customRenderTargets[customIndex];
  18662. if (renderTarget._shouldRender()) {
  18663. this._renderId++;
  18664. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18665. if (!this.activeCamera)
  18666. throw new Error("Active camera not set");
  18667. // Viewport
  18668. engine.setViewport(this.activeCamera.viewport);
  18669. // Camera
  18670. this.updateTransformMatrix();
  18671. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18672. }
  18673. }
  18674. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18675. this._intermediateRendering = false;
  18676. this._renderId++;
  18677. }
  18678. // Restore back buffer
  18679. if (this.customRenderTargets.length > 0) {
  18680. engine.restoreDefaultFramebuffer();
  18681. }
  18682. this._renderTargetsDuration.endMonitoring();
  18683. this.activeCamera = currentActiveCamera;
  18684. // Procedural textures
  18685. if (this.proceduralTexturesEnabled) {
  18686. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18687. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18688. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18689. if (proceduralTexture._shouldRender()) {
  18690. proceduralTexture.render();
  18691. }
  18692. }
  18693. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18694. }
  18695. // Clear
  18696. if (this.autoClearDepthAndStencil || this.autoClear) {
  18697. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18698. }
  18699. // Shadows
  18700. if (this.shadowsEnabled) {
  18701. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18702. var light = this.lights[lightIndex];
  18703. var shadowGenerator = light.getShadowGenerator();
  18704. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18705. var shadowMap = shadowGenerator.getShadowMap();
  18706. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18707. this._renderTargets.push(shadowMap);
  18708. }
  18709. }
  18710. }
  18711. }
  18712. // Depth renderer
  18713. if (this._depthRenderer) {
  18714. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18715. }
  18716. // Geometry renderer
  18717. if (this._geometryBufferRenderer) {
  18718. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  18719. }
  18720. // RenderPipeline
  18721. if (this._postProcessRenderPipelineManager) {
  18722. this._postProcessRenderPipelineManager.update();
  18723. }
  18724. // Multi-cameras?
  18725. if (this.activeCameras.length > 0) {
  18726. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18727. if (cameraIndex > 0) {
  18728. this._engine.clear(null, false, true, true);
  18729. }
  18730. this._processSubCameras(this.activeCameras[cameraIndex]);
  18731. }
  18732. }
  18733. else {
  18734. if (!this.activeCamera) {
  18735. throw new Error("No camera defined");
  18736. }
  18737. this._processSubCameras(this.activeCamera);
  18738. }
  18739. // Intersection checks
  18740. this._checkIntersections();
  18741. // Update the audio listener attached to the camera
  18742. if (BABYLON.AudioEngine) {
  18743. this._updateAudioParameters();
  18744. }
  18745. // After render
  18746. if (this.afterRender) {
  18747. this.afterRender();
  18748. }
  18749. this.onAfterRenderObservable.notifyObservers(this);
  18750. // Cleaning
  18751. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18752. this._toBeDisposed.data[index].dispose();
  18753. this._toBeDisposed[index] = null;
  18754. }
  18755. this._toBeDisposed.reset();
  18756. if (this.dumpNextRenderTargets) {
  18757. this.dumpNextRenderTargets = false;
  18758. }
  18759. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18760. this._lastFrameDuration.endMonitoring();
  18761. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18762. this._totalLightsCounter.addCount(this.lights.length, true);
  18763. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18764. this._totalTexturesCounter.addCount(this.textures.length, true);
  18765. this._activeBones.addCount(0, true);
  18766. this._activeIndices.addCount(0, true);
  18767. this._activeParticles.addCount(0, true);
  18768. };
  18769. Scene.prototype._updateAudioParameters = function () {
  18770. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18771. return;
  18772. }
  18773. var listeningCamera;
  18774. var audioEngine = BABYLON.Engine.audioEngine;
  18775. if (this.activeCameras.length > 0) {
  18776. listeningCamera = this.activeCameras[0];
  18777. }
  18778. else {
  18779. listeningCamera = this.activeCamera;
  18780. }
  18781. if (listeningCamera && audioEngine.canUseWebAudio) {
  18782. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18783. // for VR cameras
  18784. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  18785. listeningCamera = listeningCamera.rigCameras[0];
  18786. }
  18787. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18788. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18789. cameraDirection.normalize();
  18790. // To avoid some errors on GearVR
  18791. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  18792. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18793. }
  18794. var i;
  18795. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18796. var sound = this.mainSoundTrack.soundCollection[i];
  18797. if (sound.useCustomAttenuation) {
  18798. sound.updateDistanceFromListener();
  18799. }
  18800. }
  18801. for (i = 0; i < this.soundTracks.length; i++) {
  18802. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18803. sound = this.soundTracks[i].soundCollection[j];
  18804. if (sound.useCustomAttenuation) {
  18805. sound.updateDistanceFromListener();
  18806. }
  18807. }
  18808. }
  18809. }
  18810. };
  18811. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18812. // Audio
  18813. get: function () {
  18814. return this._audioEnabled;
  18815. },
  18816. set: function (value) {
  18817. this._audioEnabled = value;
  18818. if (BABYLON.AudioEngine) {
  18819. if (this._audioEnabled) {
  18820. this._enableAudio();
  18821. }
  18822. else {
  18823. this._disableAudio();
  18824. }
  18825. }
  18826. },
  18827. enumerable: true,
  18828. configurable: true
  18829. });
  18830. Scene.prototype._disableAudio = function () {
  18831. var i;
  18832. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18833. this.mainSoundTrack.soundCollection[i].pause();
  18834. }
  18835. for (i = 0; i < this.soundTracks.length; i++) {
  18836. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18837. this.soundTracks[i].soundCollection[j].pause();
  18838. }
  18839. }
  18840. };
  18841. Scene.prototype._enableAudio = function () {
  18842. var i;
  18843. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18844. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18845. this.mainSoundTrack.soundCollection[i].play();
  18846. }
  18847. }
  18848. for (i = 0; i < this.soundTracks.length; i++) {
  18849. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18850. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18851. this.soundTracks[i].soundCollection[j].play();
  18852. }
  18853. }
  18854. }
  18855. };
  18856. Object.defineProperty(Scene.prototype, "headphone", {
  18857. get: function () {
  18858. return this._headphone;
  18859. },
  18860. set: function (value) {
  18861. this._headphone = value;
  18862. if (BABYLON.AudioEngine) {
  18863. if (this._headphone) {
  18864. this._switchAudioModeForHeadphones();
  18865. }
  18866. else {
  18867. this._switchAudioModeForNormalSpeakers();
  18868. }
  18869. }
  18870. },
  18871. enumerable: true,
  18872. configurable: true
  18873. });
  18874. Scene.prototype._switchAudioModeForHeadphones = function () {
  18875. this.mainSoundTrack.switchPanningModelToHRTF();
  18876. for (var i = 0; i < this.soundTracks.length; i++) {
  18877. this.soundTracks[i].switchPanningModelToHRTF();
  18878. }
  18879. };
  18880. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18881. this.mainSoundTrack.switchPanningModelToEqualPower();
  18882. for (var i = 0; i < this.soundTracks.length; i++) {
  18883. this.soundTracks[i].switchPanningModelToEqualPower();
  18884. }
  18885. };
  18886. Scene.prototype.enableDepthRenderer = function () {
  18887. if (this._depthRenderer) {
  18888. return this._depthRenderer;
  18889. }
  18890. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18891. return this._depthRenderer;
  18892. };
  18893. Scene.prototype.disableDepthRenderer = function () {
  18894. if (!this._depthRenderer) {
  18895. return;
  18896. }
  18897. this._depthRenderer.dispose();
  18898. this._depthRenderer = null;
  18899. };
  18900. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  18901. if (ratio === void 0) { ratio = 1; }
  18902. if (this._geometryBufferRenderer) {
  18903. return this._geometryBufferRenderer;
  18904. }
  18905. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18906. if (!this._geometryBufferRenderer.isSupported) {
  18907. this._geometryBufferRenderer = null;
  18908. }
  18909. return this._geometryBufferRenderer;
  18910. };
  18911. Scene.prototype.disableGeometryBufferRenderer = function () {
  18912. if (!this._geometryBufferRenderer) {
  18913. return;
  18914. }
  18915. this._geometryBufferRenderer.dispose();
  18916. this._geometryBufferRenderer = null;
  18917. };
  18918. Scene.prototype.freezeMaterials = function () {
  18919. for (var i = 0; i < this.materials.length; i++) {
  18920. this.materials[i].freeze();
  18921. }
  18922. };
  18923. Scene.prototype.unfreezeMaterials = function () {
  18924. for (var i = 0; i < this.materials.length; i++) {
  18925. this.materials[i].unfreeze();
  18926. }
  18927. };
  18928. Scene.prototype.dispose = function () {
  18929. this.beforeRender = null;
  18930. this.afterRender = null;
  18931. this.skeletons = [];
  18932. this.morphTargetManagers = [];
  18933. this.importedMeshesFiles = new Array();
  18934. this.resetCachedMaterial();
  18935. if (this._depthRenderer) {
  18936. this._depthRenderer.dispose();
  18937. }
  18938. if (this._gamepadManager) {
  18939. this._gamepadManager.dispose();
  18940. this._gamepadManager = null;
  18941. }
  18942. // Smart arrays
  18943. if (this.activeCamera) {
  18944. this.activeCamera._activeMeshes.dispose();
  18945. this.activeCamera = null;
  18946. }
  18947. this._activeMeshes.dispose();
  18948. this._renderingManager.dispose();
  18949. this._processedMaterials.dispose();
  18950. this._activeParticleSystems.dispose();
  18951. this._activeSkeletons.dispose();
  18952. this._softwareSkinnedMeshes.dispose();
  18953. this._renderTargets.dispose();
  18954. if (this._boundingBoxRenderer) {
  18955. this._boundingBoxRenderer.dispose();
  18956. }
  18957. this._meshesForIntersections.dispose();
  18958. this._toBeDisposed.dispose();
  18959. // Debug layer
  18960. if (this._debugLayer) {
  18961. this._debugLayer.hide();
  18962. }
  18963. // Events
  18964. this.onDisposeObservable.notifyObservers(this);
  18965. this.onDisposeObservable.clear();
  18966. this.onBeforeRenderObservable.clear();
  18967. this.onAfterRenderObservable.clear();
  18968. this.detachControl();
  18969. // Release sounds & sounds tracks
  18970. if (BABYLON.AudioEngine) {
  18971. this.disposeSounds();
  18972. }
  18973. // VR Helper
  18974. if (this.VRHelper) {
  18975. this.VRHelper.dispose();
  18976. }
  18977. // Detach cameras
  18978. var canvas = this._engine.getRenderingCanvas();
  18979. var index;
  18980. for (index = 0; index < this.cameras.length; index++) {
  18981. this.cameras[index].detachControl(canvas);
  18982. }
  18983. // Release lights
  18984. while (this.lights.length) {
  18985. this.lights[0].dispose();
  18986. }
  18987. // Release meshes
  18988. while (this.meshes.length) {
  18989. this.meshes[0].dispose(true);
  18990. }
  18991. // Release cameras
  18992. while (this.cameras.length) {
  18993. this.cameras[0].dispose();
  18994. }
  18995. // Release materials
  18996. if (this.defaultMaterial) {
  18997. this.defaultMaterial.dispose();
  18998. }
  18999. while (this.multiMaterials.length) {
  19000. this.multiMaterials[0].dispose();
  19001. }
  19002. while (this.materials.length) {
  19003. this.materials[0].dispose();
  19004. }
  19005. // Release particles
  19006. while (this.particleSystems.length) {
  19007. this.particleSystems[0].dispose();
  19008. }
  19009. // Release sprites
  19010. while (this.spriteManagers.length) {
  19011. this.spriteManagers[0].dispose();
  19012. }
  19013. // Release postProcesses
  19014. while (this.postProcesses.length) {
  19015. this.postProcesses[0].dispose();
  19016. }
  19017. // Release layers
  19018. while (this.layers.length) {
  19019. this.layers[0].dispose();
  19020. }
  19021. while (this.highlightLayers.length) {
  19022. this.highlightLayers[0].dispose();
  19023. }
  19024. // Release textures
  19025. while (this.textures.length) {
  19026. this.textures[0].dispose();
  19027. }
  19028. // Release UBO
  19029. this._sceneUbo.dispose();
  19030. // Post-processes
  19031. this.postProcessManager.dispose();
  19032. // Physics
  19033. if (this._physicsEngine) {
  19034. this.disablePhysicsEngine();
  19035. }
  19036. // Remove from engine
  19037. index = this._engine.scenes.indexOf(this);
  19038. if (index > -1) {
  19039. this._engine.scenes.splice(index, 1);
  19040. }
  19041. this._engine.wipeCaches();
  19042. this._engine = null;
  19043. this.defaultMaterial = null;
  19044. this.multiMaterials = null;
  19045. this.materials = null;
  19046. };
  19047. Object.defineProperty(Scene.prototype, "isDisposed", {
  19048. get: function () {
  19049. return !this._engine;
  19050. },
  19051. enumerable: true,
  19052. configurable: true
  19053. });
  19054. // Release sounds & sounds tracks
  19055. Scene.prototype.disposeSounds = function () {
  19056. this.mainSoundTrack.dispose();
  19057. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19058. this.soundTracks[scIndex].dispose();
  19059. }
  19060. };
  19061. // Octrees
  19062. Scene.prototype.getWorldExtends = function () {
  19063. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19064. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19065. for (var index = 0; index < this.meshes.length; index++) {
  19066. var mesh = this.meshes[index];
  19067. mesh.computeWorldMatrix(true);
  19068. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19069. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19070. BABYLON.Tools.CheckExtends(minBox, min, max);
  19071. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19072. }
  19073. return {
  19074. min: min,
  19075. max: max
  19076. };
  19077. };
  19078. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19079. if (maxCapacity === void 0) { maxCapacity = 64; }
  19080. if (maxDepth === void 0) { maxDepth = 2; }
  19081. if (!this._selectionOctree) {
  19082. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19083. }
  19084. var worldExtends = this.getWorldExtends();
  19085. // Update octree
  19086. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19087. return this._selectionOctree;
  19088. };
  19089. // Picking
  19090. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19091. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19092. var engine = this._engine;
  19093. if (!camera) {
  19094. if (!this.activeCamera)
  19095. throw new Error("Active camera not set");
  19096. camera = this.activeCamera;
  19097. }
  19098. var cameraViewport = camera.viewport;
  19099. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19100. // Moving coordinates to local viewport world
  19101. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19102. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19103. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19104. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19105. };
  19106. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19107. if (!BABYLON.PickingInfo) {
  19108. return null;
  19109. }
  19110. var engine = this._engine;
  19111. if (!camera) {
  19112. if (!this.activeCamera)
  19113. throw new Error("Active camera not set");
  19114. camera = this.activeCamera;
  19115. }
  19116. var cameraViewport = camera.viewport;
  19117. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19118. var identity = BABYLON.Matrix.Identity();
  19119. // Moving coordinates to local viewport world
  19120. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19121. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19122. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19123. };
  19124. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19125. if (!BABYLON.PickingInfo) {
  19126. return null;
  19127. }
  19128. var pickingInfo = null;
  19129. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19130. var mesh = this.meshes[meshIndex];
  19131. if (predicate) {
  19132. if (!predicate(mesh)) {
  19133. continue;
  19134. }
  19135. }
  19136. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19137. continue;
  19138. }
  19139. var world = mesh.getWorldMatrix();
  19140. var ray = rayFunction(world);
  19141. var result = mesh.intersects(ray, fastCheck);
  19142. if (!result || !result.hit)
  19143. continue;
  19144. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19145. continue;
  19146. pickingInfo = result;
  19147. if (fastCheck) {
  19148. break;
  19149. }
  19150. }
  19151. return pickingInfo || new BABYLON.PickingInfo();
  19152. };
  19153. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19154. if (!BABYLON.PickingInfo) {
  19155. return null;
  19156. }
  19157. var pickingInfos = new Array();
  19158. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19159. var mesh = this.meshes[meshIndex];
  19160. if (predicate) {
  19161. if (!predicate(mesh)) {
  19162. continue;
  19163. }
  19164. }
  19165. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19166. continue;
  19167. }
  19168. var world = mesh.getWorldMatrix();
  19169. var ray = rayFunction(world);
  19170. var result = mesh.intersects(ray, false);
  19171. if (!result || !result.hit)
  19172. continue;
  19173. pickingInfos.push(result);
  19174. }
  19175. return pickingInfos;
  19176. };
  19177. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19178. if (!BABYLON.PickingInfo) {
  19179. return null;
  19180. }
  19181. var pickingInfo = null;
  19182. camera = camera || this.activeCamera;
  19183. if (this.spriteManagers.length > 0) {
  19184. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19185. var spriteManager = this.spriteManagers[spriteIndex];
  19186. if (!spriteManager.isPickable) {
  19187. continue;
  19188. }
  19189. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19190. if (!result || !result.hit)
  19191. continue;
  19192. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19193. continue;
  19194. pickingInfo = result;
  19195. if (fastCheck) {
  19196. break;
  19197. }
  19198. }
  19199. }
  19200. return pickingInfo || new BABYLON.PickingInfo();
  19201. };
  19202. /** Launch a ray to try to pick a mesh in the scene
  19203. * @param x position on screen
  19204. * @param y position on screen
  19205. * @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
  19206. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19207. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19208. */
  19209. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19210. var _this = this;
  19211. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19212. };
  19213. /** Launch a ray to try to pick a sprite in the scene
  19214. * @param x position on screen
  19215. * @param y position on screen
  19216. * @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
  19217. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19218. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19219. */
  19220. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19221. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19222. };
  19223. /** Use the given ray to pick a mesh in the scene
  19224. * @param ray The ray to use to pick meshes
  19225. * @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
  19226. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19227. */
  19228. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19229. var _this = this;
  19230. return this._internalPick(function (world) {
  19231. if (!_this._pickWithRayInverseMatrix) {
  19232. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19233. }
  19234. world.invertToRef(_this._pickWithRayInverseMatrix);
  19235. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19236. }, predicate, fastCheck);
  19237. };
  19238. /**
  19239. * Launch a ray to try to pick a mesh in the scene
  19240. * @param x X position on screen
  19241. * @param y Y position on screen
  19242. * @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
  19243. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19244. */
  19245. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19246. var _this = this;
  19247. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19248. };
  19249. /**
  19250. * Launch a ray to try to pick a mesh in the scene
  19251. * @param ray Ray to use
  19252. * @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
  19253. */
  19254. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19255. var _this = this;
  19256. return this._internalMultiPick(function (world) {
  19257. if (!_this._pickWithRayInverseMatrix) {
  19258. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19259. }
  19260. world.invertToRef(_this._pickWithRayInverseMatrix);
  19261. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19262. }, predicate);
  19263. };
  19264. Scene.prototype.setPointerOverMesh = function (mesh) {
  19265. if (this._pointerOverMesh === mesh) {
  19266. return;
  19267. }
  19268. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19269. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19270. }
  19271. this._pointerOverMesh = mesh;
  19272. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19273. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19274. }
  19275. };
  19276. Scene.prototype.getPointerOverMesh = function () {
  19277. return this._pointerOverMesh;
  19278. };
  19279. Scene.prototype.setPointerOverSprite = function (sprite) {
  19280. if (this._pointerOverSprite === sprite) {
  19281. return;
  19282. }
  19283. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19284. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19285. }
  19286. this._pointerOverSprite = sprite;
  19287. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19288. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19289. }
  19290. };
  19291. Scene.prototype.getPointerOverSprite = function () {
  19292. return this._pointerOverSprite;
  19293. };
  19294. // Physics
  19295. Scene.prototype.getPhysicsEngine = function () {
  19296. return this._physicsEngine;
  19297. };
  19298. /**
  19299. * Enables physics to the current scene
  19300. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19301. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19302. * @return {boolean} was the physics engine initialized
  19303. */
  19304. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19305. if (this._physicsEngine) {
  19306. return true;
  19307. }
  19308. try {
  19309. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19310. return true;
  19311. }
  19312. catch (e) {
  19313. BABYLON.Tools.Error(e.message);
  19314. return false;
  19315. }
  19316. };
  19317. Scene.prototype.disablePhysicsEngine = function () {
  19318. if (!this._physicsEngine) {
  19319. return;
  19320. }
  19321. this._physicsEngine.dispose();
  19322. this._physicsEngine = undefined;
  19323. };
  19324. Scene.prototype.isPhysicsEnabled = function () {
  19325. return this._physicsEngine !== undefined;
  19326. };
  19327. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19328. var mesh = compound.parts[0].mesh;
  19329. mesh.physicsImpostor.dispose();
  19330. mesh.physicsImpostor = null;
  19331. };
  19332. // Misc.
  19333. Scene.prototype._rebuildGeometries = function () {
  19334. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19335. var geometry = _a[_i];
  19336. geometry._rebuild();
  19337. }
  19338. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19339. var mesh = _c[_b];
  19340. mesh._rebuild();
  19341. }
  19342. if (this.postProcessManager) {
  19343. this.postProcessManager._rebuild();
  19344. }
  19345. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19346. var layer = _e[_d];
  19347. layer._rebuild();
  19348. }
  19349. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19350. var highlightLayer = _g[_f];
  19351. highlightLayer._rebuild();
  19352. }
  19353. };
  19354. Scene.prototype._rebuildTextures = function () {
  19355. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19356. var texture = _a[_i];
  19357. texture._rebuild();
  19358. }
  19359. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19360. };
  19361. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19362. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19363. if (replace === void 0) { replace = false; }
  19364. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19365. // Dispose existing camera or light in replace mode.
  19366. if (replace) {
  19367. if (this.activeCamera) {
  19368. this.activeCamera.dispose();
  19369. this.activeCamera = null;
  19370. }
  19371. if (this.lights) {
  19372. for (var i = 0; i < this.lights.length; i++) {
  19373. this.lights[i].dispose();
  19374. }
  19375. }
  19376. }
  19377. // Light
  19378. if (this.lights.length === 0) {
  19379. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19380. }
  19381. // Camera
  19382. if (!this.activeCamera) {
  19383. var worldExtends = this.getWorldExtends();
  19384. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19385. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19386. var camera;
  19387. var radius = worldSize.length() * 1.5;
  19388. if (createArcRotateCamera) {
  19389. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19390. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19391. arcRotateCamera.wheelPrecision = 100 / radius;
  19392. camera = arcRotateCamera;
  19393. }
  19394. else {
  19395. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19396. freeCamera.setTarget(worldCenter);
  19397. camera = freeCamera;
  19398. }
  19399. camera.minZ = radius * 0.01;
  19400. camera.maxZ = radius * 100;
  19401. camera.speed = radius * 0.2;
  19402. this.activeCamera = camera;
  19403. if (attachCameraControls) {
  19404. camera.attachControl(this.getEngine().getRenderingCanvas());
  19405. }
  19406. }
  19407. };
  19408. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19409. if (pbr === void 0) { pbr = false; }
  19410. if (scale === void 0) { scale = 1000; }
  19411. if (blur === void 0) { blur = 0; }
  19412. if (environmentTexture) {
  19413. this.environmentTexture = environmentTexture;
  19414. }
  19415. if (!this.environmentTexture) {
  19416. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19417. return;
  19418. }
  19419. // Skybox
  19420. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19421. if (pbr) {
  19422. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19423. hdrSkyboxMaterial.backFaceCulling = false;
  19424. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19425. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19426. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19427. hdrSkyboxMaterial.disableLighting = true;
  19428. hdrSkyboxMaterial.twoSidedLighting = true;
  19429. hdrSkybox.infiniteDistance = true;
  19430. hdrSkybox.material = hdrSkyboxMaterial;
  19431. }
  19432. else {
  19433. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19434. skyboxMaterial.backFaceCulling = false;
  19435. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19436. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19437. skyboxMaterial.disableLighting = true;
  19438. hdrSkybox.infiniteDistance = true;
  19439. hdrSkybox.material = skyboxMaterial;
  19440. }
  19441. return hdrSkybox;
  19442. };
  19443. Scene.prototype.createDefaultVRExperience = function () {
  19444. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19445. };
  19446. // Tags
  19447. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19448. if (tagsQuery === undefined) {
  19449. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19450. return list;
  19451. }
  19452. var listByTags = [];
  19453. forEach = forEach || (function (item) { return; });
  19454. for (var i in list) {
  19455. var item = list[i];
  19456. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19457. listByTags.push(item);
  19458. forEach(item);
  19459. }
  19460. }
  19461. return listByTags;
  19462. };
  19463. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19464. return this._getByTags(this.meshes, tagsQuery, forEach);
  19465. };
  19466. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19467. return this._getByTags(this.cameras, tagsQuery, forEach);
  19468. };
  19469. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19470. return this._getByTags(this.lights, tagsQuery, forEach);
  19471. };
  19472. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19473. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19474. };
  19475. /**
  19476. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19477. * This allowed control for front to back rendering or reversly depending of the special needs.
  19478. *
  19479. * @param renderingGroupId The rendering group id corresponding to its index
  19480. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19481. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19482. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19483. */
  19484. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19485. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19486. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19487. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19488. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19489. };
  19490. /**
  19491. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19492. *
  19493. * @param renderingGroupId The rendering group id corresponding to its index
  19494. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19495. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19496. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19497. */
  19498. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19499. if (depth === void 0) { depth = true; }
  19500. if (stencil === void 0) { stencil = true; }
  19501. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19502. };
  19503. /**
  19504. * Will flag all materials as dirty to trigger new shader compilation
  19505. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19506. */
  19507. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19508. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19509. var material = _a[_i];
  19510. if (predicate && !predicate(material)) {
  19511. continue;
  19512. }
  19513. material.markAsDirty(flag);
  19514. }
  19515. };
  19516. // Statics
  19517. Scene._FOGMODE_NONE = 0;
  19518. Scene._FOGMODE_EXP = 1;
  19519. Scene._FOGMODE_EXP2 = 2;
  19520. Scene._FOGMODE_LINEAR = 3;
  19521. Scene.MinDeltaTime = 1.0;
  19522. Scene.MaxDeltaTime = 1000.0;
  19523. /** The distance in pixel that you have to move to prevent some events */
  19524. Scene.DragMovementThreshold = 10; // in pixels
  19525. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19526. Scene.LongPressDelay = 500; // in milliseconds
  19527. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19528. Scene.DoubleClickDelay = 300; // in milliseconds
  19529. /** If you need to check double click without raising a single click at first click, enable this flag */
  19530. Scene.ExclusiveDoubleClickMode = false;
  19531. return Scene;
  19532. }());
  19533. BABYLON.Scene = Scene;
  19534. })(BABYLON || (BABYLON = {}));
  19535. //# sourceMappingURL=babylon.scene.js.map
  19536. var BABYLON;
  19537. (function (BABYLON) {
  19538. var Buffer = (function () {
  19539. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19540. if (engine instanceof BABYLON.Mesh) {
  19541. this._engine = engine.getScene().getEngine();
  19542. }
  19543. else {
  19544. this._engine = engine;
  19545. }
  19546. this._updatable = updatable;
  19547. this._data = data;
  19548. this._strideSize = stride;
  19549. if (!postponeInternalCreation) {
  19550. this.create();
  19551. }
  19552. this._instanced = instanced;
  19553. this._instanceDivisor = instanced ? 1 : 0;
  19554. }
  19555. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19556. // a lot of these parameters are ignored as they are overriden by the buffer
  19557. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19558. };
  19559. // Properties
  19560. Buffer.prototype.isUpdatable = function () {
  19561. return this._updatable;
  19562. };
  19563. Buffer.prototype.getData = function () {
  19564. return this._data;
  19565. };
  19566. Buffer.prototype.getBuffer = function () {
  19567. return this._buffer;
  19568. };
  19569. Buffer.prototype.getStrideSize = function () {
  19570. return this._strideSize;
  19571. };
  19572. Buffer.prototype.getIsInstanced = function () {
  19573. return this._instanced;
  19574. };
  19575. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19576. get: function () {
  19577. return this._instanceDivisor;
  19578. },
  19579. set: function (value) {
  19580. this._instanceDivisor = value;
  19581. if (value == 0) {
  19582. this._instanced = false;
  19583. }
  19584. else {
  19585. this._instanced = true;
  19586. }
  19587. },
  19588. enumerable: true,
  19589. configurable: true
  19590. });
  19591. // Methods
  19592. Buffer.prototype.create = function (data) {
  19593. if (!data && this._buffer) {
  19594. return; // nothing to do
  19595. }
  19596. data = data || this._data;
  19597. if (!this._buffer) {
  19598. if (this._updatable) {
  19599. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19600. this._data = data;
  19601. }
  19602. else {
  19603. this._buffer = this._engine.createVertexBuffer(data);
  19604. }
  19605. }
  19606. else if (this._updatable) {
  19607. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19608. this._data = data;
  19609. }
  19610. };
  19611. Buffer.prototype._rebuild = function () {
  19612. this._buffer = null;
  19613. this.create(this._data);
  19614. };
  19615. Buffer.prototype.update = function (data) {
  19616. this.create(data);
  19617. };
  19618. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19619. if (!this._buffer) {
  19620. return;
  19621. }
  19622. if (this._updatable) {
  19623. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19624. this._data = null;
  19625. }
  19626. };
  19627. Buffer.prototype.dispose = function () {
  19628. if (!this._buffer) {
  19629. return;
  19630. }
  19631. if (this._engine._releaseBuffer(this._buffer)) {
  19632. this._buffer = null;
  19633. }
  19634. };
  19635. return Buffer;
  19636. }());
  19637. BABYLON.Buffer = Buffer;
  19638. })(BABYLON || (BABYLON = {}));
  19639. //# sourceMappingURL=babylon.buffer.js.map
  19640. var BABYLON;
  19641. (function (BABYLON) {
  19642. var VertexBuffer = (function () {
  19643. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19644. if (!stride) {
  19645. // Deduce stride from kind
  19646. switch (kind) {
  19647. case VertexBuffer.PositionKind:
  19648. stride = 3;
  19649. break;
  19650. case VertexBuffer.NormalKind:
  19651. stride = 3;
  19652. break;
  19653. case VertexBuffer.UVKind:
  19654. case VertexBuffer.UV2Kind:
  19655. case VertexBuffer.UV3Kind:
  19656. case VertexBuffer.UV4Kind:
  19657. case VertexBuffer.UV5Kind:
  19658. case VertexBuffer.UV6Kind:
  19659. stride = 2;
  19660. break;
  19661. case VertexBuffer.TangentKind:
  19662. case VertexBuffer.ColorKind:
  19663. stride = 4;
  19664. break;
  19665. case VertexBuffer.MatricesIndicesKind:
  19666. case VertexBuffer.MatricesIndicesExtraKind:
  19667. stride = 4;
  19668. break;
  19669. case VertexBuffer.MatricesWeightsKind:
  19670. case VertexBuffer.MatricesWeightsExtraKind:
  19671. stride = 4;
  19672. break;
  19673. }
  19674. }
  19675. if (data instanceof BABYLON.Buffer) {
  19676. if (!stride) {
  19677. stride = data.getStrideSize();
  19678. }
  19679. this._buffer = data;
  19680. this._ownsBuffer = false;
  19681. }
  19682. else {
  19683. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19684. this._ownsBuffer = true;
  19685. }
  19686. this._stride = stride;
  19687. this._offset = offset ? offset : 0;
  19688. this._size = size ? size : stride;
  19689. this._kind = kind;
  19690. }
  19691. VertexBuffer.prototype._rebuild = function () {
  19692. if (!this._buffer) {
  19693. return;
  19694. }
  19695. this._buffer._rebuild();
  19696. };
  19697. /**
  19698. * Returns the kind of the VertexBuffer (string).
  19699. */
  19700. VertexBuffer.prototype.getKind = function () {
  19701. return this._kind;
  19702. };
  19703. // Properties
  19704. /**
  19705. * Boolean : is the VertexBuffer updatable ?
  19706. */
  19707. VertexBuffer.prototype.isUpdatable = function () {
  19708. return this._buffer.isUpdatable();
  19709. };
  19710. /**
  19711. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  19712. */
  19713. VertexBuffer.prototype.getData = function () {
  19714. return this._buffer.getData();
  19715. };
  19716. /**
  19717. * Returns the WebGLBuffer associated to the VertexBuffer.
  19718. */
  19719. VertexBuffer.prototype.getBuffer = function () {
  19720. return this._buffer.getBuffer();
  19721. };
  19722. /**
  19723. * Returns the stride of the VertexBuffer (integer).
  19724. */
  19725. VertexBuffer.prototype.getStrideSize = function () {
  19726. return this._stride;
  19727. };
  19728. /**
  19729. * Returns the offset (integer).
  19730. */
  19731. VertexBuffer.prototype.getOffset = function () {
  19732. return this._offset;
  19733. };
  19734. /**
  19735. * Returns the VertexBuffer total size (integer).
  19736. */
  19737. VertexBuffer.prototype.getSize = function () {
  19738. return this._size;
  19739. };
  19740. /**
  19741. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  19742. */
  19743. VertexBuffer.prototype.getIsInstanced = function () {
  19744. return this._buffer.getIsInstanced();
  19745. };
  19746. /**
  19747. * Returns the instancing divisor, zero for non-instanced (integer).
  19748. */
  19749. VertexBuffer.prototype.getInstanceDivisor = function () {
  19750. return this._buffer.instanceDivisor;
  19751. };
  19752. // Methods
  19753. /**
  19754. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  19755. * Returns the created WebGLBuffer.
  19756. */
  19757. VertexBuffer.prototype.create = function (data) {
  19758. return this._buffer.create(data);
  19759. };
  19760. /**
  19761. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19762. * Returns the updated WebGLBuffer.
  19763. */
  19764. VertexBuffer.prototype.update = function (data) {
  19765. return this._buffer.update(data);
  19766. };
  19767. /**
  19768. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19769. * Returns the directly updated WebGLBuffer.
  19770. */
  19771. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19772. return this._buffer.updateDirectly(data, offset);
  19773. };
  19774. /**
  19775. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  19776. */
  19777. VertexBuffer.prototype.dispose = function () {
  19778. if (this._ownsBuffer) {
  19779. this._buffer.dispose();
  19780. }
  19781. };
  19782. Object.defineProperty(VertexBuffer, "PositionKind", {
  19783. get: function () {
  19784. return VertexBuffer._PositionKind;
  19785. },
  19786. enumerable: true,
  19787. configurable: true
  19788. });
  19789. Object.defineProperty(VertexBuffer, "NormalKind", {
  19790. get: function () {
  19791. return VertexBuffer._NormalKind;
  19792. },
  19793. enumerable: true,
  19794. configurable: true
  19795. });
  19796. Object.defineProperty(VertexBuffer, "TangentKind", {
  19797. get: function () {
  19798. return VertexBuffer._TangentKind;
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(VertexBuffer, "UVKind", {
  19804. get: function () {
  19805. return VertexBuffer._UVKind;
  19806. },
  19807. enumerable: true,
  19808. configurable: true
  19809. });
  19810. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19811. get: function () {
  19812. return VertexBuffer._UV2Kind;
  19813. },
  19814. enumerable: true,
  19815. configurable: true
  19816. });
  19817. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19818. get: function () {
  19819. return VertexBuffer._UV3Kind;
  19820. },
  19821. enumerable: true,
  19822. configurable: true
  19823. });
  19824. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19825. get: function () {
  19826. return VertexBuffer._UV4Kind;
  19827. },
  19828. enumerable: true,
  19829. configurable: true
  19830. });
  19831. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19832. get: function () {
  19833. return VertexBuffer._UV5Kind;
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19839. get: function () {
  19840. return VertexBuffer._UV6Kind;
  19841. },
  19842. enumerable: true,
  19843. configurable: true
  19844. });
  19845. Object.defineProperty(VertexBuffer, "ColorKind", {
  19846. get: function () {
  19847. return VertexBuffer._ColorKind;
  19848. },
  19849. enumerable: true,
  19850. configurable: true
  19851. });
  19852. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19853. get: function () {
  19854. return VertexBuffer._MatricesIndicesKind;
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19860. get: function () {
  19861. return VertexBuffer._MatricesWeightsKind;
  19862. },
  19863. enumerable: true,
  19864. configurable: true
  19865. });
  19866. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19867. get: function () {
  19868. return VertexBuffer._MatricesIndicesExtraKind;
  19869. },
  19870. enumerable: true,
  19871. configurable: true
  19872. });
  19873. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19874. get: function () {
  19875. return VertexBuffer._MatricesWeightsExtraKind;
  19876. },
  19877. enumerable: true,
  19878. configurable: true
  19879. });
  19880. // Enums
  19881. VertexBuffer._PositionKind = "position";
  19882. VertexBuffer._NormalKind = "normal";
  19883. VertexBuffer._TangentKind = "tangent";
  19884. VertexBuffer._UVKind = "uv";
  19885. VertexBuffer._UV2Kind = "uv2";
  19886. VertexBuffer._UV3Kind = "uv3";
  19887. VertexBuffer._UV4Kind = "uv4";
  19888. VertexBuffer._UV5Kind = "uv5";
  19889. VertexBuffer._UV6Kind = "uv6";
  19890. VertexBuffer._ColorKind = "color";
  19891. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19892. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19893. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19894. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19895. return VertexBuffer;
  19896. }());
  19897. BABYLON.VertexBuffer = VertexBuffer;
  19898. })(BABYLON || (BABYLON = {}));
  19899. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19900. var BABYLON;
  19901. (function (BABYLON) {
  19902. var InternalTexture = (function () {
  19903. function InternalTexture(engine, dataSource) {
  19904. this.onLoadedObservable = new BABYLON.Observable();
  19905. // Private
  19906. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  19907. this._references = 1;
  19908. this._engine = engine;
  19909. this._dataSource = dataSource;
  19910. this._webGLTexture = engine._createTexture();
  19911. }
  19912. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  19913. get: function () {
  19914. return this._dataSource;
  19915. },
  19916. enumerable: true,
  19917. configurable: true
  19918. });
  19919. InternalTexture.prototype.incrementReferences = function () {
  19920. this._references++;
  19921. };
  19922. InternalTexture.prototype.updateSize = function (width, height) {
  19923. this.width = width;
  19924. this.height = height;
  19925. this._size = width * height;
  19926. this.baseWidth = width;
  19927. this.baseHeight = height;
  19928. };
  19929. InternalTexture.prototype._rebuild = function () {
  19930. var _this = this;
  19931. var proxy;
  19932. this.isReady = false;
  19933. this._cachedCoordinatesMode = null;
  19934. this._cachedWrapU = null;
  19935. this._cachedWrapV = null;
  19936. this._cachedAnisotropicFilteringLevel = null;
  19937. switch (this._dataSource) {
  19938. case InternalTexture.DATASOURCE_TEMP:
  19939. return;
  19940. case InternalTexture.DATASOURCE_URL:
  19941. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  19942. _this.isReady = true;
  19943. }, null, this._buffer, null, this.format);
  19944. proxy._swapAndDie(this);
  19945. return;
  19946. case InternalTexture.DATASOURCE_RAW:
  19947. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  19948. proxy._swapAndDie(this);
  19949. this.isReady = true;
  19950. return;
  19951. case InternalTexture.DATASOURCE_DYNAMIC:
  19952. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  19953. proxy._swapAndDie(this);
  19954. // The engine will make sure to update content so no need to flag it as isReady = true
  19955. return;
  19956. case InternalTexture.DATASOURCE_RENDERTARGET:
  19957. var options = new BABYLON.RenderTargetCreationOptions();
  19958. options.generateDepthBuffer = this._generateDepthBuffer;
  19959. options.generateMipMaps = this.generateMipMaps;
  19960. options.generateStencilBuffer = this._generateStencilBuffer;
  19961. options.samplingMode = this.samplingMode;
  19962. options.type = this.type;
  19963. if (this.isCube) {
  19964. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  19965. }
  19966. else {
  19967. var size = {
  19968. width: this.width,
  19969. height: this.height
  19970. };
  19971. proxy = this._engine.createRenderTargetTexture(size, options);
  19972. }
  19973. proxy._swapAndDie(this);
  19974. this.isReady = true;
  19975. return;
  19976. case InternalTexture.DATASOURCE_CUBE:
  19977. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  19978. _this.isReady = true;
  19979. }, null, this.format, this._extension);
  19980. proxy._swapAndDie(this);
  19981. return;
  19982. case InternalTexture.DATASOURCE_CUBERAW:
  19983. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  19984. proxy._swapAndDie(this);
  19985. this.isReady = true;
  19986. return;
  19987. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  19988. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  19989. proxy._swapAndDie(_this);
  19990. _this.isReady = true;
  19991. }, null, this.format, this._extension);
  19992. return;
  19993. }
  19994. };
  19995. InternalTexture.prototype._swapAndDie = function (target) {
  19996. target._webGLTexture = this._webGLTexture;
  19997. if (this._framebuffer) {
  19998. target._framebuffer = this._framebuffer;
  19999. }
  20000. if (this._depthStencilBuffer) {
  20001. target._depthStencilBuffer = this._depthStencilBuffer;
  20002. }
  20003. if (this._lodTextureHigh) {
  20004. if (target._lodTextureHigh) {
  20005. target._lodTextureHigh.dispose();
  20006. }
  20007. target._lodTextureHigh = this._lodTextureHigh;
  20008. }
  20009. if (this._lodTextureMid) {
  20010. if (target._lodTextureMid) {
  20011. target._lodTextureMid.dispose();
  20012. }
  20013. target._lodTextureMid = this._lodTextureMid;
  20014. }
  20015. if (this._lodTextureLow) {
  20016. if (target._lodTextureLow) {
  20017. target._lodTextureLow.dispose();
  20018. }
  20019. target._lodTextureLow = this._lodTextureLow;
  20020. }
  20021. var cache = this._engine.getLoadedTexturesCache();
  20022. var index = cache.indexOf(this);
  20023. if (index !== -1) {
  20024. cache.splice(index, 1);
  20025. }
  20026. };
  20027. InternalTexture.prototype.dispose = function () {
  20028. if (!this._webGLTexture) {
  20029. return;
  20030. }
  20031. this._references--;
  20032. if (this._references === 0) {
  20033. this._engine._releaseTexture(this);
  20034. this._webGLTexture = null;
  20035. }
  20036. };
  20037. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20038. InternalTexture.DATASOURCE_URL = 1;
  20039. InternalTexture.DATASOURCE_TEMP = 2;
  20040. InternalTexture.DATASOURCE_RAW = 3;
  20041. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20042. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20043. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20044. InternalTexture.DATASOURCE_CUBE = 7;
  20045. InternalTexture.DATASOURCE_CUBERAW = 8;
  20046. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20047. return InternalTexture;
  20048. }());
  20049. BABYLON.InternalTexture = InternalTexture;
  20050. })(BABYLON || (BABYLON = {}));
  20051. //# sourceMappingURL=babylon.internalTexture.js.map
  20052. var BABYLON;
  20053. (function (BABYLON) {
  20054. var BaseTexture = (function () {
  20055. function BaseTexture(scene) {
  20056. this._hasAlpha = false;
  20057. this.getAlphaFromRGB = false;
  20058. this.level = 1;
  20059. this.coordinatesIndex = 0;
  20060. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20061. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20062. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20063. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20064. this.isCube = false;
  20065. this.gammaSpace = true;
  20066. this.invertZ = false;
  20067. this.lodLevelInAlpha = false;
  20068. this.lodGenerationOffset = 0.0;
  20069. this.lodGenerationScale = 0.8;
  20070. this.isRenderTarget = false;
  20071. this.animations = new Array();
  20072. /**
  20073. * An event triggered when the texture is disposed.
  20074. * @type {BABYLON.Observable}
  20075. */
  20076. this.onDisposeObservable = new BABYLON.Observable();
  20077. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20078. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20079. this._scene.textures.push(this);
  20080. this._uid = null;
  20081. }
  20082. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20083. get: function () {
  20084. return this._hasAlpha;
  20085. },
  20086. set: function (value) {
  20087. if (this._hasAlpha === value) {
  20088. return;
  20089. }
  20090. this._hasAlpha = value;
  20091. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20092. },
  20093. enumerable: true,
  20094. configurable: true
  20095. });
  20096. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20097. get: function () {
  20098. return this._coordinatesMode;
  20099. },
  20100. set: function (value) {
  20101. if (this._coordinatesMode === value) {
  20102. return;
  20103. }
  20104. this._coordinatesMode = value;
  20105. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20106. },
  20107. enumerable: true,
  20108. configurable: true
  20109. });
  20110. Object.defineProperty(BaseTexture.prototype, "uid", {
  20111. get: function () {
  20112. if (!this._uid) {
  20113. this._uid = BABYLON.Tools.RandomId();
  20114. }
  20115. return this._uid;
  20116. },
  20117. enumerable: true,
  20118. configurable: true
  20119. });
  20120. BaseTexture.prototype.toString = function () {
  20121. return this.name;
  20122. };
  20123. BaseTexture.prototype.getClassName = function () {
  20124. return "BaseTexture";
  20125. };
  20126. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20127. set: function (callback) {
  20128. if (this._onDisposeObserver) {
  20129. this.onDisposeObservable.remove(this._onDisposeObserver);
  20130. }
  20131. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20132. },
  20133. enumerable: true,
  20134. configurable: true
  20135. });
  20136. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20137. get: function () {
  20138. return true;
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. BaseTexture.prototype.getScene = function () {
  20144. return this._scene;
  20145. };
  20146. BaseTexture.prototype.getTextureMatrix = function () {
  20147. return null;
  20148. };
  20149. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20150. return null;
  20151. };
  20152. BaseTexture.prototype.getInternalTexture = function () {
  20153. return this._texture;
  20154. };
  20155. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20156. return !this.isBlocking || this.isReady();
  20157. };
  20158. BaseTexture.prototype.isReady = function () {
  20159. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20160. this.delayLoad();
  20161. return false;
  20162. }
  20163. if (this._texture) {
  20164. return this._texture.isReady;
  20165. }
  20166. return false;
  20167. };
  20168. BaseTexture.prototype.getSize = function () {
  20169. if (this._texture.width) {
  20170. return new BABYLON.Size(this._texture.width, this._texture.height);
  20171. }
  20172. if (this._texture._size) {
  20173. return new BABYLON.Size(this._texture._size, this._texture._size);
  20174. }
  20175. return BABYLON.Size.Zero();
  20176. };
  20177. BaseTexture.prototype.getBaseSize = function () {
  20178. if (!this.isReady() || !this._texture)
  20179. return BABYLON.Size.Zero();
  20180. if (this._texture._size) {
  20181. return new BABYLON.Size(this._texture._size, this._texture._size);
  20182. }
  20183. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20184. };
  20185. BaseTexture.prototype.scale = function (ratio) {
  20186. };
  20187. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20188. get: function () {
  20189. return false;
  20190. },
  20191. enumerable: true,
  20192. configurable: true
  20193. });
  20194. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20195. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20196. for (var index = 0; index < texturesCache.length; index++) {
  20197. var texturesCacheEntry = texturesCache[index];
  20198. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20199. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20200. texturesCacheEntry.incrementReferences();
  20201. return texturesCacheEntry;
  20202. }
  20203. }
  20204. }
  20205. return null;
  20206. };
  20207. BaseTexture.prototype._rebuild = function () {
  20208. };
  20209. BaseTexture.prototype.delayLoad = function () {
  20210. };
  20211. BaseTexture.prototype.clone = function () {
  20212. return null;
  20213. };
  20214. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20215. get: function () {
  20216. if (!this._texture) {
  20217. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20218. }
  20219. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20220. },
  20221. enumerable: true,
  20222. configurable: true
  20223. });
  20224. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20225. get: function () {
  20226. if (!this._texture) {
  20227. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20228. }
  20229. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20230. },
  20231. enumerable: true,
  20232. configurable: true
  20233. });
  20234. BaseTexture.prototype.readPixels = function (faceIndex) {
  20235. if (faceIndex === void 0) { faceIndex = 0; }
  20236. if (!this._texture) {
  20237. return null;
  20238. }
  20239. var size = this.getSize();
  20240. var engine = this.getScene().getEngine();
  20241. if (this._texture.isCube) {
  20242. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20243. }
  20244. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20245. };
  20246. BaseTexture.prototype.releaseInternalTexture = function () {
  20247. if (this._texture) {
  20248. this._texture.dispose();
  20249. this._texture = null;
  20250. }
  20251. };
  20252. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20253. get: function () {
  20254. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20255. return null;
  20256. }
  20257. if (!this._texture._sphericalPolynomial) {
  20258. this._texture._sphericalPolynomial =
  20259. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20260. }
  20261. return this._texture._sphericalPolynomial;
  20262. },
  20263. set: function (value) {
  20264. if (this._texture) {
  20265. this._texture._sphericalPolynomial = value;
  20266. }
  20267. },
  20268. enumerable: true,
  20269. configurable: true
  20270. });
  20271. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20272. get: function () {
  20273. if (this._texture) {
  20274. return this._texture._lodTextureHigh;
  20275. }
  20276. return null;
  20277. },
  20278. enumerable: true,
  20279. configurable: true
  20280. });
  20281. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20282. get: function () {
  20283. if (this._texture) {
  20284. return this._texture._lodTextureMid;
  20285. }
  20286. return null;
  20287. },
  20288. enumerable: true,
  20289. configurable: true
  20290. });
  20291. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20292. get: function () {
  20293. if (this._texture) {
  20294. return this._texture._lodTextureLow;
  20295. }
  20296. return null;
  20297. },
  20298. enumerable: true,
  20299. configurable: true
  20300. });
  20301. BaseTexture.prototype.dispose = function () {
  20302. // Animations
  20303. this.getScene().stopAnimation(this);
  20304. // Remove from scene
  20305. this._scene._removePendingData(this);
  20306. var index = this._scene.textures.indexOf(this);
  20307. if (index >= 0) {
  20308. this._scene.textures.splice(index, 1);
  20309. }
  20310. if (this._texture === undefined) {
  20311. return;
  20312. }
  20313. // Release
  20314. this.releaseInternalTexture();
  20315. // Callback
  20316. this.onDisposeObservable.notifyObservers(this);
  20317. this.onDisposeObservable.clear();
  20318. };
  20319. BaseTexture.prototype.serialize = function () {
  20320. if (!this.name) {
  20321. return null;
  20322. }
  20323. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20324. // Animations
  20325. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20326. return serializationObject;
  20327. };
  20328. BaseTexture.WhenAllReady = function (textures, callback) {
  20329. var numRemaining = textures.length;
  20330. if (numRemaining === 0) {
  20331. callback();
  20332. return;
  20333. }
  20334. var _loop_1 = function () {
  20335. texture = textures[i];
  20336. if (texture.isReady()) {
  20337. if (--numRemaining === 0) {
  20338. callback();
  20339. }
  20340. }
  20341. else {
  20342. onLoadObservable = texture.onLoadObservable;
  20343. var onLoadCallback_1 = function () {
  20344. onLoadObservable.removeCallback(onLoadCallback_1);
  20345. if (--numRemaining === 0) {
  20346. callback();
  20347. }
  20348. };
  20349. onLoadObservable.add(onLoadCallback_1);
  20350. }
  20351. };
  20352. var texture, onLoadObservable;
  20353. for (var i = 0; i < textures.length; i++) {
  20354. _loop_1();
  20355. }
  20356. };
  20357. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20358. __decorate([
  20359. BABYLON.serialize()
  20360. ], BaseTexture.prototype, "name", void 0);
  20361. __decorate([
  20362. BABYLON.serialize("hasAlpha")
  20363. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20364. __decorate([
  20365. BABYLON.serialize()
  20366. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20367. __decorate([
  20368. BABYLON.serialize()
  20369. ], BaseTexture.prototype, "level", void 0);
  20370. __decorate([
  20371. BABYLON.serialize()
  20372. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20373. __decorate([
  20374. BABYLON.serialize("coordinatesMode")
  20375. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20376. __decorate([
  20377. BABYLON.serialize()
  20378. ], BaseTexture.prototype, "wrapU", void 0);
  20379. __decorate([
  20380. BABYLON.serialize()
  20381. ], BaseTexture.prototype, "wrapV", void 0);
  20382. __decorate([
  20383. BABYLON.serialize()
  20384. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20385. __decorate([
  20386. BABYLON.serialize()
  20387. ], BaseTexture.prototype, "isCube", void 0);
  20388. __decorate([
  20389. BABYLON.serialize()
  20390. ], BaseTexture.prototype, "gammaSpace", void 0);
  20391. __decorate([
  20392. BABYLON.serialize()
  20393. ], BaseTexture.prototype, "invertZ", void 0);
  20394. __decorate([
  20395. BABYLON.serialize()
  20396. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20397. __decorate([
  20398. BABYLON.serialize()
  20399. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20400. __decorate([
  20401. BABYLON.serialize()
  20402. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20403. __decorate([
  20404. BABYLON.serialize()
  20405. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20406. return BaseTexture;
  20407. }());
  20408. BABYLON.BaseTexture = BaseTexture;
  20409. })(BABYLON || (BABYLON = {}));
  20410. //# sourceMappingURL=babylon.baseTexture.js.map
  20411. var BABYLON;
  20412. (function (BABYLON) {
  20413. var Texture = (function (_super) {
  20414. __extends(Texture, _super);
  20415. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20416. if (noMipmap === void 0) { noMipmap = false; }
  20417. if (invertY === void 0) { invertY = true; }
  20418. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20419. if (onLoad === void 0) { onLoad = null; }
  20420. if (onError === void 0) { onError = null; }
  20421. if (buffer === void 0) { buffer = null; }
  20422. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20423. var _this = _super.call(this, scene) || this;
  20424. _this.uOffset = 0;
  20425. _this.vOffset = 0;
  20426. _this.uScale = 1.0;
  20427. _this.vScale = 1.0;
  20428. _this.uAng = 0;
  20429. _this.vAng = 0;
  20430. _this.wAng = 0;
  20431. _this._isBlocking = true;
  20432. _this.name = url;
  20433. _this.url = url;
  20434. _this._noMipmap = noMipmap;
  20435. _this._invertY = invertY;
  20436. _this._samplingMode = samplingMode;
  20437. _this._buffer = buffer;
  20438. _this._deleteBuffer = deleteBuffer;
  20439. _this._format = format;
  20440. scene = _this.getScene();
  20441. var load = function () {
  20442. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20443. _this.onLoadObservable.notifyObservers(_this);
  20444. }
  20445. if (onLoad) {
  20446. onLoad();
  20447. }
  20448. if (!_this.isBlocking) {
  20449. scene.resetCachedMaterial();
  20450. }
  20451. };
  20452. if (!url) {
  20453. _this._delayedOnLoad = load;
  20454. _this._delayedOnError = onError;
  20455. return _this;
  20456. }
  20457. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20458. if (!_this._texture) {
  20459. if (!scene.useDelayedTextureLoading) {
  20460. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20461. if (deleteBuffer) {
  20462. delete _this._buffer;
  20463. }
  20464. }
  20465. else {
  20466. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20467. _this._delayedOnLoad = load;
  20468. _this._delayedOnError = onError;
  20469. }
  20470. }
  20471. else {
  20472. if (_this._texture.isReady) {
  20473. BABYLON.Tools.SetImmediate(function () { return load(); });
  20474. }
  20475. else {
  20476. _this._texture.onLoadedObservable.add(load);
  20477. }
  20478. }
  20479. return _this;
  20480. }
  20481. Object.defineProperty(Texture.prototype, "noMipmap", {
  20482. get: function () {
  20483. return this._noMipmap;
  20484. },
  20485. enumerable: true,
  20486. configurable: true
  20487. });
  20488. Object.defineProperty(Texture.prototype, "isBlocking", {
  20489. get: function () {
  20490. return this._isBlocking;
  20491. },
  20492. set: function (value) {
  20493. this._isBlocking = value;
  20494. },
  20495. enumerable: true,
  20496. configurable: true
  20497. });
  20498. Object.defineProperty(Texture.prototype, "samplingMode", {
  20499. get: function () {
  20500. return this._samplingMode;
  20501. },
  20502. enumerable: true,
  20503. configurable: true
  20504. });
  20505. Texture.prototype.updateURL = function (url) {
  20506. this.url = url;
  20507. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20508. this.delayLoad();
  20509. };
  20510. Texture.prototype.delayLoad = function () {
  20511. var _this = this;
  20512. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20513. return;
  20514. }
  20515. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20516. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20517. if (!this._texture) {
  20518. 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);
  20519. if (this._deleteBuffer) {
  20520. delete this._buffer;
  20521. }
  20522. }
  20523. else {
  20524. if (this._texture.isReady) {
  20525. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20526. }
  20527. else {
  20528. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  20529. }
  20530. }
  20531. };
  20532. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20533. if (!this._texture) {
  20534. return;
  20535. }
  20536. this._samplingMode = samplingMode;
  20537. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20538. };
  20539. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20540. x *= this.uScale;
  20541. y *= this.vScale;
  20542. x -= 0.5 * this.uScale;
  20543. y -= 0.5 * this.vScale;
  20544. z -= 0.5;
  20545. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20546. t.x += 0.5 * this.uScale + this.uOffset;
  20547. t.y += 0.5 * this.vScale + this.vOffset;
  20548. t.z += 0.5;
  20549. };
  20550. Texture.prototype.getTextureMatrix = function () {
  20551. var _this = this;
  20552. if (this.uOffset === this._cachedUOffset &&
  20553. this.vOffset === this._cachedVOffset &&
  20554. this.uScale === this._cachedUScale &&
  20555. this.vScale === this._cachedVScale &&
  20556. this.uAng === this._cachedUAng &&
  20557. this.vAng === this._cachedVAng &&
  20558. this.wAng === this._cachedWAng) {
  20559. return this._cachedTextureMatrix;
  20560. }
  20561. this._cachedUOffset = this.uOffset;
  20562. this._cachedVOffset = this.vOffset;
  20563. this._cachedUScale = this.uScale;
  20564. this._cachedVScale = this.vScale;
  20565. this._cachedUAng = this.uAng;
  20566. this._cachedVAng = this.vAng;
  20567. this._cachedWAng = this.wAng;
  20568. if (!this._cachedTextureMatrix) {
  20569. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20570. this._rowGenerationMatrix = new BABYLON.Matrix();
  20571. this._t0 = BABYLON.Vector3.Zero();
  20572. this._t1 = BABYLON.Vector3.Zero();
  20573. this._t2 = BABYLON.Vector3.Zero();
  20574. }
  20575. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20576. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20577. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20578. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20579. this._t1.subtractInPlace(this._t0);
  20580. this._t2.subtractInPlace(this._t0);
  20581. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20582. this._cachedTextureMatrix.m[0] = this._t1.x;
  20583. this._cachedTextureMatrix.m[1] = this._t1.y;
  20584. this._cachedTextureMatrix.m[2] = this._t1.z;
  20585. this._cachedTextureMatrix.m[4] = this._t2.x;
  20586. this._cachedTextureMatrix.m[5] = this._t2.y;
  20587. this._cachedTextureMatrix.m[6] = this._t2.z;
  20588. this._cachedTextureMatrix.m[8] = this._t0.x;
  20589. this._cachedTextureMatrix.m[9] = this._t0.y;
  20590. this._cachedTextureMatrix.m[10] = this._t0.z;
  20591. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20592. return mat.hasTexture(_this);
  20593. });
  20594. return this._cachedTextureMatrix;
  20595. };
  20596. Texture.prototype.getReflectionTextureMatrix = function () {
  20597. var _this = this;
  20598. var scene = this.getScene();
  20599. if (this.uOffset === this._cachedUOffset &&
  20600. this.vOffset === this._cachedVOffset &&
  20601. this.uScale === this._cachedUScale &&
  20602. this.vScale === this._cachedVScale &&
  20603. this.coordinatesMode === this._cachedCoordinatesMode) {
  20604. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  20605. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  20606. return this._cachedTextureMatrix;
  20607. }
  20608. }
  20609. else {
  20610. return this._cachedTextureMatrix;
  20611. }
  20612. }
  20613. if (!this._cachedTextureMatrix) {
  20614. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20615. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20616. }
  20617. this._cachedUOffset = this.uOffset;
  20618. this._cachedVOffset = this.vOffset;
  20619. this._cachedUScale = this.uScale;
  20620. this._cachedVScale = this.vScale;
  20621. this._cachedCoordinatesMode = this.coordinatesMode;
  20622. switch (this.coordinatesMode) {
  20623. case Texture.PLANAR_MODE:
  20624. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20625. this._cachedTextureMatrix[0] = this.uScale;
  20626. this._cachedTextureMatrix[5] = this.vScale;
  20627. this._cachedTextureMatrix[12] = this.uOffset;
  20628. this._cachedTextureMatrix[13] = this.vOffset;
  20629. break;
  20630. case Texture.PROJECTION_MODE:
  20631. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20632. this._projectionModeMatrix.m[0] = 0.5;
  20633. this._projectionModeMatrix.m[5] = -0.5;
  20634. this._projectionModeMatrix.m[10] = 0.0;
  20635. this._projectionModeMatrix.m[12] = 0.5;
  20636. this._projectionModeMatrix.m[13] = 0.5;
  20637. this._projectionModeMatrix.m[14] = 1.0;
  20638. this._projectionModeMatrix.m[15] = 1.0;
  20639. var projectionMatrix = scene.getProjectionMatrix();
  20640. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  20641. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20642. break;
  20643. default:
  20644. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20645. break;
  20646. }
  20647. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20648. return (mat.getActiveTextures().indexOf(_this) !== -1);
  20649. });
  20650. return this._cachedTextureMatrix;
  20651. };
  20652. Texture.prototype.clone = function () {
  20653. var _this = this;
  20654. return BABYLON.SerializationHelper.Clone(function () {
  20655. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20656. }, this);
  20657. };
  20658. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  20659. get: function () {
  20660. if (!this._onLoadObservable) {
  20661. this._onLoadObservable = new BABYLON.Observable();
  20662. }
  20663. return this._onLoadObservable;
  20664. },
  20665. enumerable: true,
  20666. configurable: true
  20667. });
  20668. Texture.prototype.serialize = function () {
  20669. var serializationObject = _super.prototype.serialize.call(this);
  20670. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  20671. serializationObject.base64String = this._buffer;
  20672. serializationObject.name = serializationObject.name.replace("data:", "");
  20673. }
  20674. return serializationObject;
  20675. };
  20676. Texture.prototype.getClassName = function () {
  20677. return "Texture";
  20678. };
  20679. Texture.prototype.dispose = function () {
  20680. _super.prototype.dispose.call(this);
  20681. if (this.onLoadObservable) {
  20682. this.onLoadObservable.clear();
  20683. this._onLoadObservable = null;
  20684. }
  20685. this._delayedOnLoad = null;
  20686. this._delayedOnError = null;
  20687. };
  20688. // Statics
  20689. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20690. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20691. if (onLoad === void 0) { onLoad = null; }
  20692. if (onError === void 0) { onError = null; }
  20693. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20694. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  20695. };
  20696. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20697. if (parsedTexture.customType) {
  20698. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  20699. // Update Sampling Mode
  20700. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  20701. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  20702. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  20703. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  20704. }
  20705. }
  20706. return parsedCustomTexture;
  20707. }
  20708. if (parsedTexture.isCube) {
  20709. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20710. }
  20711. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20712. return null;
  20713. }
  20714. var texture = BABYLON.SerializationHelper.Parse(function () {
  20715. if (parsedTexture.mirrorPlane) {
  20716. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20717. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20718. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20719. return mirrorTexture;
  20720. }
  20721. else if (parsedTexture.isRenderTarget) {
  20722. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20723. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20724. return renderTargetTexture;
  20725. }
  20726. else {
  20727. var texture;
  20728. if (parsedTexture.base64String) {
  20729. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20730. }
  20731. else {
  20732. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20733. }
  20734. return texture;
  20735. }
  20736. }, parsedTexture, scene);
  20737. // Update Sampling Mode
  20738. if (parsedTexture.samplingMode) {
  20739. var sampling = parsedTexture.samplingMode;
  20740. if (texture._samplingMode !== sampling) {
  20741. texture.updateSamplingMode(sampling);
  20742. }
  20743. }
  20744. // Animations
  20745. if (parsedTexture.animations) {
  20746. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20747. var parsedAnimation = parsedTexture.animations[animationIndex];
  20748. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20749. }
  20750. }
  20751. return texture;
  20752. };
  20753. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20754. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20755. if (noMipmap === void 0) { noMipmap = false; }
  20756. if (invertY === void 0) { invertY = true; }
  20757. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20758. if (onLoad === void 0) { onLoad = null; }
  20759. if (onError === void 0) { onError = null; }
  20760. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20761. if (name.substr(0, 5) !== "data:") {
  20762. name = "data:" + name;
  20763. }
  20764. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  20765. };
  20766. // Constants
  20767. Texture.NEAREST_SAMPLINGMODE = 1;
  20768. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  20769. Texture.BILINEAR_SAMPLINGMODE = 2;
  20770. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  20771. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20772. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  20773. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  20774. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  20775. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  20776. Texture.NEAREST_LINEAR = 7;
  20777. Texture.NEAREST_NEAREST = 8;
  20778. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  20779. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  20780. Texture.LINEAR_LINEAR = 11;
  20781. Texture.LINEAR_NEAREST = 12;
  20782. Texture.EXPLICIT_MODE = 0;
  20783. Texture.SPHERICAL_MODE = 1;
  20784. Texture.PLANAR_MODE = 2;
  20785. Texture.CUBIC_MODE = 3;
  20786. Texture.PROJECTION_MODE = 4;
  20787. Texture.SKYBOX_MODE = 5;
  20788. Texture.INVCUBIC_MODE = 6;
  20789. Texture.EQUIRECTANGULAR_MODE = 7;
  20790. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20791. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  20792. Texture.CLAMP_ADDRESSMODE = 0;
  20793. Texture.WRAP_ADDRESSMODE = 1;
  20794. Texture.MIRROR_ADDRESSMODE = 2;
  20795. __decorate([
  20796. BABYLON.serialize()
  20797. ], Texture.prototype, "url", void 0);
  20798. __decorate([
  20799. BABYLON.serialize()
  20800. ], Texture.prototype, "uOffset", void 0);
  20801. __decorate([
  20802. BABYLON.serialize()
  20803. ], Texture.prototype, "vOffset", void 0);
  20804. __decorate([
  20805. BABYLON.serialize()
  20806. ], Texture.prototype, "uScale", void 0);
  20807. __decorate([
  20808. BABYLON.serialize()
  20809. ], Texture.prototype, "vScale", void 0);
  20810. __decorate([
  20811. BABYLON.serialize()
  20812. ], Texture.prototype, "uAng", void 0);
  20813. __decorate([
  20814. BABYLON.serialize()
  20815. ], Texture.prototype, "vAng", void 0);
  20816. __decorate([
  20817. BABYLON.serialize()
  20818. ], Texture.prototype, "wAng", void 0);
  20819. __decorate([
  20820. BABYLON.serialize()
  20821. ], Texture.prototype, "isBlocking", null);
  20822. return Texture;
  20823. }(BABYLON.BaseTexture));
  20824. BABYLON.Texture = Texture;
  20825. })(BABYLON || (BABYLON = {}));
  20826. //# sourceMappingURL=babylon.texture.js.map
  20827. var BABYLON;
  20828. (function (BABYLON) {
  20829. var _InstancesBatch = (function () {
  20830. function _InstancesBatch() {
  20831. this.mustReturn = false;
  20832. this.visibleInstances = new Array();
  20833. this.renderSelf = new Array();
  20834. }
  20835. return _InstancesBatch;
  20836. }());
  20837. BABYLON._InstancesBatch = _InstancesBatch;
  20838. var Mesh = (function (_super) {
  20839. __extends(Mesh, _super);
  20840. /**
  20841. * @constructor
  20842. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  20843. * @param {Scene} scene The scene to add this mesh to.
  20844. * @param {Node} parent The parent of this mesh, if it has one
  20845. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  20846. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  20847. * When false, achieved by calling a clone(), also passing False.
  20848. * This will make creation of children, recursive.
  20849. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  20850. */
  20851. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  20852. if (parent === void 0) { parent = null; }
  20853. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20854. var _this = _super.call(this, name, scene) || this;
  20855. // Events
  20856. /**
  20857. * An event triggered before rendering the mesh
  20858. * @type {BABYLON.Observable}
  20859. */
  20860. _this.onBeforeRenderObservable = new BABYLON.Observable();
  20861. /**
  20862. * An event triggered after rendering the mesh
  20863. * @type {BABYLON.Observable}
  20864. */
  20865. _this.onAfterRenderObservable = new BABYLON.Observable();
  20866. /**
  20867. * An event triggered before drawing the mesh
  20868. * @type {BABYLON.Observable}
  20869. */
  20870. _this.onBeforeDrawObservable = new BABYLON.Observable();
  20871. // Members
  20872. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20873. _this.instances = new Array();
  20874. _this._LODLevels = new Array();
  20875. _this._visibleInstances = {};
  20876. _this._renderIdForInstances = new Array();
  20877. _this._batchCache = new _InstancesBatch();
  20878. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  20879. _this._sideOrientation = Mesh._DEFAULTSIDE;
  20880. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  20881. // Will be used to save a source mesh reference, If any
  20882. _this._source = null;
  20883. if (source) {
  20884. // Source mesh
  20885. _this._source = source;
  20886. // Geometry
  20887. if (source._geometry) {
  20888. source._geometry.applyToMesh(_this);
  20889. }
  20890. // Deep copy
  20891. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  20892. // Parent
  20893. _this.parent = source.parent;
  20894. // Pivot
  20895. _this.setPivotMatrix(source.getPivotMatrix());
  20896. _this.id = name + "." + source.id;
  20897. // Material
  20898. _this.material = source.material;
  20899. var index;
  20900. if (!doNotCloneChildren) {
  20901. // Children
  20902. for (index = 0; index < scene.meshes.length; index++) {
  20903. var mesh = scene.meshes[index];
  20904. if (mesh.parent === source) {
  20905. // doNotCloneChildren is always going to be False
  20906. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20907. }
  20908. }
  20909. }
  20910. // Physics clone
  20911. var physicsEngine = _this.getScene().getPhysicsEngine();
  20912. if (clonePhysicsImpostor && physicsEngine) {
  20913. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20914. if (impostor) {
  20915. _this.physicsImpostor = impostor.clone(_this);
  20916. }
  20917. }
  20918. // Particles
  20919. for (index = 0; index < scene.particleSystems.length; index++) {
  20920. var system = scene.particleSystems[index];
  20921. if (system.emitter === source) {
  20922. system.clone(system.name, _this);
  20923. }
  20924. }
  20925. _this.computeWorldMatrix(true);
  20926. }
  20927. // Parent
  20928. if (parent !== null) {
  20929. _this.parent = parent;
  20930. }
  20931. return _this;
  20932. }
  20933. Object.defineProperty(Mesh, "FRONTSIDE", {
  20934. /**
  20935. * Mesh side orientation : usually the external or front surface
  20936. */
  20937. get: function () {
  20938. return Mesh._FRONTSIDE;
  20939. },
  20940. enumerable: true,
  20941. configurable: true
  20942. });
  20943. Object.defineProperty(Mesh, "BACKSIDE", {
  20944. /**
  20945. * Mesh side orientation : usually the internal or back surface
  20946. */
  20947. get: function () {
  20948. return Mesh._BACKSIDE;
  20949. },
  20950. enumerable: true,
  20951. configurable: true
  20952. });
  20953. Object.defineProperty(Mesh, "DOUBLESIDE", {
  20954. /**
  20955. * Mesh side orientation : both internal and external or front and back surfaces
  20956. */
  20957. get: function () {
  20958. return Mesh._DOUBLESIDE;
  20959. },
  20960. enumerable: true,
  20961. configurable: true
  20962. });
  20963. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  20964. /**
  20965. * Mesh side orientation : by default, `FRONTSIDE`
  20966. */
  20967. get: function () {
  20968. return Mesh._DEFAULTSIDE;
  20969. },
  20970. enumerable: true,
  20971. configurable: true
  20972. });
  20973. Object.defineProperty(Mesh, "NO_CAP", {
  20974. /**
  20975. * Mesh cap setting : no cap
  20976. */
  20977. get: function () {
  20978. return Mesh._NO_CAP;
  20979. },
  20980. enumerable: true,
  20981. configurable: true
  20982. });
  20983. Object.defineProperty(Mesh, "CAP_START", {
  20984. /**
  20985. * Mesh cap setting : one cap at the beginning of the mesh
  20986. */
  20987. get: function () {
  20988. return Mesh._CAP_START;
  20989. },
  20990. enumerable: true,
  20991. configurable: true
  20992. });
  20993. Object.defineProperty(Mesh, "CAP_END", {
  20994. /**
  20995. * Mesh cap setting : one cap at the end of the mesh
  20996. */
  20997. get: function () {
  20998. return Mesh._CAP_END;
  20999. },
  21000. enumerable: true,
  21001. configurable: true
  21002. });
  21003. Object.defineProperty(Mesh, "CAP_ALL", {
  21004. /**
  21005. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21006. */
  21007. get: function () {
  21008. return Mesh._CAP_ALL;
  21009. },
  21010. enumerable: true,
  21011. configurable: true
  21012. });
  21013. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21014. set: function (callback) {
  21015. if (this._onBeforeDrawObserver) {
  21016. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21017. }
  21018. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21019. },
  21020. enumerable: true,
  21021. configurable: true
  21022. });
  21023. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21024. get: function () {
  21025. return this._morphTargetManager;
  21026. },
  21027. set: function (value) {
  21028. if (this._morphTargetManager === value) {
  21029. return;
  21030. }
  21031. this._morphTargetManager = value;
  21032. this._syncGeometryWithMorphTargetManager();
  21033. },
  21034. enumerable: true,
  21035. configurable: true
  21036. });
  21037. Object.defineProperty(Mesh.prototype, "source", {
  21038. get: function () {
  21039. return this._source;
  21040. },
  21041. enumerable: true,
  21042. configurable: true
  21043. });
  21044. // Methods
  21045. /**
  21046. * Returns the string "Mesh".
  21047. */
  21048. Mesh.prototype.getClassName = function () {
  21049. return "Mesh";
  21050. };
  21051. /**
  21052. * Returns a string.
  21053. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21054. */
  21055. Mesh.prototype.toString = function (fullDetails) {
  21056. var ret = _super.prototype.toString.call(this, fullDetails);
  21057. ret += ", n vertices: " + this.getTotalVertices();
  21058. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21059. if (this.animations) {
  21060. for (var i = 0; i < this.animations.length; i++) {
  21061. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21062. }
  21063. }
  21064. if (fullDetails) {
  21065. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21066. }
  21067. return ret;
  21068. };
  21069. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21070. /**
  21071. * True if the mesh has some Levels Of Details (LOD).
  21072. * Returns a boolean.
  21073. */
  21074. get: function () {
  21075. return this._LODLevels.length > 0;
  21076. },
  21077. enumerable: true,
  21078. configurable: true
  21079. });
  21080. Mesh.prototype._sortLODLevels = function () {
  21081. this._LODLevels.sort(function (a, b) {
  21082. if (a.distance < b.distance) {
  21083. return 1;
  21084. }
  21085. if (a.distance > b.distance) {
  21086. return -1;
  21087. }
  21088. return 0;
  21089. });
  21090. };
  21091. /**
  21092. * Add a mesh as LOD level triggered at the given distance.
  21093. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21094. * @param {number} distance The distance from the center of the object to show this level
  21095. * @param {Mesh} mesh The mesh to be added as LOD level
  21096. * @return {Mesh} This mesh (for chaining)
  21097. */
  21098. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21099. if (mesh && mesh._masterMesh) {
  21100. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21101. return this;
  21102. }
  21103. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21104. this._LODLevels.push(level);
  21105. if (mesh) {
  21106. mesh._masterMesh = this;
  21107. }
  21108. this._sortLODLevels();
  21109. return this;
  21110. };
  21111. /**
  21112. * Returns the LOD level mesh at the passed distance or null if not found.
  21113. * It is related to the method `addLODLevel(distance, mesh)`.
  21114. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21115. * Returns an object Mesh or `null`.
  21116. */
  21117. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21118. for (var index = 0; index < this._LODLevels.length; index++) {
  21119. var level = this._LODLevels[index];
  21120. if (level.distance === distance) {
  21121. return level.mesh;
  21122. }
  21123. }
  21124. return null;
  21125. };
  21126. /**
  21127. * Remove a mesh from the LOD array
  21128. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21129. * @param {Mesh} mesh The mesh to be removed.
  21130. * @return {Mesh} This mesh (for chaining)
  21131. */
  21132. Mesh.prototype.removeLODLevel = function (mesh) {
  21133. for (var index = 0; index < this._LODLevels.length; index++) {
  21134. if (this._LODLevels[index].mesh === mesh) {
  21135. this._LODLevels.splice(index, 1);
  21136. if (mesh) {
  21137. mesh._masterMesh = null;
  21138. }
  21139. }
  21140. }
  21141. this._sortLODLevels();
  21142. return this;
  21143. };
  21144. /**
  21145. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21146. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21147. */
  21148. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21149. if (!this._LODLevels || this._LODLevels.length === 0) {
  21150. return this;
  21151. }
  21152. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21153. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21154. if (this.onLODLevelSelection) {
  21155. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21156. }
  21157. return this;
  21158. }
  21159. for (var index = 0; index < this._LODLevels.length; index++) {
  21160. var level = this._LODLevels[index];
  21161. if (level.distance < distanceToCamera) {
  21162. if (level.mesh) {
  21163. level.mesh._preActivate();
  21164. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21165. }
  21166. if (this.onLODLevelSelection) {
  21167. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21168. }
  21169. return level.mesh;
  21170. }
  21171. }
  21172. if (this.onLODLevelSelection) {
  21173. this.onLODLevelSelection(distanceToCamera, this, this);
  21174. }
  21175. return this;
  21176. };
  21177. Object.defineProperty(Mesh.prototype, "geometry", {
  21178. /**
  21179. * Returns the mesh internal Geometry object.
  21180. */
  21181. get: function () {
  21182. return this._geometry;
  21183. },
  21184. enumerable: true,
  21185. configurable: true
  21186. });
  21187. /**
  21188. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21189. */
  21190. Mesh.prototype.getTotalVertices = function () {
  21191. if (!this._geometry) {
  21192. return 0;
  21193. }
  21194. return this._geometry.getTotalVertices();
  21195. };
  21196. /**
  21197. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21198. * 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.
  21199. * You can force the copy with forceCopy === true
  21200. * Returns null if the mesh has no geometry or no vertex buffer.
  21201. * Possible `kind` values :
  21202. * - BABYLON.VertexBuffer.PositionKind
  21203. * - BABYLON.VertexBuffer.UVKind
  21204. * - BABYLON.VertexBuffer.UV2Kind
  21205. * - BABYLON.VertexBuffer.UV3Kind
  21206. * - BABYLON.VertexBuffer.UV4Kind
  21207. * - BABYLON.VertexBuffer.UV5Kind
  21208. * - BABYLON.VertexBuffer.UV6Kind
  21209. * - BABYLON.VertexBuffer.ColorKind
  21210. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21211. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21212. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21213. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21214. */
  21215. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21216. if (!this._geometry) {
  21217. return null;
  21218. }
  21219. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21220. };
  21221. /**
  21222. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21223. * Returns `undefined` if the mesh has no geometry.
  21224. * Possible `kind` values :
  21225. * - BABYLON.VertexBuffer.PositionKind
  21226. * - BABYLON.VertexBuffer.UVKind
  21227. * - BABYLON.VertexBuffer.UV2Kind
  21228. * - BABYLON.VertexBuffer.UV3Kind
  21229. * - BABYLON.VertexBuffer.UV4Kind
  21230. * - BABYLON.VertexBuffer.UV5Kind
  21231. * - BABYLON.VertexBuffer.UV6Kind
  21232. * - BABYLON.VertexBuffer.ColorKind
  21233. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21234. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21235. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21236. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21237. */
  21238. Mesh.prototype.getVertexBuffer = function (kind) {
  21239. if (!this._geometry) {
  21240. return undefined;
  21241. }
  21242. return this._geometry.getVertexBuffer(kind);
  21243. };
  21244. /**
  21245. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21246. * Possible `kind` values :
  21247. * - BABYLON.VertexBuffer.PositionKind
  21248. * - BABYLON.VertexBuffer.UVKind
  21249. * - BABYLON.VertexBuffer.UV2Kind
  21250. * - BABYLON.VertexBuffer.UV3Kind
  21251. * - BABYLON.VertexBuffer.UV4Kind
  21252. * - BABYLON.VertexBuffer.UV5Kind
  21253. * - BABYLON.VertexBuffer.UV6Kind
  21254. * - BABYLON.VertexBuffer.ColorKind
  21255. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21256. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21257. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21258. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21259. */
  21260. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21261. if (!this._geometry) {
  21262. if (this._delayInfo) {
  21263. return this._delayInfo.indexOf(kind) !== -1;
  21264. }
  21265. return false;
  21266. }
  21267. return this._geometry.isVerticesDataPresent(kind);
  21268. };
  21269. /**
  21270. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21271. * Possible `kind` values :
  21272. * - BABYLON.VertexBuffer.PositionKind
  21273. * - BABYLON.VertexBuffer.UVKind
  21274. * - BABYLON.VertexBuffer.UV2Kind
  21275. * - BABYLON.VertexBuffer.UV3Kind
  21276. * - BABYLON.VertexBuffer.UV4Kind
  21277. * - BABYLON.VertexBuffer.UV5Kind
  21278. * - BABYLON.VertexBuffer.UV6Kind
  21279. * - BABYLON.VertexBuffer.ColorKind
  21280. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21281. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21282. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21283. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21284. */
  21285. Mesh.prototype.getVerticesDataKinds = function () {
  21286. if (!this._geometry) {
  21287. var result = [];
  21288. if (this._delayInfo) {
  21289. this._delayInfo.forEach(function (kind, index, array) {
  21290. result.push(kind);
  21291. });
  21292. }
  21293. return result;
  21294. }
  21295. return this._geometry.getVerticesDataKinds();
  21296. };
  21297. /**
  21298. * Returns a positive integer : the total number of indices in this mesh geometry.
  21299. * Returns zero if the mesh has no geometry.
  21300. */
  21301. Mesh.prototype.getTotalIndices = function () {
  21302. if (!this._geometry) {
  21303. return 0;
  21304. }
  21305. return this._geometry.getTotalIndices();
  21306. };
  21307. /**
  21308. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21309. * 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.
  21310. * Returns an empty array if the mesh has no geometry.
  21311. */
  21312. Mesh.prototype.getIndices = function (copyWhenShared) {
  21313. if (!this._geometry) {
  21314. return [];
  21315. }
  21316. return this._geometry.getIndices(copyWhenShared);
  21317. };
  21318. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21319. get: function () {
  21320. return this._masterMesh !== null && this._masterMesh !== undefined;
  21321. },
  21322. enumerable: true,
  21323. configurable: true
  21324. });
  21325. /**
  21326. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21327. */
  21328. Mesh.prototype.isReady = function () {
  21329. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21330. return false;
  21331. }
  21332. return _super.prototype.isReady.call(this);
  21333. };
  21334. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  21335. get: function () {
  21336. return this._sideOrientation;
  21337. },
  21338. /**
  21339. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  21340. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  21341. */
  21342. set: function (sideO) {
  21343. this._sideOrientation = sideO;
  21344. },
  21345. enumerable: true,
  21346. configurable: true
  21347. });
  21348. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21349. /**
  21350. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21351. * This property is pertinent only for updatable parametric shapes.
  21352. */
  21353. get: function () {
  21354. return this._areNormalsFrozen;
  21355. },
  21356. enumerable: true,
  21357. configurable: true
  21358. });
  21359. /**
  21360. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21361. * It has no effect at all on other shapes.
  21362. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21363. * Returns the Mesh.
  21364. */
  21365. Mesh.prototype.freezeNormals = function () {
  21366. this._areNormalsFrozen = true;
  21367. return this;
  21368. };
  21369. /**
  21370. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21371. * It has no effect at all on other shapes.
  21372. * It reactivates the mesh normals computation if it was previously frozen.
  21373. * Returns the Mesh.
  21374. */
  21375. Mesh.prototype.unfreezeNormals = function () {
  21376. this._areNormalsFrozen = false;
  21377. return this;
  21378. };
  21379. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21380. /**
  21381. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21382. */
  21383. set: function (count) {
  21384. this._overridenInstanceCount = count;
  21385. },
  21386. enumerable: true,
  21387. configurable: true
  21388. });
  21389. // Methods
  21390. Mesh.prototype._preActivate = function () {
  21391. var sceneRenderId = this.getScene().getRenderId();
  21392. if (this._preActivateId === sceneRenderId) {
  21393. return this;
  21394. }
  21395. this._preActivateId = sceneRenderId;
  21396. this._visibleInstances = null;
  21397. return this;
  21398. };
  21399. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21400. if (this._visibleInstances) {
  21401. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21402. }
  21403. return this;
  21404. };
  21405. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21406. if (!this._visibleInstances) {
  21407. this._visibleInstances = {};
  21408. this._visibleInstances.defaultRenderId = renderId;
  21409. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21410. }
  21411. if (!this._visibleInstances[renderId]) {
  21412. this._visibleInstances[renderId] = new Array();
  21413. }
  21414. this._visibleInstances[renderId].push(instance);
  21415. return this;
  21416. };
  21417. /**
  21418. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21419. * This means the mesh underlying bounding box and sphere are recomputed.
  21420. * Returns the Mesh.
  21421. */
  21422. Mesh.prototype.refreshBoundingInfo = function () {
  21423. if (this._boundingInfo.isLocked) {
  21424. return;
  21425. }
  21426. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21427. if (data) {
  21428. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21429. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21430. }
  21431. if (this.subMeshes) {
  21432. for (var index = 0; index < this.subMeshes.length; index++) {
  21433. this.subMeshes[index].refreshBoundingInfo();
  21434. }
  21435. }
  21436. this._updateBoundingInfo();
  21437. return this;
  21438. };
  21439. Mesh.prototype._createGlobalSubMesh = function (force) {
  21440. var totalVertices = this.getTotalVertices();
  21441. if (!totalVertices || !this.getIndices()) {
  21442. return null;
  21443. }
  21444. // Check if we need to recreate the submeshes
  21445. if (this.subMeshes && this.subMeshes.length > 0) {
  21446. var totalIndices = this.getIndices().length;
  21447. var needToRecreate = false;
  21448. if (force) {
  21449. needToRecreate = true;
  21450. }
  21451. else {
  21452. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21453. var submesh = _a[_i];
  21454. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21455. needToRecreate = true;
  21456. break;
  21457. }
  21458. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21459. needToRecreate = true;
  21460. break;
  21461. }
  21462. }
  21463. }
  21464. if (!needToRecreate) {
  21465. return;
  21466. }
  21467. }
  21468. this.releaseSubMeshes();
  21469. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21470. };
  21471. Mesh.prototype.subdivide = function (count) {
  21472. if (count < 1) {
  21473. return;
  21474. }
  21475. var totalIndices = this.getTotalIndices();
  21476. var subdivisionSize = (totalIndices / count) | 0;
  21477. var offset = 0;
  21478. // Ensure that subdivisionSize is a multiple of 3
  21479. while (subdivisionSize % 3 !== 0) {
  21480. subdivisionSize++;
  21481. }
  21482. this.releaseSubMeshes();
  21483. for (var index = 0; index < count; index++) {
  21484. if (offset >= totalIndices) {
  21485. break;
  21486. }
  21487. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21488. offset += subdivisionSize;
  21489. }
  21490. this.synchronizeInstances();
  21491. };
  21492. /**
  21493. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21494. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21495. * The `data` are either a numeric array either a Float32Array.
  21496. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21497. * 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).
  21498. * Note that a new underlying VertexBuffer object is created each call.
  21499. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21500. *
  21501. * Possible `kind` values :
  21502. * - BABYLON.VertexBuffer.PositionKind
  21503. * - BABYLON.VertexBuffer.UVKind
  21504. * - BABYLON.VertexBuffer.UV2Kind
  21505. * - BABYLON.VertexBuffer.UV3Kind
  21506. * - BABYLON.VertexBuffer.UV4Kind
  21507. * - BABYLON.VertexBuffer.UV5Kind
  21508. * - BABYLON.VertexBuffer.UV6Kind
  21509. * - BABYLON.VertexBuffer.ColorKind
  21510. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21511. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21512. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21513. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21514. *
  21515. * Returns the Mesh.
  21516. */
  21517. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21518. if (!this._geometry) {
  21519. var vertexData = new BABYLON.VertexData();
  21520. vertexData.set(data, kind);
  21521. var scene = this.getScene();
  21522. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21523. }
  21524. else {
  21525. this._geometry.setVerticesData(kind, data, updatable, stride);
  21526. }
  21527. return this;
  21528. };
  21529. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21530. if (updatable === void 0) { updatable = true; }
  21531. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21532. return;
  21533. }
  21534. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21535. };
  21536. /**
  21537. * Sets the mesh VertexBuffer.
  21538. * Returns the Mesh.
  21539. */
  21540. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21541. if (!this._geometry) {
  21542. var scene = this.getScene();
  21543. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21544. }
  21545. this._geometry.setVerticesBuffer(buffer);
  21546. return this;
  21547. };
  21548. /**
  21549. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21550. * If the mesh has no geometry, it is simply returned as it is.
  21551. * The `data` are either a numeric array either a Float32Array.
  21552. * No new underlying VertexBuffer object is created.
  21553. * 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.
  21554. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21555. *
  21556. * Possible `kind` values :
  21557. * - BABYLON.VertexBuffer.PositionKind
  21558. * - BABYLON.VertexBuffer.UVKind
  21559. * - BABYLON.VertexBuffer.UV2Kind
  21560. * - BABYLON.VertexBuffer.UV3Kind
  21561. * - BABYLON.VertexBuffer.UV4Kind
  21562. * - BABYLON.VertexBuffer.UV5Kind
  21563. * - BABYLON.VertexBuffer.UV6Kind
  21564. * - BABYLON.VertexBuffer.ColorKind
  21565. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21566. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21567. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21568. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21569. *
  21570. * Returns the Mesh.
  21571. */
  21572. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21573. if (!this._geometry) {
  21574. return;
  21575. }
  21576. if (!makeItUnique) {
  21577. this._geometry.updateVerticesData(kind, data, updateExtends);
  21578. }
  21579. else {
  21580. this.makeGeometryUnique();
  21581. this.updateVerticesData(kind, data, updateExtends, false);
  21582. }
  21583. return this;
  21584. };
  21585. /**
  21586. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21587. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21588. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21589. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21590. * Returns the Mesh.
  21591. */
  21592. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21593. if (computeNormals === void 0) { computeNormals = true; }
  21594. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21595. positionFunction(positions);
  21596. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21597. if (computeNormals) {
  21598. var indices = this.getIndices();
  21599. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21600. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21601. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21602. }
  21603. return this;
  21604. };
  21605. /**
  21606. * Creates a un-shared specific occurence of the geometry for the mesh.
  21607. * Returns the Mesh.
  21608. */
  21609. Mesh.prototype.makeGeometryUnique = function () {
  21610. if (!this._geometry) {
  21611. return;
  21612. }
  21613. var oldGeometry = this._geometry;
  21614. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21615. oldGeometry.releaseForMesh(this, true);
  21616. geometry.applyToMesh(this);
  21617. return this;
  21618. };
  21619. /**
  21620. * Sets the mesh indices.
  21621. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21622. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21623. * This method creates a new index buffer each call.
  21624. * Returns the Mesh.
  21625. */
  21626. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21627. if (!this._geometry) {
  21628. var vertexData = new BABYLON.VertexData();
  21629. vertexData.indices = indices;
  21630. var scene = this.getScene();
  21631. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21632. }
  21633. else {
  21634. this._geometry.setIndices(indices, totalVertices);
  21635. }
  21636. return this;
  21637. };
  21638. /**
  21639. * Invert the geometry to move from a right handed system to a left handed one.
  21640. * Returns the Mesh.
  21641. */
  21642. Mesh.prototype.toLeftHanded = function () {
  21643. if (!this._geometry) {
  21644. return;
  21645. }
  21646. this._geometry.toLeftHanded();
  21647. return this;
  21648. };
  21649. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21650. var engine = this.getScene().getEngine();
  21651. // Wireframe
  21652. var indexToBind;
  21653. if (this._unIndexed) {
  21654. indexToBind = null;
  21655. }
  21656. else {
  21657. switch (fillMode) {
  21658. case BABYLON.Material.PointFillMode:
  21659. indexToBind = null;
  21660. break;
  21661. case BABYLON.Material.WireFrameFillMode:
  21662. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21663. break;
  21664. default:
  21665. case BABYLON.Material.TriangleFillMode:
  21666. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21667. break;
  21668. }
  21669. }
  21670. // VBOs
  21671. this._geometry._bind(effect, indexToBind);
  21672. return this;
  21673. };
  21674. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21675. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21676. return this;
  21677. }
  21678. this.onBeforeDrawObservable.notifyObservers(this);
  21679. var engine = this.getScene().getEngine();
  21680. // Draw order
  21681. switch (fillMode) {
  21682. case BABYLON.Material.PointFillMode:
  21683. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21684. break;
  21685. case BABYLON.Material.WireFrameFillMode:
  21686. if (this._unIndexed) {
  21687. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21688. }
  21689. else {
  21690. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  21691. }
  21692. break;
  21693. default:
  21694. if (this._unIndexed) {
  21695. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21696. }
  21697. else {
  21698. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21699. }
  21700. }
  21701. return this;
  21702. };
  21703. /**
  21704. * Registers for this mesh a javascript function called just before the rendering process.
  21705. * This function is passed the current mesh.
  21706. * Return the Mesh.
  21707. */
  21708. Mesh.prototype.registerBeforeRender = function (func) {
  21709. this.onBeforeRenderObservable.add(func);
  21710. return this;
  21711. };
  21712. /**
  21713. * Disposes a previously registered javascript function called before the rendering.
  21714. * This function is passed the current mesh.
  21715. * Returns the Mesh.
  21716. */
  21717. Mesh.prototype.unregisterBeforeRender = function (func) {
  21718. this.onBeforeRenderObservable.removeCallback(func);
  21719. return this;
  21720. };
  21721. /**
  21722. * Registers for this mesh a javascript function called just after the rendering is complete.
  21723. * This function is passed the current mesh.
  21724. * Returns the Mesh.
  21725. */
  21726. Mesh.prototype.registerAfterRender = function (func) {
  21727. this.onAfterRenderObservable.add(func);
  21728. return this;
  21729. };
  21730. /**
  21731. * Disposes a previously registered javascript function called after the rendering.
  21732. * This function is passed the current mesh.
  21733. * Return the Mesh.
  21734. */
  21735. Mesh.prototype.unregisterAfterRender = function (func) {
  21736. this.onAfterRenderObservable.removeCallback(func);
  21737. return this;
  21738. };
  21739. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21740. var scene = this.getScene();
  21741. this._batchCache.mustReturn = false;
  21742. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21743. this._batchCache.visibleInstances[subMeshId] = null;
  21744. if (this._visibleInstances) {
  21745. var currentRenderId = scene.getRenderId();
  21746. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21747. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21748. var selfRenderId = this._renderId;
  21749. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21750. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21751. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21752. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21753. }
  21754. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21755. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21756. this._batchCache.mustReturn = true;
  21757. return this._batchCache;
  21758. }
  21759. if (currentRenderId !== selfRenderId) {
  21760. this._batchCache.renderSelf[subMeshId] = false;
  21761. }
  21762. }
  21763. this._renderIdForInstances[subMeshId] = currentRenderId;
  21764. }
  21765. return this._batchCache;
  21766. };
  21767. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21768. var visibleInstances = batch.visibleInstances[subMesh._id];
  21769. var matricesCount = visibleInstances.length + 1;
  21770. var bufferSize = matricesCount * 16 * 4;
  21771. var currentInstancesBufferSize = this._instancesBufferSize;
  21772. var instancesBuffer = this._instancesBuffer;
  21773. while (this._instancesBufferSize < bufferSize) {
  21774. this._instancesBufferSize *= 2;
  21775. }
  21776. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21777. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21778. }
  21779. var offset = 0;
  21780. var instancesCount = 0;
  21781. var world = this.getWorldMatrix();
  21782. if (batch.renderSelf[subMesh._id]) {
  21783. world.copyToArray(this._instancesData, offset);
  21784. offset += 16;
  21785. instancesCount++;
  21786. }
  21787. if (visibleInstances) {
  21788. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21789. var instance = visibleInstances[instanceIndex];
  21790. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21791. offset += 16;
  21792. instancesCount++;
  21793. }
  21794. }
  21795. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21796. if (instancesBuffer) {
  21797. instancesBuffer.dispose();
  21798. }
  21799. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21800. this._instancesBuffer = instancesBuffer;
  21801. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21802. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21803. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21804. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21805. }
  21806. else {
  21807. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21808. }
  21809. this._bind(subMesh, effect, fillMode);
  21810. this._draw(subMesh, fillMode, instancesCount);
  21811. engine.unbindInstanceAttributes();
  21812. return this;
  21813. };
  21814. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21815. var scene = this.getScene();
  21816. var engine = scene.getEngine();
  21817. if (hardwareInstancedRendering) {
  21818. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21819. }
  21820. else {
  21821. if (batch.renderSelf[subMesh._id]) {
  21822. // Draw
  21823. if (onBeforeDraw) {
  21824. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21825. }
  21826. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  21827. }
  21828. if (batch.visibleInstances[subMesh._id]) {
  21829. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21830. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21831. // World
  21832. var world = instance.getWorldMatrix();
  21833. if (onBeforeDraw) {
  21834. onBeforeDraw(true, world, effectiveMaterial);
  21835. }
  21836. // Draw
  21837. this._draw(subMesh, fillMode);
  21838. }
  21839. }
  21840. }
  21841. return this;
  21842. };
  21843. /**
  21844. * Triggers the draw call for the mesh.
  21845. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  21846. * Returns the Mesh.
  21847. */
  21848. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  21849. this.checkOcclusionQuery();
  21850. if (this._isOccluded) {
  21851. return;
  21852. }
  21853. var scene = this.getScene();
  21854. // Managing instances
  21855. var batch = this._getInstancesRenderList(subMesh._id);
  21856. if (batch.mustReturn) {
  21857. return this;
  21858. }
  21859. // Checking geometry state
  21860. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21861. return this;
  21862. }
  21863. var callbackIndex;
  21864. this.onBeforeRenderObservable.notifyObservers(this);
  21865. var engine = scene.getEngine();
  21866. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  21867. // Material
  21868. var effectiveMaterial = subMesh.getMaterial();
  21869. if (!effectiveMaterial) {
  21870. return this;
  21871. }
  21872. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21873. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  21874. return this;
  21875. }
  21876. }
  21877. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  21878. return this;
  21879. }
  21880. // Alpha mode
  21881. if (enableAlphaMode) {
  21882. engine.setAlphaMode(effectiveMaterial.alphaMode);
  21883. }
  21884. // Outline - step 1
  21885. var savedDepthWrite = engine.getDepthWrite();
  21886. if (this.renderOutline) {
  21887. engine.setDepthWrite(false);
  21888. scene.getOutlineRenderer().render(subMesh, batch);
  21889. engine.setDepthWrite(savedDepthWrite);
  21890. }
  21891. var effect;
  21892. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21893. effect = subMesh.effect;
  21894. }
  21895. else {
  21896. effect = effectiveMaterial.getEffect();
  21897. }
  21898. effectiveMaterial._preBind(effect);
  21899. // Bind
  21900. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  21901. if (!hardwareInstancedRendering) {
  21902. this._bind(subMesh, effect, fillMode);
  21903. }
  21904. var world = this.getWorldMatrix();
  21905. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21906. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  21907. }
  21908. else {
  21909. effectiveMaterial.bind(world, this);
  21910. }
  21911. // Draw
  21912. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  21913. // Unbind
  21914. effectiveMaterial.unbind();
  21915. // Outline - step 2
  21916. if (this.renderOutline && savedDepthWrite) {
  21917. engine.setDepthWrite(true);
  21918. engine.setColorWrite(false);
  21919. scene.getOutlineRenderer().render(subMesh, batch);
  21920. engine.setColorWrite(true);
  21921. }
  21922. // Overlay
  21923. if (this.renderOverlay) {
  21924. var currentMode = engine.getAlphaMode();
  21925. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21926. scene.getOutlineRenderer().render(subMesh, batch, true);
  21927. engine.setAlphaMode(currentMode);
  21928. }
  21929. this.onAfterRenderObservable.notifyObservers(this);
  21930. return this;
  21931. };
  21932. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  21933. if (isInstance) {
  21934. effectiveMaterial.bindOnlyWorldMatrix(world);
  21935. }
  21936. return this;
  21937. };
  21938. /**
  21939. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  21940. */
  21941. Mesh.prototype.getEmittedParticleSystems = function () {
  21942. var results = new Array();
  21943. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21944. var particleSystem = this.getScene().particleSystems[index];
  21945. if (particleSystem.emitter === this) {
  21946. results.push(particleSystem);
  21947. }
  21948. }
  21949. return results;
  21950. };
  21951. /**
  21952. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  21953. */
  21954. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  21955. var results = new Array();
  21956. var descendants = this.getDescendants();
  21957. descendants.push(this);
  21958. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21959. var particleSystem = this.getScene().particleSystems[index];
  21960. var emitter = particleSystem.emitter;
  21961. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  21962. results.push(particleSystem);
  21963. }
  21964. }
  21965. return results;
  21966. };
  21967. Mesh.prototype._checkDelayState = function () {
  21968. var scene = this.getScene();
  21969. if (this._geometry) {
  21970. this._geometry.load(scene);
  21971. }
  21972. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21973. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21974. this._queueLoad(this, scene);
  21975. }
  21976. return this;
  21977. };
  21978. Mesh.prototype._queueLoad = function (mesh, scene) {
  21979. var _this = this;
  21980. scene._addPendingData(mesh);
  21981. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  21982. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21983. if (data instanceof ArrayBuffer) {
  21984. _this._delayLoadingFunction(data, _this);
  21985. }
  21986. else {
  21987. _this._delayLoadingFunction(JSON.parse(data), _this);
  21988. }
  21989. _this.instances.forEach(function (instance) {
  21990. instance._syncSubMeshes();
  21991. });
  21992. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21993. scene._removePendingData(_this);
  21994. }, function () { }, scene.database, getBinaryData);
  21995. return this;
  21996. };
  21997. /**
  21998. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  21999. */
  22000. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22001. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22002. return false;
  22003. }
  22004. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22005. return false;
  22006. }
  22007. this._checkDelayState();
  22008. return true;
  22009. };
  22010. /**
  22011. * Sets the mesh material by the material or multiMaterial `id` property.
  22012. * The material `id` is a string identifying the material or the multiMaterial.
  22013. * This method returns the Mesh.
  22014. */
  22015. Mesh.prototype.setMaterialByID = function (id) {
  22016. var materials = this.getScene().materials;
  22017. var index;
  22018. for (index = materials.length - 1; index > -1; index--) {
  22019. if (materials[index].id === id) {
  22020. this.material = materials[index];
  22021. return this;
  22022. }
  22023. }
  22024. // Multi
  22025. var multiMaterials = this.getScene().multiMaterials;
  22026. for (index = multiMaterials.length - 1; index > -1; index--) {
  22027. if (multiMaterials[index].id === id) {
  22028. this.material = multiMaterials[index];
  22029. return this;
  22030. }
  22031. }
  22032. return this;
  22033. };
  22034. /**
  22035. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22036. */
  22037. Mesh.prototype.getAnimatables = function () {
  22038. var results = [];
  22039. if (this.material) {
  22040. results.push(this.material);
  22041. }
  22042. if (this.skeleton) {
  22043. results.push(this.skeleton);
  22044. }
  22045. return results;
  22046. };
  22047. /**
  22048. * Modifies the mesh geometry according to the passed transformation matrix.
  22049. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22050. * The mesh normals are modified accordingly the same transformation.
  22051. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22052. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22053. * Returns the Mesh.
  22054. */
  22055. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22056. // Position
  22057. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22058. return this;
  22059. }
  22060. var submeshes = this.subMeshes.splice(0);
  22061. this._resetPointsArrayCache();
  22062. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22063. var temp = [];
  22064. var index;
  22065. for (index = 0; index < data.length; index += 3) {
  22066. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22067. }
  22068. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22069. // Normals
  22070. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22071. return this;
  22072. }
  22073. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22074. temp = [];
  22075. for (index = 0; index < data.length; index += 3) {
  22076. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22077. }
  22078. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22079. // flip faces?
  22080. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22081. this.flipFaces();
  22082. }
  22083. // Restore submeshes
  22084. this.releaseSubMeshes();
  22085. this.subMeshes = submeshes;
  22086. return this;
  22087. };
  22088. /**
  22089. * Modifies the mesh geometry according to its own current World Matrix.
  22090. * The mesh World Matrix is then reset.
  22091. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22092. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22093. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22094. * Returns the Mesh.
  22095. */
  22096. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22097. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22098. this.scaling.copyFromFloats(1, 1, 1);
  22099. this.position.copyFromFloats(0, 0, 0);
  22100. this.rotation.copyFromFloats(0, 0, 0);
  22101. //only if quaternion is already set
  22102. if (this.rotationQuaternion) {
  22103. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22104. }
  22105. this._worldMatrix = BABYLON.Matrix.Identity();
  22106. return this;
  22107. };
  22108. Object.defineProperty(Mesh.prototype, "_positions", {
  22109. // Cache
  22110. get: function () {
  22111. if (this._geometry) {
  22112. return this._geometry._positions;
  22113. }
  22114. return null;
  22115. },
  22116. enumerable: true,
  22117. configurable: true
  22118. });
  22119. Mesh.prototype._resetPointsArrayCache = function () {
  22120. if (this._geometry) {
  22121. this._geometry._resetPointsArrayCache();
  22122. }
  22123. return this;
  22124. };
  22125. Mesh.prototype._generatePointsArray = function () {
  22126. if (this._geometry) {
  22127. return this._geometry._generatePointsArray();
  22128. }
  22129. return false;
  22130. };
  22131. /**
  22132. * Returns a new Mesh object generated from the current mesh properties.
  22133. * This method must not get confused with createInstance().
  22134. * The parameter `name` is a string, the name given to the new mesh.
  22135. * The optional parameter `newParent` can be any Node object (default `null`).
  22136. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22137. * 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.
  22138. */
  22139. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22140. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22141. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22142. };
  22143. /**
  22144. * Disposes the mesh.
  22145. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22146. */
  22147. Mesh.prototype.dispose = function (doNotRecurse) {
  22148. var _this = this;
  22149. this.morphTargetManager = undefined;
  22150. if (this._geometry) {
  22151. this._geometry.releaseForMesh(this, true);
  22152. }
  22153. // Sources
  22154. var meshes = this.getScene().meshes;
  22155. meshes.forEach(function (mesh) {
  22156. if (mesh._source && mesh._source === _this) {
  22157. mesh._source = null;
  22158. }
  22159. });
  22160. this._source = null;
  22161. // Instances
  22162. if (this._instancesBuffer) {
  22163. this._instancesBuffer.dispose();
  22164. this._instancesBuffer = null;
  22165. }
  22166. while (this.instances.length) {
  22167. this.instances[0].dispose();
  22168. }
  22169. // Highlight layers.
  22170. var highlightLayers = this.getScene().highlightLayers;
  22171. for (var i = 0; i < highlightLayers.length; i++) {
  22172. var highlightLayer = highlightLayers[i];
  22173. if (highlightLayer) {
  22174. highlightLayer.removeMesh(this);
  22175. highlightLayer.removeExcludedMesh(this);
  22176. }
  22177. }
  22178. _super.prototype.dispose.call(this, doNotRecurse);
  22179. };
  22180. /**
  22181. * Modifies the mesh geometry according to a displacement map.
  22182. * 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.
  22183. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22184. * This method returns nothing.
  22185. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22186. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22187. * 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.
  22188. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22189. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22190. *
  22191. * Returns the Mesh.
  22192. */
  22193. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22194. var _this = this;
  22195. var scene = this.getScene();
  22196. var onload = function (img) {
  22197. // Getting height map data
  22198. var canvas = document.createElement("canvas");
  22199. var context = canvas.getContext("2d");
  22200. var heightMapWidth = img.width;
  22201. var heightMapHeight = img.height;
  22202. canvas.width = heightMapWidth;
  22203. canvas.height = heightMapHeight;
  22204. context.drawImage(img, 0, 0);
  22205. // Create VertexData from map data
  22206. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22207. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22208. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22209. //execute success callback, if set
  22210. if (onSuccess) {
  22211. onSuccess(_this);
  22212. }
  22213. };
  22214. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22215. return this;
  22216. };
  22217. /**
  22218. * Modifies the mesh geometry according to a displacementMap buffer.
  22219. * 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.
  22220. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22221. * This method returns nothing.
  22222. * 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.
  22223. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22224. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22225. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22226. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22227. *
  22228. * Returns the Mesh.
  22229. */
  22230. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22231. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22232. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22233. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22234. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22235. return this;
  22236. }
  22237. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22238. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22239. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22240. var position = BABYLON.Vector3.Zero();
  22241. var normal = BABYLON.Vector3.Zero();
  22242. var uv = BABYLON.Vector2.Zero();
  22243. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22244. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22245. for (var index = 0; index < positions.length; index += 3) {
  22246. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22247. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22248. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22249. // Compute height
  22250. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22251. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22252. var pos = (u + v * heightMapWidth) * 4;
  22253. var r = buffer[pos] / 255.0;
  22254. var g = buffer[pos + 1] / 255.0;
  22255. var b = buffer[pos + 2] / 255.0;
  22256. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22257. normal.normalize();
  22258. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22259. position = position.add(normal);
  22260. position.toArray(positions, index);
  22261. }
  22262. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22263. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22264. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22265. return this;
  22266. };
  22267. /**
  22268. * Modify the mesh to get a flat shading rendering.
  22269. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22270. * This method returns the Mesh.
  22271. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22272. */
  22273. Mesh.prototype.convertToFlatShadedMesh = function () {
  22274. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22275. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22276. var kinds = this.getVerticesDataKinds();
  22277. var vbs = [];
  22278. var data = [];
  22279. var newdata = [];
  22280. var updatableNormals = false;
  22281. var kindIndex;
  22282. var kind;
  22283. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22284. kind = kinds[kindIndex];
  22285. var vertexBuffer = this.getVertexBuffer(kind);
  22286. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22287. updatableNormals = vertexBuffer.isUpdatable();
  22288. kinds.splice(kindIndex, 1);
  22289. kindIndex--;
  22290. continue;
  22291. }
  22292. vbs[kind] = vertexBuffer;
  22293. data[kind] = vbs[kind].getData();
  22294. newdata[kind] = [];
  22295. }
  22296. // Save previous submeshes
  22297. var previousSubmeshes = this.subMeshes.slice(0);
  22298. var indices = this.getIndices();
  22299. var totalIndices = this.getTotalIndices();
  22300. // Generating unique vertices per face
  22301. var index;
  22302. for (index = 0; index < totalIndices; index++) {
  22303. var vertexIndex = indices[index];
  22304. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22305. kind = kinds[kindIndex];
  22306. var stride = vbs[kind].getStrideSize();
  22307. for (var offset = 0; offset < stride; offset++) {
  22308. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22309. }
  22310. }
  22311. }
  22312. // Updating faces & normal
  22313. var normals = [];
  22314. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22315. for (index = 0; index < totalIndices; index += 3) {
  22316. indices[index] = index;
  22317. indices[index + 1] = index + 1;
  22318. indices[index + 2] = index + 2;
  22319. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22320. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22321. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22322. var p1p2 = p1.subtract(p2);
  22323. var p3p2 = p3.subtract(p2);
  22324. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22325. // Store same normals for every vertex
  22326. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22327. normals.push(normal.x);
  22328. normals.push(normal.y);
  22329. normals.push(normal.z);
  22330. }
  22331. }
  22332. this.setIndices(indices);
  22333. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22334. // Updating vertex buffers
  22335. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22336. kind = kinds[kindIndex];
  22337. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22338. }
  22339. // Updating submeshes
  22340. this.releaseSubMeshes();
  22341. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22342. var previousOne = previousSubmeshes[submeshIndex];
  22343. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22344. }
  22345. this.synchronizeInstances();
  22346. return this;
  22347. };
  22348. /**
  22349. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22350. * In other words, more vertices, no more indices and a single bigger VBO.
  22351. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22352. * Returns the Mesh.
  22353. */
  22354. Mesh.prototype.convertToUnIndexedMesh = function () {
  22355. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22356. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22357. var kinds = this.getVerticesDataKinds();
  22358. var vbs = [];
  22359. var data = [];
  22360. var newdata = [];
  22361. var updatableNormals = false;
  22362. var kindIndex;
  22363. var kind;
  22364. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22365. kind = kinds[kindIndex];
  22366. var vertexBuffer = this.getVertexBuffer(kind);
  22367. vbs[kind] = vertexBuffer;
  22368. data[kind] = vbs[kind].getData();
  22369. newdata[kind] = [];
  22370. }
  22371. // Save previous submeshes
  22372. var previousSubmeshes = this.subMeshes.slice(0);
  22373. var indices = this.getIndices();
  22374. var totalIndices = this.getTotalIndices();
  22375. // Generating unique vertices per face
  22376. var index;
  22377. for (index = 0; index < totalIndices; index++) {
  22378. var vertexIndex = indices[index];
  22379. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22380. kind = kinds[kindIndex];
  22381. var stride = vbs[kind].getStrideSize();
  22382. for (var offset = 0; offset < stride; offset++) {
  22383. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22384. }
  22385. }
  22386. }
  22387. // Updating indices
  22388. for (index = 0; index < totalIndices; index += 3) {
  22389. indices[index] = index;
  22390. indices[index + 1] = index + 1;
  22391. indices[index + 2] = index + 2;
  22392. }
  22393. this.setIndices(indices);
  22394. // Updating vertex buffers
  22395. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22396. kind = kinds[kindIndex];
  22397. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22398. }
  22399. // Updating submeshes
  22400. this.releaseSubMeshes();
  22401. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22402. var previousOne = previousSubmeshes[submeshIndex];
  22403. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22404. }
  22405. this._unIndexed = true;
  22406. this.synchronizeInstances();
  22407. return this;
  22408. };
  22409. /**
  22410. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22411. * This method returns the Mesh.
  22412. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22413. */
  22414. Mesh.prototype.flipFaces = function (flipNormals) {
  22415. if (flipNormals === void 0) { flipNormals = false; }
  22416. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22417. var i;
  22418. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22419. for (i = 0; i < vertex_data.normals.length; i++) {
  22420. vertex_data.normals[i] *= -1;
  22421. }
  22422. }
  22423. var temp;
  22424. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22425. // reassign indices
  22426. temp = vertex_data.indices[i + 1];
  22427. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22428. vertex_data.indices[i + 2] = temp;
  22429. }
  22430. vertex_data.applyToMesh(this);
  22431. return this;
  22432. };
  22433. // Instances
  22434. /**
  22435. * Creates a new InstancedMesh object from the mesh model.
  22436. * An instance shares the same properties and the same material than its model.
  22437. * Only these properties of each instance can then be set individually :
  22438. * - position
  22439. * - rotation
  22440. * - rotationQuaternion
  22441. * - setPivotMatrix
  22442. * - scaling
  22443. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22444. * Warning : this method is not supported for Line mesh and LineSystem
  22445. */
  22446. Mesh.prototype.createInstance = function (name) {
  22447. return new BABYLON.InstancedMesh(name, this);
  22448. };
  22449. /**
  22450. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22451. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22452. * This method returns the Mesh.
  22453. */
  22454. Mesh.prototype.synchronizeInstances = function () {
  22455. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22456. var instance = this.instances[instanceIndex];
  22457. instance._syncSubMeshes();
  22458. }
  22459. return this;
  22460. };
  22461. /**
  22462. * Simplify the mesh according to the given array of settings.
  22463. * Function will return immediately and will simplify async. It returns the Mesh.
  22464. * @param settings a collection of simplification settings.
  22465. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22466. * @param type the type of simplification to run.
  22467. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22468. */
  22469. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22470. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22471. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22472. this.getScene().simplificationQueue.addTask({
  22473. settings: settings,
  22474. parallelProcessing: parallelProcessing,
  22475. mesh: this,
  22476. simplificationType: simplificationType,
  22477. successCallback: successCallback
  22478. });
  22479. return this;
  22480. };
  22481. /**
  22482. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22483. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22484. * This should be used together with the simplification to avoid disappearing triangles.
  22485. * Returns the Mesh.
  22486. * @param successCallback an optional success callback to be called after the optimization finished.
  22487. */
  22488. Mesh.prototype.optimizeIndices = function (successCallback) {
  22489. var _this = this;
  22490. var indices = this.getIndices();
  22491. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22492. var vectorPositions = [];
  22493. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22494. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22495. }
  22496. var dupes = [];
  22497. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22498. var realPos = vectorPositions.length - 1 - iteration;
  22499. var testedPosition = vectorPositions[realPos];
  22500. for (var j = 0; j < realPos; ++j) {
  22501. var againstPosition = vectorPositions[j];
  22502. if (testedPosition.equals(againstPosition)) {
  22503. dupes[realPos] = j;
  22504. break;
  22505. }
  22506. }
  22507. }, function () {
  22508. for (var i = 0; i < indices.length; ++i) {
  22509. indices[i] = dupes[indices[i]] || indices[i];
  22510. }
  22511. //indices are now reordered
  22512. var originalSubMeshes = _this.subMeshes.slice(0);
  22513. _this.setIndices(indices);
  22514. _this.subMeshes = originalSubMeshes;
  22515. if (successCallback) {
  22516. successCallback(_this);
  22517. }
  22518. });
  22519. return this;
  22520. };
  22521. Mesh.prototype.serialize = function (serializationObject) {
  22522. serializationObject.name = this.name;
  22523. serializationObject.id = this.id;
  22524. serializationObject.type = this.getClassName();
  22525. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22526. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22527. }
  22528. serializationObject.position = this.position.asArray();
  22529. if (this.rotationQuaternion) {
  22530. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22531. }
  22532. else if (this.rotation) {
  22533. serializationObject.rotation = this.rotation.asArray();
  22534. }
  22535. serializationObject.scaling = this.scaling.asArray();
  22536. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22537. serializationObject.isEnabled = this.isEnabled();
  22538. serializationObject.isVisible = this.isVisible;
  22539. serializationObject.infiniteDistance = this.infiniteDistance;
  22540. serializationObject.pickable = this.isPickable;
  22541. serializationObject.receiveShadows = this.receiveShadows;
  22542. serializationObject.billboardMode = this.billboardMode;
  22543. serializationObject.visibility = this.visibility;
  22544. serializationObject.checkCollisions = this.checkCollisions;
  22545. serializationObject.isBlocker = this.isBlocker;
  22546. // Parent
  22547. if (this.parent) {
  22548. serializationObject.parentId = this.parent.id;
  22549. }
  22550. // Geometry
  22551. var geometry = this._geometry;
  22552. if (geometry) {
  22553. var geometryId = geometry.id;
  22554. serializationObject.geometryId = geometryId;
  22555. // SubMeshes
  22556. serializationObject.subMeshes = [];
  22557. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22558. var subMesh = this.subMeshes[subIndex];
  22559. serializationObject.subMeshes.push({
  22560. materialIndex: subMesh.materialIndex,
  22561. verticesStart: subMesh.verticesStart,
  22562. verticesCount: subMesh.verticesCount,
  22563. indexStart: subMesh.indexStart,
  22564. indexCount: subMesh.indexCount
  22565. });
  22566. }
  22567. }
  22568. // Material
  22569. if (this.material) {
  22570. serializationObject.materialId = this.material.id;
  22571. }
  22572. else {
  22573. this.material = null;
  22574. }
  22575. // Morph targets
  22576. if (this.morphTargetManager) {
  22577. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22578. }
  22579. // Skeleton
  22580. if (this.skeleton) {
  22581. serializationObject.skeletonId = this.skeleton.id;
  22582. }
  22583. // Physics
  22584. //TODO implement correct serialization for physics impostors.
  22585. if (this.getPhysicsImpostor()) {
  22586. var impostor = this.getPhysicsImpostor();
  22587. serializationObject.physicsMass = impostor.getParam("mass");
  22588. serializationObject.physicsFriction = impostor.getParam("friction");
  22589. serializationObject.physicsRestitution = impostor.getParam("mass");
  22590. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  22591. }
  22592. // Metadata
  22593. if (this.metadata) {
  22594. serializationObject.metadata = this.metadata;
  22595. }
  22596. // Instances
  22597. serializationObject.instances = [];
  22598. for (var index = 0; index < this.instances.length; index++) {
  22599. var instance = this.instances[index];
  22600. var serializationInstance = {
  22601. name: instance.name,
  22602. position: instance.position.asArray(),
  22603. scaling: instance.scaling.asArray()
  22604. };
  22605. if (instance.rotationQuaternion) {
  22606. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  22607. }
  22608. else if (instance.rotation) {
  22609. serializationInstance.rotation = instance.rotation.asArray();
  22610. }
  22611. serializationObject.instances.push(serializationInstance);
  22612. // Animations
  22613. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  22614. serializationInstance.ranges = instance.serializeAnimationRanges();
  22615. }
  22616. //
  22617. // Animations
  22618. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22619. serializationObject.ranges = this.serializeAnimationRanges();
  22620. // Layer mask
  22621. serializationObject.layerMask = this.layerMask;
  22622. // Alpha
  22623. serializationObject.alphaIndex = this.alphaIndex;
  22624. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  22625. // Overlay
  22626. serializationObject.overlayAlpha = this.overlayAlpha;
  22627. serializationObject.overlayColor = this.overlayColor.asArray();
  22628. serializationObject.renderOverlay = this.renderOverlay;
  22629. // Fog
  22630. serializationObject.applyFog = this.applyFog;
  22631. // Action Manager
  22632. if (this.actionManager) {
  22633. serializationObject.actions = this.actionManager.serialize(this.name);
  22634. }
  22635. };
  22636. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  22637. if (!this.geometry) {
  22638. return;
  22639. }
  22640. this._markSubMeshesAsAttributesDirty();
  22641. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  22642. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  22643. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  22644. this.morphTargetManager = undefined;
  22645. return;
  22646. }
  22647. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  22648. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  22649. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  22650. if (morphTarget.hasNormals) {
  22651. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  22652. }
  22653. if (morphTarget.hasTangents) {
  22654. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  22655. }
  22656. }
  22657. }
  22658. else {
  22659. var index = 0;
  22660. // Positions
  22661. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  22662. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  22663. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  22664. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  22665. }
  22666. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  22667. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  22668. }
  22669. index++;
  22670. }
  22671. }
  22672. };
  22673. // Statics
  22674. /**
  22675. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22676. * The parameter `parsedMesh` is the mesh to be copied.
  22677. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22678. */
  22679. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22680. var mesh;
  22681. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  22682. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  22683. }
  22684. else {
  22685. mesh = new Mesh(parsedMesh.name, scene);
  22686. }
  22687. mesh.id = parsedMesh.id;
  22688. if (BABYLON.Tags) {
  22689. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  22690. }
  22691. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  22692. if (parsedMesh.metadata !== undefined) {
  22693. mesh.metadata = parsedMesh.metadata;
  22694. }
  22695. if (parsedMesh.rotationQuaternion) {
  22696. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  22697. }
  22698. else if (parsedMesh.rotation) {
  22699. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  22700. }
  22701. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  22702. if (parsedMesh.localMatrix) {
  22703. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  22704. }
  22705. else if (parsedMesh.pivotMatrix) {
  22706. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  22707. }
  22708. mesh.setEnabled(parsedMesh.isEnabled);
  22709. mesh.isVisible = parsedMesh.isVisible;
  22710. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  22711. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  22712. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  22713. if (parsedMesh.applyFog !== undefined) {
  22714. mesh.applyFog = parsedMesh.applyFog;
  22715. }
  22716. if (parsedMesh.pickable !== undefined) {
  22717. mesh.isPickable = parsedMesh.pickable;
  22718. }
  22719. if (parsedMesh.alphaIndex !== undefined) {
  22720. mesh.alphaIndex = parsedMesh.alphaIndex;
  22721. }
  22722. mesh.receiveShadows = parsedMesh.receiveShadows;
  22723. mesh.billboardMode = parsedMesh.billboardMode;
  22724. if (parsedMesh.visibility !== undefined) {
  22725. mesh.visibility = parsedMesh.visibility;
  22726. }
  22727. mesh.checkCollisions = parsedMesh.checkCollisions;
  22728. if (parsedMesh.isBlocker !== undefined) {
  22729. mesh.isBlocker = parsedMesh.isBlocker;
  22730. }
  22731. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  22732. // freezeWorldMatrix
  22733. if (parsedMesh.freezeWorldMatrix) {
  22734. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  22735. }
  22736. // Parent
  22737. if (parsedMesh.parentId) {
  22738. mesh._waitingParentId = parsedMesh.parentId;
  22739. }
  22740. // Actions
  22741. if (parsedMesh.actions !== undefined) {
  22742. mesh._waitingActions = parsedMesh.actions;
  22743. }
  22744. // Overlay
  22745. if (parsedMesh.overlayAlpha !== undefined) {
  22746. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22747. }
  22748. if (parsedMesh.overlayColor !== undefined) {
  22749. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22750. }
  22751. if (parsedMesh.renderOverlay !== undefined) {
  22752. mesh.renderOverlay = parsedMesh.renderOverlay;
  22753. }
  22754. // Geometry
  22755. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22756. if (parsedMesh.delayLoadingFile) {
  22757. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22758. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22759. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22760. if (parsedMesh._binaryInfo) {
  22761. mesh._binaryInfo = parsedMesh._binaryInfo;
  22762. }
  22763. mesh._delayInfo = [];
  22764. if (parsedMesh.hasUVs) {
  22765. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22766. }
  22767. if (parsedMesh.hasUVs2) {
  22768. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22769. }
  22770. if (parsedMesh.hasUVs3) {
  22771. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22772. }
  22773. if (parsedMesh.hasUVs4) {
  22774. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22775. }
  22776. if (parsedMesh.hasUVs5) {
  22777. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22778. }
  22779. if (parsedMesh.hasUVs6) {
  22780. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22781. }
  22782. if (parsedMesh.hasColors) {
  22783. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22784. }
  22785. if (parsedMesh.hasMatricesIndices) {
  22786. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22787. }
  22788. if (parsedMesh.hasMatricesWeights) {
  22789. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22790. }
  22791. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22792. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22793. mesh._checkDelayState();
  22794. }
  22795. }
  22796. else {
  22797. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22798. }
  22799. // Material
  22800. if (parsedMesh.materialId) {
  22801. mesh.setMaterialByID(parsedMesh.materialId);
  22802. }
  22803. else {
  22804. mesh.material = null;
  22805. }
  22806. // Morph targets
  22807. if (parsedMesh.morphTargetManagerId > -1) {
  22808. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  22809. }
  22810. // Skeleton
  22811. if (parsedMesh.skeletonId > -1) {
  22812. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22813. if (parsedMesh.numBoneInfluencers) {
  22814. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22815. }
  22816. }
  22817. // Animations
  22818. if (parsedMesh.animations) {
  22819. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22820. var parsedAnimation = parsedMesh.animations[animationIndex];
  22821. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22822. }
  22823. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  22824. }
  22825. if (parsedMesh.autoAnimate) {
  22826. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  22827. }
  22828. // Layer Mask
  22829. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  22830. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  22831. }
  22832. else {
  22833. mesh.layerMask = 0x0FFFFFFF;
  22834. }
  22835. // Physics
  22836. if (parsedMesh.physicsImpostor) {
  22837. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  22838. mass: parsedMesh.physicsMass,
  22839. friction: parsedMesh.physicsFriction,
  22840. restitution: parsedMesh.physicsRestitution
  22841. }, scene);
  22842. }
  22843. // Instances
  22844. if (parsedMesh.instances) {
  22845. for (var index = 0; index < parsedMesh.instances.length; index++) {
  22846. var parsedInstance = parsedMesh.instances[index];
  22847. var instance = mesh.createInstance(parsedInstance.name);
  22848. if (BABYLON.Tags) {
  22849. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  22850. }
  22851. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  22852. if (parsedInstance.parentId) {
  22853. instance._waitingParentId = parsedInstance.parentId;
  22854. }
  22855. if (parsedInstance.rotationQuaternion) {
  22856. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  22857. }
  22858. else if (parsedInstance.rotation) {
  22859. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  22860. }
  22861. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  22862. instance.checkCollisions = mesh.checkCollisions;
  22863. if (parsedMesh.animations) {
  22864. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22865. parsedAnimation = parsedMesh.animations[animationIndex];
  22866. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22867. }
  22868. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  22869. }
  22870. }
  22871. }
  22872. return mesh;
  22873. };
  22874. /**
  22875. * Creates a ribbon mesh.
  22876. * Please consider using the same method from the MeshBuilder class instead.
  22877. * 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.
  22878. *
  22879. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22880. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22881. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22882. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22883. * 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.
  22884. * 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.
  22885. * 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
  22886. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22887. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22888. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22889. */
  22890. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  22891. return BABYLON.MeshBuilder.CreateRibbon(name, {
  22892. pathArray: pathArray,
  22893. closeArray: closeArray,
  22894. closePath: closePath,
  22895. offset: offset,
  22896. updatable: updatable,
  22897. sideOrientation: sideOrientation,
  22898. instance: instance
  22899. }, scene);
  22900. };
  22901. /**
  22902. * Creates a plane polygonal mesh. By default, this is a disc.
  22903. * Please consider using the same method from the MeshBuilder class instead.
  22904. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22905. * 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.
  22906. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22907. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22908. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22909. */
  22910. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22911. var options = {
  22912. radius: radius,
  22913. tessellation: tessellation,
  22914. sideOrientation: sideOrientation,
  22915. updatable: updatable
  22916. };
  22917. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22918. };
  22919. /**
  22920. * Creates a box mesh.
  22921. * Please consider using the same method from the MeshBuilder class instead.
  22922. * The parameter `size` sets the size (float) of each box side (default 1).
  22923. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22924. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22925. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22926. */
  22927. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22928. var options = {
  22929. size: size,
  22930. sideOrientation: sideOrientation,
  22931. updatable: updatable
  22932. };
  22933. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22934. };
  22935. /**
  22936. * Creates a sphere mesh.
  22937. * Please consider using the same method from the MeshBuilder class instead.
  22938. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22939. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22940. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22941. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22942. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22943. */
  22944. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22945. var options = {
  22946. segments: segments,
  22947. diameterX: diameter,
  22948. diameterY: diameter,
  22949. diameterZ: diameter,
  22950. sideOrientation: sideOrientation,
  22951. updatable: updatable
  22952. };
  22953. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  22954. };
  22955. /**
  22956. * Creates a cylinder or a cone mesh.
  22957. * Please consider using the same method from the MeshBuilder class instead.
  22958. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22959. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22960. * 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.
  22961. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22962. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22963. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22964. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22965. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22966. */
  22967. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  22968. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  22969. if (scene !== undefined) {
  22970. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  22971. updatable = scene;
  22972. }
  22973. scene = subdivisions;
  22974. subdivisions = 1;
  22975. }
  22976. var options = {
  22977. height: height,
  22978. diameterTop: diameterTop,
  22979. diameterBottom: diameterBottom,
  22980. tessellation: tessellation,
  22981. subdivisions: subdivisions,
  22982. sideOrientation: sideOrientation,
  22983. updatable: updatable
  22984. };
  22985. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  22986. };
  22987. // Torus (Code from SharpDX.org)
  22988. /**
  22989. * Creates a torus mesh.
  22990. * Please consider using the same method from the MeshBuilder class instead.
  22991. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22992. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22993. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22994. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22995. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22996. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22997. */
  22998. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  22999. var options = {
  23000. diameter: diameter,
  23001. thickness: thickness,
  23002. tessellation: tessellation,
  23003. sideOrientation: sideOrientation,
  23004. updatable: updatable
  23005. };
  23006. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23007. };
  23008. /**
  23009. * Creates a torus knot mesh.
  23010. * Please consider using the same method from the MeshBuilder class instead.
  23011. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23012. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23013. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23014. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23015. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23016. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23017. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23018. */
  23019. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23020. var options = {
  23021. radius: radius,
  23022. tube: tube,
  23023. radialSegments: radialSegments,
  23024. tubularSegments: tubularSegments,
  23025. p: p,
  23026. q: q,
  23027. sideOrientation: sideOrientation,
  23028. updatable: updatable
  23029. };
  23030. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23031. };
  23032. /**
  23033. * Creates a line mesh.
  23034. * Please consider using the same method from the MeshBuilder class instead.
  23035. * 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.
  23036. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23037. * The parameter `points` is an array successive Vector3.
  23038. * 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
  23039. * When updating an instance, remember that only point positions can change, not the number of points.
  23040. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23041. */
  23042. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23043. var options = {
  23044. points: points,
  23045. updatable: updatable,
  23046. instance: instance
  23047. };
  23048. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23049. };
  23050. /**
  23051. * Creates a dashed line mesh.
  23052. * Please consider using the same method from the MeshBuilder class instead.
  23053. * 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.
  23054. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23055. * The parameter `points` is an array successive Vector3.
  23056. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23057. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23058. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23059. * 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
  23060. * When updating an instance, remember that only point positions can change, not the number of points.
  23061. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23062. */
  23063. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23064. var options = {
  23065. points: points,
  23066. dashSize: dashSize,
  23067. gapSize: gapSize,
  23068. dashNb: dashNb,
  23069. updatable: updatable,
  23070. instance: instance
  23071. };
  23072. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23073. };
  23074. /**
  23075. * Creates a polygon mesh.
  23076. * Please consider using the same method from the MeshBuilder class instead.
  23077. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23078. * 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.
  23079. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23080. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23081. * Remember you can only change the shape positions, not their number when updating a polygon.
  23082. */
  23083. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23084. var options = {
  23085. shape: shape,
  23086. holes: holes,
  23087. updatable: updatable,
  23088. sideOrientation: sideOrientation
  23089. };
  23090. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23091. };
  23092. /**
  23093. * Creates an extruded polygon mesh, with depth in the Y direction.
  23094. * Please consider using the same method from the MeshBuilder class instead.
  23095. */
  23096. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23097. var options = {
  23098. shape: shape,
  23099. holes: holes,
  23100. depth: depth,
  23101. updatable: updatable,
  23102. sideOrientation: sideOrientation
  23103. };
  23104. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23105. };
  23106. /**
  23107. * Creates an extruded shape mesh.
  23108. * 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.
  23109. * Please consider using the same method from the MeshBuilder class instead.
  23110. *
  23111. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23112. * 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
  23113. * extruded along the Z axis.
  23114. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23115. * 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.
  23116. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23117. * 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
  23118. * 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
  23119. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23120. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23121. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23123. */
  23124. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23125. var options = {
  23126. shape: shape,
  23127. path: path,
  23128. scale: scale,
  23129. rotation: rotation,
  23130. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23131. sideOrientation: sideOrientation,
  23132. instance: instance,
  23133. updatable: updatable
  23134. };
  23135. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23136. };
  23137. /**
  23138. * Creates an custom extruded shape mesh.
  23139. * 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.
  23140. * Please consider using the same method from the MeshBuilder class instead.
  23141. *
  23142. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23143. * 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
  23144. * extruded along the Z axis.
  23145. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23146. * 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
  23147. * and the distance of this point from the begining of the path :
  23148. * ```javascript
  23149. * var rotationFunction = function(i, distance) {
  23150. * // do things
  23151. * return rotationValue; }
  23152. * ```
  23153. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23154. * 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
  23155. * and the distance of this point from the begining of the path :
  23156. * ```javascript
  23157. * var scaleFunction = function(i, distance) {
  23158. * // do things
  23159. * return scaleValue;}
  23160. * ```
  23161. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23162. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23163. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23164. * 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
  23165. * 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
  23166. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23167. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23168. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23169. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23170. */
  23171. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23172. var options = {
  23173. shape: shape,
  23174. path: path,
  23175. scaleFunction: scaleFunction,
  23176. rotationFunction: rotationFunction,
  23177. ribbonCloseArray: ribbonCloseArray,
  23178. ribbonClosePath: ribbonClosePath,
  23179. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23180. sideOrientation: sideOrientation,
  23181. instance: instance,
  23182. updatable: updatable
  23183. };
  23184. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23185. };
  23186. /**
  23187. * Creates lathe mesh.
  23188. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23189. * Please consider using the same method from the MeshBuilder class instead.
  23190. * 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
  23191. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23192. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23193. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23194. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23195. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23196. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23197. */
  23198. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23199. var options = {
  23200. shape: shape,
  23201. radius: radius,
  23202. tessellation: tessellation,
  23203. sideOrientation: sideOrientation,
  23204. updatable: updatable
  23205. };
  23206. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23207. };
  23208. /**
  23209. * Creates a plane mesh.
  23210. * Please consider using the same method from the MeshBuilder class instead.
  23211. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23212. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23213. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23214. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23215. */
  23216. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23217. var options = {
  23218. size: size,
  23219. width: size,
  23220. height: size,
  23221. sideOrientation: sideOrientation,
  23222. updatable: updatable
  23223. };
  23224. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23225. };
  23226. /**
  23227. * Creates a ground mesh.
  23228. * Please consider using the same method from the MeshBuilder class instead.
  23229. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23230. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23231. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23232. */
  23233. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23234. var options = {
  23235. width: width,
  23236. height: height,
  23237. subdivisions: subdivisions,
  23238. updatable: updatable
  23239. };
  23240. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23241. };
  23242. /**
  23243. * Creates a tiled ground mesh.
  23244. * Please consider using the same method from the MeshBuilder class instead.
  23245. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23246. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23247. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23248. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23249. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23250. * numbers of subdivisions on the ground width and height of each tile.
  23251. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23252. */
  23253. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23254. var options = {
  23255. xmin: xmin,
  23256. zmin: zmin,
  23257. xmax: xmax,
  23258. zmax: zmax,
  23259. subdivisions: subdivisions,
  23260. precision: precision,
  23261. updatable: updatable
  23262. };
  23263. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23264. };
  23265. /**
  23266. * Creates a ground mesh from a height map.
  23267. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23268. * Please consider using the same method from the MeshBuilder class instead.
  23269. * The parameter `url` sets the URL of the height map image resource.
  23270. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23271. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23272. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23273. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23274. * 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).
  23275. * This function is passed the newly built mesh :
  23276. * ```javascript
  23277. * function(mesh) { // do things
  23278. * return; }
  23279. * ```
  23280. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23281. */
  23282. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23283. var options = {
  23284. width: width,
  23285. height: height,
  23286. subdivisions: subdivisions,
  23287. minHeight: minHeight,
  23288. maxHeight: maxHeight,
  23289. updatable: updatable,
  23290. onReady: onReady
  23291. };
  23292. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23293. };
  23294. /**
  23295. * Creates a tube mesh.
  23296. * 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.
  23297. * Please consider using the same method from the MeshBuilder class instead.
  23298. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23299. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23300. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23301. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23302. * 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.
  23303. * It must return a radius value (positive float) :
  23304. * ```javascript
  23305. * var radiusFunction = function(i, distance) {
  23306. * // do things
  23307. * return radius; }
  23308. * ```
  23309. * 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
  23310. * 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
  23311. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23312. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23313. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23314. */
  23315. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23316. var options = {
  23317. path: path,
  23318. radius: radius,
  23319. tessellation: tessellation,
  23320. radiusFunction: radiusFunction,
  23321. arc: 1,
  23322. cap: cap,
  23323. updatable: updatable,
  23324. sideOrientation: sideOrientation,
  23325. instance: instance
  23326. };
  23327. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23328. };
  23329. /**
  23330. * Creates a polyhedron mesh.
  23331. * Please consider using the same method from the MeshBuilder class instead.
  23332. * 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
  23333. * to choose the wanted type.
  23334. * The parameter `size` (positive float, default 1) sets the polygon size.
  23335. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23336. * 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`.
  23337. * 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
  23338. * 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)`).
  23339. * 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
  23340. * 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.
  23341. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23342. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23344. */
  23345. Mesh.CreatePolyhedron = function (name, options, scene) {
  23346. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23347. };
  23348. /**
  23349. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23350. * Please consider using the same method from the MeshBuilder class instead.
  23351. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23352. * 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`).
  23353. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23354. * 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.
  23355. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23356. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23357. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23358. */
  23359. Mesh.CreateIcoSphere = function (name, options, scene) {
  23360. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23361. };
  23362. /**
  23363. * Creates a decal mesh.
  23364. * Please consider using the same method from the MeshBuilder class instead.
  23365. * 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.
  23366. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23367. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23368. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23369. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23370. */
  23371. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23372. var options = {
  23373. position: position,
  23374. normal: normal,
  23375. size: size,
  23376. angle: angle
  23377. };
  23378. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23379. };
  23380. // Skeletons
  23381. /**
  23382. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23383. */
  23384. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23385. var source;
  23386. if (!this._sourcePositions) {
  23387. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23388. this._sourcePositions = new Float32Array(source);
  23389. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23390. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23391. }
  23392. }
  23393. return this._sourcePositions;
  23394. };
  23395. /**
  23396. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23397. */
  23398. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23399. var source;
  23400. if (!this._sourceNormals) {
  23401. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23402. this._sourceNormals = new Float32Array(source);
  23403. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23404. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23405. }
  23406. }
  23407. return this._sourceNormals;
  23408. };
  23409. /**
  23410. * Updates the vertex buffer by applying transformation from the bones.
  23411. * Returns the Mesh.
  23412. *
  23413. * @param {skeleton} skeleton to apply
  23414. */
  23415. Mesh.prototype.applySkeleton = function (skeleton) {
  23416. if (!this.geometry) {
  23417. return this;
  23418. }
  23419. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23420. return this;
  23421. }
  23422. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23423. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23424. return this;
  23425. }
  23426. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23427. return this;
  23428. }
  23429. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23430. return this;
  23431. }
  23432. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23433. return this;
  23434. }
  23435. if (!this._sourcePositions) {
  23436. var submeshes = this.subMeshes.slice();
  23437. this.setPositionsForCPUSkinning();
  23438. this.subMeshes = submeshes;
  23439. }
  23440. if (!this._sourceNormals) {
  23441. this.setNormalsForCPUSkinning();
  23442. }
  23443. // positionsData checks for not being Float32Array will only pass at most once
  23444. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23445. if (!(positionsData instanceof Float32Array)) {
  23446. positionsData = new Float32Array(positionsData);
  23447. }
  23448. // normalsData checks for not being Float32Array will only pass at most once
  23449. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23450. if (!(normalsData instanceof Float32Array)) {
  23451. normalsData = new Float32Array(normalsData);
  23452. }
  23453. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23454. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23455. var needExtras = this.numBoneInfluencers > 4;
  23456. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23457. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23458. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23459. var tempVector3 = BABYLON.Vector3.Zero();
  23460. var finalMatrix = new BABYLON.Matrix();
  23461. var tempMatrix = new BABYLON.Matrix();
  23462. var matWeightIdx = 0;
  23463. var inf;
  23464. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23465. var weight;
  23466. for (inf = 0; inf < 4; inf++) {
  23467. weight = matricesWeightsData[matWeightIdx + inf];
  23468. if (weight > 0) {
  23469. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23470. finalMatrix.addToSelf(tempMatrix);
  23471. }
  23472. else
  23473. break;
  23474. }
  23475. if (needExtras) {
  23476. for (inf = 0; inf < 4; inf++) {
  23477. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23478. if (weight > 0) {
  23479. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23480. finalMatrix.addToSelf(tempMatrix);
  23481. }
  23482. else
  23483. break;
  23484. }
  23485. }
  23486. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23487. tempVector3.toArray(positionsData, index);
  23488. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23489. tempVector3.toArray(normalsData, index);
  23490. finalMatrix.reset();
  23491. }
  23492. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23493. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23494. return this;
  23495. };
  23496. // Tools
  23497. /**
  23498. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23499. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23500. */
  23501. Mesh.MinMax = function (meshes) {
  23502. var minVector = null;
  23503. var maxVector = null;
  23504. meshes.forEach(function (mesh, index, array) {
  23505. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23506. if (!minVector) {
  23507. minVector = boundingBox.minimumWorld;
  23508. maxVector = boundingBox.maximumWorld;
  23509. }
  23510. else {
  23511. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23512. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23513. }
  23514. });
  23515. return {
  23516. min: minVector,
  23517. max: maxVector
  23518. };
  23519. };
  23520. /**
  23521. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23522. */
  23523. Mesh.Center = function (meshesOrMinMaxVector) {
  23524. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23525. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23526. };
  23527. /**
  23528. * Merge the array of meshes into a single mesh for performance reasons.
  23529. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23530. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23531. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23532. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23533. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23534. */
  23535. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23536. if (disposeSource === void 0) { disposeSource = true; }
  23537. var index;
  23538. if (!allow32BitsIndices) {
  23539. var totalVertices = 0;
  23540. // Counting vertices
  23541. for (index = 0; index < meshes.length; index++) {
  23542. if (meshes[index]) {
  23543. totalVertices += meshes[index].getTotalVertices();
  23544. if (totalVertices > 65536) {
  23545. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23546. return null;
  23547. }
  23548. }
  23549. }
  23550. }
  23551. // Merge
  23552. var vertexData;
  23553. var otherVertexData;
  23554. var indiceArray = new Array();
  23555. var source;
  23556. for (index = 0; index < meshes.length; index++) {
  23557. if (meshes[index]) {
  23558. meshes[index].computeWorldMatrix(true);
  23559. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23560. otherVertexData.transform(meshes[index].getWorldMatrix());
  23561. if (vertexData) {
  23562. vertexData.merge(otherVertexData);
  23563. }
  23564. else {
  23565. vertexData = otherVertexData;
  23566. source = meshes[index];
  23567. }
  23568. if (subdivideWithSubMeshes) {
  23569. indiceArray.push(meshes[index].getTotalIndices());
  23570. }
  23571. }
  23572. }
  23573. if (!meshSubclass) {
  23574. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23575. }
  23576. vertexData.applyToMesh(meshSubclass);
  23577. // Setting properties
  23578. meshSubclass.material = source.material;
  23579. meshSubclass.checkCollisions = source.checkCollisions;
  23580. // Cleaning
  23581. if (disposeSource) {
  23582. for (index = 0; index < meshes.length; index++) {
  23583. if (meshes[index]) {
  23584. meshes[index].dispose();
  23585. }
  23586. }
  23587. }
  23588. // Subdivide
  23589. if (subdivideWithSubMeshes) {
  23590. //-- Suppresions du submesh global
  23591. meshSubclass.releaseSubMeshes();
  23592. index = 0;
  23593. var offset = 0;
  23594. //-- aplique la subdivision en fonction du tableau d'indices
  23595. while (index < indiceArray.length) {
  23596. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  23597. offset += indiceArray[index];
  23598. index++;
  23599. }
  23600. }
  23601. return meshSubclass;
  23602. };
  23603. // Consts
  23604. Mesh._FRONTSIDE = 0;
  23605. Mesh._BACKSIDE = 1;
  23606. Mesh._DOUBLESIDE = 2;
  23607. Mesh._DEFAULTSIDE = 0;
  23608. Mesh._NO_CAP = 0;
  23609. Mesh._CAP_START = 1;
  23610. Mesh._CAP_END = 2;
  23611. Mesh._CAP_ALL = 3;
  23612. return Mesh;
  23613. }(BABYLON.AbstractMesh));
  23614. BABYLON.Mesh = Mesh;
  23615. })(BABYLON || (BABYLON = {}));
  23616. //# sourceMappingURL=babylon.mesh.js.map
  23617. var BABYLON;
  23618. (function (BABYLON) {
  23619. var BaseSubMesh = (function () {
  23620. function BaseSubMesh() {
  23621. }
  23622. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  23623. get: function () {
  23624. return this._materialEffect;
  23625. },
  23626. enumerable: true,
  23627. configurable: true
  23628. });
  23629. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  23630. if (this._materialEffect === effect) {
  23631. if (!effect) {
  23632. this._materialDefines = undefined;
  23633. }
  23634. return;
  23635. }
  23636. this._materialDefines = defines;
  23637. this._materialEffect = effect;
  23638. };
  23639. return BaseSubMesh;
  23640. }());
  23641. BABYLON.BaseSubMesh = BaseSubMesh;
  23642. var SubMesh = (function (_super) {
  23643. __extends(SubMesh, _super);
  23644. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  23645. if (createBoundingBox === void 0) { createBoundingBox = true; }
  23646. var _this = _super.call(this) || this;
  23647. _this.materialIndex = materialIndex;
  23648. _this.verticesStart = verticesStart;
  23649. _this.verticesCount = verticesCount;
  23650. _this.indexStart = indexStart;
  23651. _this.indexCount = indexCount;
  23652. _this._renderId = 0;
  23653. _this._mesh = mesh;
  23654. _this._renderingMesh = renderingMesh || mesh;
  23655. mesh.subMeshes.push(_this);
  23656. _this._trianglePlanes = [];
  23657. _this._id = mesh.subMeshes.length - 1;
  23658. if (createBoundingBox) {
  23659. _this.refreshBoundingInfo();
  23660. mesh.computeWorldMatrix(true);
  23661. }
  23662. return _this;
  23663. }
  23664. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  23665. get: function () {
  23666. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  23667. },
  23668. enumerable: true,
  23669. configurable: true
  23670. });
  23671. /**
  23672. * Returns the submesh BoudingInfo object.
  23673. */
  23674. SubMesh.prototype.getBoundingInfo = function () {
  23675. if (this.IsGlobal) {
  23676. return this._mesh.getBoundingInfo();
  23677. }
  23678. return this._boundingInfo;
  23679. };
  23680. /**
  23681. * Sets the submesh BoundingInfo.
  23682. * Return the SubMesh.
  23683. */
  23684. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  23685. this._boundingInfo = boundingInfo;
  23686. return this;
  23687. };
  23688. /**
  23689. * Returns the mesh of the current submesh.
  23690. */
  23691. SubMesh.prototype.getMesh = function () {
  23692. return this._mesh;
  23693. };
  23694. /**
  23695. * Returns the rendering mesh of the submesh.
  23696. */
  23697. SubMesh.prototype.getRenderingMesh = function () {
  23698. return this._renderingMesh;
  23699. };
  23700. /**
  23701. * Returns the submesh material.
  23702. */
  23703. SubMesh.prototype.getMaterial = function () {
  23704. var rootMaterial = this._renderingMesh.material;
  23705. if (rootMaterial && rootMaterial.getSubMaterial) {
  23706. var multiMaterial = rootMaterial;
  23707. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  23708. if (this._currentMaterial !== effectiveMaterial) {
  23709. this._currentMaterial = effectiveMaterial;
  23710. this._materialDefines = undefined;
  23711. }
  23712. return effectiveMaterial;
  23713. }
  23714. if (!rootMaterial) {
  23715. return this._mesh.getScene().defaultMaterial;
  23716. }
  23717. return rootMaterial;
  23718. };
  23719. // Methods
  23720. /**
  23721. * Sets a new updated BoundingInfo object to the submesh.
  23722. * Returns the SubMesh.
  23723. */
  23724. SubMesh.prototype.refreshBoundingInfo = function () {
  23725. this._lastColliderWorldVertices = null;
  23726. if (this.IsGlobal) {
  23727. return;
  23728. }
  23729. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23730. if (!data) {
  23731. this._boundingInfo = this._mesh._boundingInfo;
  23732. return;
  23733. }
  23734. var indices = this._renderingMesh.getIndices();
  23735. var extend;
  23736. //is this the only submesh?
  23737. if (this.indexStart === 0 && this.indexCount === indices.length) {
  23738. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  23739. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  23740. }
  23741. else {
  23742. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  23743. }
  23744. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23745. return this;
  23746. };
  23747. SubMesh.prototype._checkCollision = function (collider) {
  23748. return this.getBoundingInfo()._checkCollision(collider);
  23749. };
  23750. /**
  23751. * Updates the submesh BoundingInfo.
  23752. * Returns the Submesh.
  23753. */
  23754. SubMesh.prototype.updateBoundingInfo = function (world) {
  23755. if (!this.getBoundingInfo()) {
  23756. this.refreshBoundingInfo();
  23757. }
  23758. this.getBoundingInfo().update(world);
  23759. return this;
  23760. };
  23761. /**
  23762. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  23763. * Boolean returned.
  23764. */
  23765. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  23766. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  23767. };
  23768. /**
  23769. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  23770. * Boolean returned.
  23771. */
  23772. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  23773. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  23774. };
  23775. /**
  23776. * Renders the submesh.
  23777. * Returns it.
  23778. */
  23779. SubMesh.prototype.render = function (enableAlphaMode) {
  23780. this._renderingMesh.render(this, enableAlphaMode);
  23781. return this;
  23782. };
  23783. /**
  23784. * Returns a new Index Buffer.
  23785. * Type returned : WebGLBuffer.
  23786. */
  23787. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  23788. if (!this._linesIndexBuffer) {
  23789. var linesIndices = [];
  23790. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23791. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  23792. }
  23793. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  23794. this.linesIndexCount = linesIndices.length;
  23795. }
  23796. return this._linesIndexBuffer;
  23797. };
  23798. /**
  23799. * True is the passed Ray intersects the submesh bounding box.
  23800. * Boolean returned.
  23801. */
  23802. SubMesh.prototype.canIntersects = function (ray) {
  23803. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  23804. };
  23805. /**
  23806. * Returns an object IntersectionInfo.
  23807. */
  23808. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  23809. var intersectInfo = null;
  23810. // LineMesh first as it's also a Mesh...
  23811. if (this._mesh instanceof BABYLON.LinesMesh) {
  23812. var lineMesh = this._mesh;
  23813. // Line test
  23814. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  23815. var p0 = positions[indices[index]];
  23816. var p1 = positions[indices[index + 1]];
  23817. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  23818. if (length < 0) {
  23819. continue;
  23820. }
  23821. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  23822. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  23823. if (fastCheck) {
  23824. break;
  23825. }
  23826. }
  23827. }
  23828. }
  23829. else {
  23830. // Triangles test
  23831. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23832. var p0 = positions[indices[index]];
  23833. var p1 = positions[indices[index + 1]];
  23834. var p2 = positions[indices[index + 2]];
  23835. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  23836. if (currentIntersectInfo) {
  23837. if (currentIntersectInfo.distance < 0) {
  23838. continue;
  23839. }
  23840. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  23841. intersectInfo = currentIntersectInfo;
  23842. intersectInfo.faceId = index / 3;
  23843. if (fastCheck) {
  23844. break;
  23845. }
  23846. }
  23847. }
  23848. }
  23849. }
  23850. return intersectInfo;
  23851. };
  23852. SubMesh.prototype._rebuild = function () {
  23853. if (this._linesIndexBuffer) {
  23854. this._linesIndexBuffer = null;
  23855. }
  23856. };
  23857. // Clone
  23858. /**
  23859. * Creates a new Submesh from the passed Mesh.
  23860. */
  23861. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  23862. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  23863. if (!this.IsGlobal) {
  23864. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  23865. }
  23866. return result;
  23867. };
  23868. // Dispose
  23869. /**
  23870. * Disposes the Submesh.
  23871. * Returns nothing.
  23872. */
  23873. SubMesh.prototype.dispose = function () {
  23874. if (this._linesIndexBuffer) {
  23875. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  23876. this._linesIndexBuffer = null;
  23877. }
  23878. // Remove from mesh
  23879. var index = this._mesh.subMeshes.indexOf(this);
  23880. this._mesh.subMeshes.splice(index, 1);
  23881. };
  23882. // Statics
  23883. /**
  23884. * Creates a new Submesh from the passed parameters :
  23885. * - materialIndex (integer) : the index of the main mesh material.
  23886. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  23887. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  23888. * - mesh (Mesh) : the main mesh to create the submesh from.
  23889. * - renderingMesh (optional Mesh) : rendering mesh.
  23890. */
  23891. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  23892. var minVertexIndex = Number.MAX_VALUE;
  23893. var maxVertexIndex = -Number.MAX_VALUE;
  23894. renderingMesh = renderingMesh || mesh;
  23895. var indices = renderingMesh.getIndices();
  23896. for (var index = startIndex; index < startIndex + indexCount; index++) {
  23897. var vertexIndex = indices[index];
  23898. if (vertexIndex < minVertexIndex)
  23899. minVertexIndex = vertexIndex;
  23900. if (vertexIndex > maxVertexIndex)
  23901. maxVertexIndex = vertexIndex;
  23902. }
  23903. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  23904. };
  23905. return SubMesh;
  23906. }(BaseSubMesh));
  23907. BABYLON.SubMesh = SubMesh;
  23908. })(BABYLON || (BABYLON = {}));
  23909. //# sourceMappingURL=babylon.subMesh.js.map
  23910. var BABYLON;
  23911. (function (BABYLON) {
  23912. var EffectFallbacks = (function () {
  23913. function EffectFallbacks() {
  23914. this._defines = {};
  23915. this._currentRank = 32;
  23916. this._maxRank = -1;
  23917. }
  23918. EffectFallbacks.prototype.unBindMesh = function () {
  23919. this._mesh = null;
  23920. };
  23921. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23922. if (!this._defines[rank]) {
  23923. if (rank < this._currentRank) {
  23924. this._currentRank = rank;
  23925. }
  23926. if (rank > this._maxRank) {
  23927. this._maxRank = rank;
  23928. }
  23929. this._defines[rank] = new Array();
  23930. }
  23931. this._defines[rank].push(define);
  23932. };
  23933. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23934. this._meshRank = rank;
  23935. this._mesh = mesh;
  23936. if (rank < this._currentRank) {
  23937. this._currentRank = rank;
  23938. }
  23939. if (rank > this._maxRank) {
  23940. this._maxRank = rank;
  23941. }
  23942. };
  23943. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23944. get: function () {
  23945. return this._currentRank <= this._maxRank;
  23946. },
  23947. enumerable: true,
  23948. configurable: true
  23949. });
  23950. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23951. // First we try to switch to CPU skinning
  23952. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  23953. this._mesh.computeBonesUsingShaders = false;
  23954. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23955. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23956. var scene = this._mesh.getScene();
  23957. for (var index = 0; index < scene.meshes.length; index++) {
  23958. var otherMesh = scene.meshes[index];
  23959. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  23960. otherMesh.computeBonesUsingShaders = false;
  23961. }
  23962. }
  23963. }
  23964. else {
  23965. var currentFallbacks = this._defines[this._currentRank];
  23966. if (currentFallbacks) {
  23967. for (var index = 0; index < currentFallbacks.length; index++) {
  23968. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23969. }
  23970. }
  23971. this._currentRank++;
  23972. }
  23973. return currentDefines;
  23974. };
  23975. return EffectFallbacks;
  23976. }());
  23977. BABYLON.EffectFallbacks = EffectFallbacks;
  23978. var EffectCreationOptions = (function () {
  23979. function EffectCreationOptions() {
  23980. }
  23981. return EffectCreationOptions;
  23982. }());
  23983. BABYLON.EffectCreationOptions = EffectCreationOptions;
  23984. var Effect = (function () {
  23985. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23986. var _this = this;
  23987. this.uniqueId = 0;
  23988. this.onCompileObservable = new BABYLON.Observable();
  23989. this.onErrorObservable = new BABYLON.Observable();
  23990. this.onBindObservable = new BABYLON.Observable();
  23991. this._uniformBuffersNames = {};
  23992. this._isReady = false;
  23993. this._compilationError = "";
  23994. this.name = baseName;
  23995. if (attributesNamesOrOptions.attributes) {
  23996. var options = attributesNamesOrOptions;
  23997. this._engine = uniformsNamesOrEngine;
  23998. this._attributesNames = options.attributes;
  23999. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24000. this._samplers = options.samplers;
  24001. this.defines = options.defines;
  24002. this.onError = options.onError;
  24003. this.onCompiled = options.onCompiled;
  24004. this._fallbacks = options.fallbacks;
  24005. this._indexParameters = options.indexParameters;
  24006. if (options.uniformBuffersNames) {
  24007. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24008. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24009. }
  24010. }
  24011. }
  24012. else {
  24013. this._engine = engine;
  24014. this.defines = defines;
  24015. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24016. this._samplers = samplers;
  24017. this._attributesNames = attributesNamesOrOptions;
  24018. this.onError = onError;
  24019. this.onCompiled = onCompiled;
  24020. this._indexParameters = indexParameters;
  24021. this._fallbacks = fallbacks;
  24022. }
  24023. this.uniqueId = Effect._uniqueIdSeed++;
  24024. var vertexSource;
  24025. var fragmentSource;
  24026. if (baseName.vertexElement) {
  24027. vertexSource = document.getElementById(baseName.vertexElement);
  24028. if (!vertexSource) {
  24029. vertexSource = baseName.vertexElement;
  24030. }
  24031. }
  24032. else {
  24033. vertexSource = baseName.vertex || baseName;
  24034. }
  24035. if (baseName.fragmentElement) {
  24036. fragmentSource = document.getElementById(baseName.fragmentElement);
  24037. if (!fragmentSource) {
  24038. fragmentSource = baseName.fragmentElement;
  24039. }
  24040. }
  24041. else {
  24042. fragmentSource = baseName.fragment || baseName;
  24043. }
  24044. this._loadVertexShader(vertexSource, function (vertexCode) {
  24045. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24046. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24047. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24048. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24049. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24050. if (baseName) {
  24051. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + migratedVertexCode;
  24052. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + migratedFragmentCode;
  24053. }
  24054. else {
  24055. _this._vertexSourceCode = migratedVertexCode;
  24056. _this._fragmentSourceCode = migratedFragmentCode;
  24057. }
  24058. _this._prepareEffect();
  24059. });
  24060. });
  24061. });
  24062. });
  24063. });
  24064. });
  24065. }
  24066. Object.defineProperty(Effect.prototype, "key", {
  24067. get: function () {
  24068. return this._key;
  24069. },
  24070. enumerable: true,
  24071. configurable: true
  24072. });
  24073. // Properties
  24074. Effect.prototype.isReady = function () {
  24075. return this._isReady;
  24076. };
  24077. Effect.prototype.getEngine = function () {
  24078. return this._engine;
  24079. };
  24080. Effect.prototype.getProgram = function () {
  24081. return this._program;
  24082. };
  24083. Effect.prototype.getAttributesNames = function () {
  24084. return this._attributesNames;
  24085. };
  24086. Effect.prototype.getAttributeLocation = function (index) {
  24087. return this._attributes[index];
  24088. };
  24089. Effect.prototype.getAttributeLocationByName = function (name) {
  24090. var index = this._attributesNames.indexOf(name);
  24091. return this._attributes[index];
  24092. };
  24093. Effect.prototype.getAttributesCount = function () {
  24094. return this._attributes.length;
  24095. };
  24096. Effect.prototype.getUniformIndex = function (uniformName) {
  24097. return this._uniformsNames.indexOf(uniformName);
  24098. };
  24099. Effect.prototype.getUniform = function (uniformName) {
  24100. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24101. };
  24102. Effect.prototype.getSamplers = function () {
  24103. return this._samplers;
  24104. };
  24105. Effect.prototype.getCompilationError = function () {
  24106. return this._compilationError;
  24107. };
  24108. // Methods
  24109. Effect.prototype.executeWhenCompiled = function (func) {
  24110. if (this.isReady()) {
  24111. func(this);
  24112. return;
  24113. }
  24114. this.onCompileObservable.add(function (effect) {
  24115. func(effect);
  24116. });
  24117. };
  24118. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24119. // DOM element ?
  24120. if (vertex instanceof HTMLElement) {
  24121. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24122. callback(vertexCode);
  24123. return;
  24124. }
  24125. // Base64 encoded ?
  24126. if (vertex.substr(0, 7) === "base64:") {
  24127. var vertexBinary = window.atob(vertex.substr(7));
  24128. callback(vertexBinary);
  24129. return;
  24130. }
  24131. // Is in local store ?
  24132. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24133. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24134. return;
  24135. }
  24136. var vertexShaderUrl;
  24137. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24138. vertexShaderUrl = vertex;
  24139. }
  24140. else {
  24141. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24142. }
  24143. // Vertex shader
  24144. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24145. };
  24146. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24147. // DOM element ?
  24148. if (fragment instanceof HTMLElement) {
  24149. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24150. callback(fragmentCode);
  24151. return;
  24152. }
  24153. // Base64 encoded ?
  24154. if (fragment.substr(0, 7) === "base64:") {
  24155. var fragmentBinary = window.atob(fragment.substr(7));
  24156. callback(fragmentBinary);
  24157. return;
  24158. }
  24159. // Is in local store ?
  24160. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24161. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24162. return;
  24163. }
  24164. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24165. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24166. return;
  24167. }
  24168. var fragmentShaderUrl;
  24169. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24170. fragmentShaderUrl = fragment;
  24171. }
  24172. else {
  24173. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24174. }
  24175. // Fragment shader
  24176. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24177. };
  24178. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24179. // Rebuild shaders source code
  24180. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24181. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24182. vertexCode = prefix + vertexCode;
  24183. fragmentCode = prefix + fragmentCode;
  24184. // Number lines of shaders source code
  24185. var i = 2;
  24186. var regex = /\n/gm;
  24187. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24188. i = 2;
  24189. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24190. // Dump shaders name and formatted source code
  24191. if (this.name.vertexElement) {
  24192. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24193. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24194. }
  24195. else if (this.name.vertex) {
  24196. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24197. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24198. }
  24199. else {
  24200. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24201. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24202. }
  24203. };
  24204. ;
  24205. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24206. var preparedSourceCode = this._processPrecision(sourceCode);
  24207. if (this._engine.webGLVersion == 1) {
  24208. callback(preparedSourceCode);
  24209. return;
  24210. }
  24211. // Already converted
  24212. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24213. callback(preparedSourceCode.replace("#version 300 es", ""));
  24214. return;
  24215. }
  24216. // Remove extensions
  24217. // #extension GL_OES_standard_derivatives : enable
  24218. // #extension GL_EXT_shader_texture_lod : enable
  24219. // #extension GL_EXT_frag_depth : enable
  24220. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  24221. var result = preparedSourceCode.replace(regex, "");
  24222. // Migrate to GLSL v300
  24223. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24224. result = result.replace(/attribute[ \t]/g, "in ");
  24225. result = result.replace(/[ \t]attribute/g, " in");
  24226. if (isFragment) {
  24227. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  24228. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  24229. result = result.replace(/texture2D\(/g, "texture(");
  24230. result = result.replace(/textureCube\(/g, "texture(");
  24231. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24232. result = result.replace(/gl_FragColor/g, "glFragColor");
  24233. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  24234. }
  24235. callback(result);
  24236. };
  24237. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24238. var _this = this;
  24239. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24240. var match = regex.exec(sourceCode);
  24241. var returnValue = new String(sourceCode);
  24242. while (match != null) {
  24243. var includeFile = match[1];
  24244. // Uniform declaration
  24245. if (includeFile.indexOf("__decl__") !== -1) {
  24246. includeFile = includeFile.replace(/__decl__/, "");
  24247. if (this._engine.webGLVersion != 1) {
  24248. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24249. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24250. }
  24251. includeFile = includeFile + "Declaration";
  24252. }
  24253. if (Effect.IncludesShadersStore[includeFile]) {
  24254. // Substitution
  24255. var includeContent = Effect.IncludesShadersStore[includeFile];
  24256. if (match[2]) {
  24257. var splits = match[3].split(",");
  24258. for (var index = 0; index < splits.length; index += 2) {
  24259. var source = new RegExp(splits[index], "g");
  24260. var dest = splits[index + 1];
  24261. includeContent = includeContent.replace(source, dest);
  24262. }
  24263. }
  24264. if (match[4]) {
  24265. var indexString = match[5];
  24266. if (indexString.indexOf("..") !== -1) {
  24267. var indexSplits = indexString.split("..");
  24268. var minIndex = parseInt(indexSplits[0]);
  24269. var maxIndex = parseInt(indexSplits[1]);
  24270. var sourceIncludeContent = includeContent.slice(0);
  24271. includeContent = "";
  24272. if (isNaN(maxIndex)) {
  24273. maxIndex = this._indexParameters[indexSplits[1]];
  24274. }
  24275. for (var i = minIndex; i < maxIndex; i++) {
  24276. if (this._engine.webGLVersion === 1) {
  24277. // Ubo replacement
  24278. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24279. return p1 + "{X}";
  24280. });
  24281. }
  24282. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24283. }
  24284. }
  24285. else {
  24286. if (this._engine.webGLVersion === 1) {
  24287. // Ubo replacement
  24288. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24289. return p1 + "{X}";
  24290. });
  24291. }
  24292. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24293. }
  24294. }
  24295. // Replace
  24296. returnValue = returnValue.replace(match[0], includeContent);
  24297. }
  24298. else {
  24299. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24300. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24301. Effect.IncludesShadersStore[includeFile] = fileContent;
  24302. _this._processIncludes(returnValue, callback);
  24303. });
  24304. return;
  24305. }
  24306. match = regex.exec(sourceCode);
  24307. }
  24308. callback(returnValue);
  24309. };
  24310. Effect.prototype._processPrecision = function (source) {
  24311. if (source.indexOf("precision highp float") === -1) {
  24312. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24313. source = "precision mediump float;\n" + source;
  24314. }
  24315. else {
  24316. source = "precision highp float;\n" + source;
  24317. }
  24318. }
  24319. else {
  24320. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24321. source = source.replace("precision highp float", "precision mediump float");
  24322. }
  24323. }
  24324. return source;
  24325. };
  24326. Effect.prototype._prepareEffect = function () {
  24327. var attributesNames = this._attributesNames;
  24328. var defines = this.defines;
  24329. var fallbacks = this._fallbacks;
  24330. this._valueCache = {};
  24331. try {
  24332. var engine = this._engine;
  24333. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24334. if (engine.webGLVersion > 1) {
  24335. for (var name in this._uniformBuffersNames) {
  24336. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24337. }
  24338. }
  24339. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24340. this._attributes = engine.getAttributes(this._program, attributesNames);
  24341. var index;
  24342. for (index = 0; index < this._samplers.length; index++) {
  24343. var sampler = this.getUniform(this._samplers[index]);
  24344. if (sampler == null) {
  24345. this._samplers.splice(index, 1);
  24346. index--;
  24347. }
  24348. }
  24349. engine.bindSamplers(this);
  24350. this._compilationError = "";
  24351. this._isReady = true;
  24352. if (this.onCompiled) {
  24353. this.onCompiled(this);
  24354. }
  24355. this.onCompileObservable.notifyObservers(this);
  24356. this.onCompileObservable.clear();
  24357. // Unbind mesh reference in fallbacks
  24358. if (this._fallbacks) {
  24359. this._fallbacks.unBindMesh();
  24360. }
  24361. }
  24362. catch (e) {
  24363. this._compilationError = e.message;
  24364. // Let's go through fallbacks then
  24365. BABYLON.Tools.Error("Unable to compile effect:");
  24366. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24367. return " " + uniform;
  24368. }));
  24369. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24370. return " " + attribute;
  24371. }));
  24372. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24373. BABYLON.Tools.Error("Error: " + this._compilationError);
  24374. if (fallbacks && fallbacks.isMoreFallbacks) {
  24375. BABYLON.Tools.Error("Trying next fallback.");
  24376. this.defines = fallbacks.reduce(this.defines);
  24377. this._prepareEffect();
  24378. }
  24379. else {
  24380. if (this.onError) {
  24381. this.onError(this, this._compilationError);
  24382. }
  24383. this.onErrorObservable.notifyObservers(this);
  24384. this.onErrorObservable.clear();
  24385. // Unbind mesh reference in fallbacks
  24386. if (this._fallbacks) {
  24387. this._fallbacks.unBindMesh();
  24388. }
  24389. }
  24390. }
  24391. };
  24392. Object.defineProperty(Effect.prototype, "isSupported", {
  24393. get: function () {
  24394. return this._compilationError === "";
  24395. },
  24396. enumerable: true,
  24397. configurable: true
  24398. });
  24399. Effect.prototype._bindTexture = function (channel, texture) {
  24400. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24401. };
  24402. Effect.prototype.setTexture = function (channel, texture) {
  24403. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24404. };
  24405. Effect.prototype.setTextureArray = function (channel, textures) {
  24406. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24407. var initialPos = this._samplers.indexOf(channel);
  24408. for (var index = 1; index < textures.length; index++) {
  24409. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24410. }
  24411. }
  24412. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24413. };
  24414. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24415. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24416. };
  24417. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24418. var cache = this._valueCache[uniformName];
  24419. var flag = matrix.updateFlag;
  24420. if (cache !== undefined && cache === flag) {
  24421. return false;
  24422. }
  24423. this._valueCache[uniformName] = flag;
  24424. return true;
  24425. };
  24426. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24427. var cache = this._valueCache[uniformName];
  24428. if (!cache) {
  24429. cache = [x, y];
  24430. this._valueCache[uniformName] = cache;
  24431. return true;
  24432. }
  24433. var changed = false;
  24434. if (cache[0] !== x) {
  24435. cache[0] = x;
  24436. changed = true;
  24437. }
  24438. if (cache[1] !== y) {
  24439. cache[1] = y;
  24440. changed = true;
  24441. }
  24442. return changed;
  24443. };
  24444. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24445. var cache = this._valueCache[uniformName];
  24446. if (!cache) {
  24447. cache = [x, y, z];
  24448. this._valueCache[uniformName] = cache;
  24449. return true;
  24450. }
  24451. var changed = false;
  24452. if (cache[0] !== x) {
  24453. cache[0] = x;
  24454. changed = true;
  24455. }
  24456. if (cache[1] !== y) {
  24457. cache[1] = y;
  24458. changed = true;
  24459. }
  24460. if (cache[2] !== z) {
  24461. cache[2] = z;
  24462. changed = true;
  24463. }
  24464. return changed;
  24465. };
  24466. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24467. var cache = this._valueCache[uniformName];
  24468. if (!cache) {
  24469. cache = [x, y, z, w];
  24470. this._valueCache[uniformName] = cache;
  24471. return true;
  24472. }
  24473. var changed = false;
  24474. if (cache[0] !== x) {
  24475. cache[0] = x;
  24476. changed = true;
  24477. }
  24478. if (cache[1] !== y) {
  24479. cache[1] = y;
  24480. changed = true;
  24481. }
  24482. if (cache[2] !== z) {
  24483. cache[2] = z;
  24484. changed = true;
  24485. }
  24486. if (cache[3] !== w) {
  24487. cache[3] = w;
  24488. changed = true;
  24489. }
  24490. return changed;
  24491. };
  24492. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24493. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24494. return;
  24495. }
  24496. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24497. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24498. };
  24499. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24500. this._engine.bindUniformBlock(this._program, blockName, index);
  24501. };
  24502. Effect.prototype.setIntArray = function (uniformName, array) {
  24503. this._valueCache[uniformName] = null;
  24504. this._engine.setIntArray(this.getUniform(uniformName), array);
  24505. return this;
  24506. };
  24507. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24508. this._valueCache[uniformName] = null;
  24509. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24510. return this;
  24511. };
  24512. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24513. this._valueCache[uniformName] = null;
  24514. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24515. return this;
  24516. };
  24517. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24518. this._valueCache[uniformName] = null;
  24519. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24520. return this;
  24521. };
  24522. Effect.prototype.setFloatArray = function (uniformName, array) {
  24523. this._valueCache[uniformName] = null;
  24524. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24525. return this;
  24526. };
  24527. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24528. this._valueCache[uniformName] = null;
  24529. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24530. return this;
  24531. };
  24532. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24533. this._valueCache[uniformName] = null;
  24534. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24535. return this;
  24536. };
  24537. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24538. this._valueCache[uniformName] = null;
  24539. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24540. return this;
  24541. };
  24542. Effect.prototype.setArray = function (uniformName, array) {
  24543. this._valueCache[uniformName] = null;
  24544. this._engine.setArray(this.getUniform(uniformName), array);
  24545. return this;
  24546. };
  24547. Effect.prototype.setArray2 = function (uniformName, array) {
  24548. this._valueCache[uniformName] = null;
  24549. this._engine.setArray2(this.getUniform(uniformName), array);
  24550. return this;
  24551. };
  24552. Effect.prototype.setArray3 = function (uniformName, array) {
  24553. this._valueCache[uniformName] = null;
  24554. this._engine.setArray3(this.getUniform(uniformName), array);
  24555. return this;
  24556. };
  24557. Effect.prototype.setArray4 = function (uniformName, array) {
  24558. this._valueCache[uniformName] = null;
  24559. this._engine.setArray4(this.getUniform(uniformName), array);
  24560. return this;
  24561. };
  24562. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24563. if (!matrices) {
  24564. return;
  24565. }
  24566. this._valueCache[uniformName] = null;
  24567. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24568. return this;
  24569. };
  24570. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24571. if (this._cacheMatrix(uniformName, matrix)) {
  24572. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24573. }
  24574. return this;
  24575. };
  24576. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24577. this._valueCache[uniformName] = null;
  24578. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24579. return this;
  24580. };
  24581. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24582. this._valueCache[uniformName] = null;
  24583. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24584. return this;
  24585. };
  24586. Effect.prototype.setFloat = function (uniformName, value) {
  24587. var cache = this._valueCache[uniformName];
  24588. if (cache !== undefined && cache === value)
  24589. return this;
  24590. this._valueCache[uniformName] = value;
  24591. this._engine.setFloat(this.getUniform(uniformName), value);
  24592. return this;
  24593. };
  24594. Effect.prototype.setBool = function (uniformName, bool) {
  24595. var cache = this._valueCache[uniformName];
  24596. if (cache !== undefined && cache === bool)
  24597. return this;
  24598. this._valueCache[uniformName] = bool;
  24599. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24600. return this;
  24601. };
  24602. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24603. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24604. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24605. }
  24606. return this;
  24607. };
  24608. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24609. if (this._cacheFloat2(uniformName, x, y)) {
  24610. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24611. }
  24612. return this;
  24613. };
  24614. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24615. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24616. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24617. }
  24618. return this;
  24619. };
  24620. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24621. if (this._cacheFloat3(uniformName, x, y, z)) {
  24622. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24623. }
  24624. return this;
  24625. };
  24626. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24627. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24628. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24629. }
  24630. return this;
  24631. };
  24632. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24633. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24634. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24635. }
  24636. return this;
  24637. };
  24638. Effect.prototype.setColor3 = function (uniformName, color3) {
  24639. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24640. this._engine.setColor3(this.getUniform(uniformName), color3);
  24641. }
  24642. return this;
  24643. };
  24644. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24645. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24646. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24647. }
  24648. return this;
  24649. };
  24650. Effect.ResetCache = function () {
  24651. Effect._baseCache = {};
  24652. };
  24653. Effect._uniqueIdSeed = 0;
  24654. Effect._baseCache = {};
  24655. // Statics
  24656. Effect.ShadersStore = {};
  24657. Effect.IncludesShadersStore = {};
  24658. return Effect;
  24659. }());
  24660. BABYLON.Effect = Effect;
  24661. })(BABYLON || (BABYLON = {}));
  24662. //# sourceMappingURL=babylon.effect.js.map
  24663. var BABYLON;
  24664. (function (BABYLON) {
  24665. var MaterialHelper = (function () {
  24666. function MaterialHelper() {
  24667. }
  24668. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24669. defines._needUVs = true;
  24670. defines[key] = true;
  24671. if (texture.getTextureMatrix().isIdentity(true)) {
  24672. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24673. if (texture.coordinatesIndex === 0) {
  24674. defines["MAINUV1"] = true;
  24675. }
  24676. else {
  24677. defines["MAINUV2"] = true;
  24678. }
  24679. }
  24680. else {
  24681. defines[key + "DIRECTUV"] = 0;
  24682. }
  24683. };
  24684. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24685. var matrix = texture.getTextureMatrix();
  24686. if (!matrix.isIdentity(true)) {
  24687. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  24688. }
  24689. };
  24690. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  24691. if (defines._areMiscDirty) {
  24692. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  24693. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  24694. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  24695. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  24696. }
  24697. };
  24698. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  24699. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  24700. var changed = false;
  24701. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  24702. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  24703. changed = true;
  24704. }
  24705. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  24706. defines["ALPHATEST"] = !defines["ALPHATEST"];
  24707. changed = true;
  24708. }
  24709. if (defines["INSTANCES"] !== useInstances) {
  24710. defines["INSTANCES"] = useInstances;
  24711. changed = true;
  24712. }
  24713. if (changed) {
  24714. defines.markAsUnprocessed();
  24715. }
  24716. };
  24717. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  24718. if (useMorphTargets === void 0) { useMorphTargets = false; }
  24719. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  24720. return false;
  24721. }
  24722. defines._normals = defines._needNormals;
  24723. defines._uvs = defines._needUVs;
  24724. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  24725. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24726. defines["TANGENT"] = true;
  24727. }
  24728. if (defines._needUVs) {
  24729. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  24730. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  24731. }
  24732. else {
  24733. defines["UV1"] = false;
  24734. defines["UV2"] = false;
  24735. }
  24736. if (useVertexColor) {
  24737. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  24738. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  24739. }
  24740. if (useBones) {
  24741. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24742. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  24743. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  24744. }
  24745. else {
  24746. defines["NUM_BONE_INFLUENCERS"] = 0;
  24747. defines["BonesPerMesh"] = 0;
  24748. }
  24749. }
  24750. if (useMorphTargets) {
  24751. if (mesh.morphTargetManager) {
  24752. var manager = mesh.morphTargetManager;
  24753. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  24754. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  24755. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  24756. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  24757. }
  24758. else {
  24759. defines["MORPHTARGETS_TANGENT"] = false;
  24760. defines["MORPHTARGETS_NORMAL"] = false;
  24761. defines["MORPHTARGETS"] = false;
  24762. defines["NUM_MORPH_INFLUENCERS"] = 0;
  24763. }
  24764. }
  24765. return true;
  24766. };
  24767. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  24768. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24769. if (disableLighting === void 0) { disableLighting = false; }
  24770. if (!defines._areLightsDirty) {
  24771. return defines._needNormals;
  24772. }
  24773. var lightIndex = 0;
  24774. var needNormals = false;
  24775. var needRebuild = false;
  24776. var lightmapMode = false;
  24777. var shadowEnabled = false;
  24778. var specularEnabled = false;
  24779. if (scene.lightsEnabled && !disableLighting) {
  24780. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24781. var light = _a[_i];
  24782. needNormals = true;
  24783. if (defines["LIGHT" + lightIndex] === undefined) {
  24784. needRebuild = true;
  24785. }
  24786. defines["LIGHT" + lightIndex] = true;
  24787. defines["SPOTLIGHT" + lightIndex] = false;
  24788. defines["HEMILIGHT" + lightIndex] = false;
  24789. defines["POINTLIGHT" + lightIndex] = false;
  24790. defines["DIRLIGHT" + lightIndex] = false;
  24791. var type;
  24792. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  24793. type = "SPOTLIGHT" + lightIndex;
  24794. }
  24795. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  24796. type = "HEMILIGHT" + lightIndex;
  24797. }
  24798. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  24799. type = "POINTLIGHT" + lightIndex;
  24800. }
  24801. else {
  24802. type = "DIRLIGHT" + lightIndex;
  24803. }
  24804. defines[type] = true;
  24805. // Specular
  24806. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  24807. specularEnabled = true;
  24808. }
  24809. // Shadows
  24810. defines["SHADOW" + lightIndex] = false;
  24811. defines["SHADOWPCF" + lightIndex] = false;
  24812. defines["SHADOWESM" + lightIndex] = false;
  24813. defines["SHADOWCUBE" + lightIndex] = false;
  24814. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  24815. var shadowGenerator = light.getShadowGenerator();
  24816. if (shadowGenerator) {
  24817. shadowEnabled = true;
  24818. shadowGenerator.prepareDefines(defines, lightIndex);
  24819. }
  24820. }
  24821. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24822. lightmapMode = true;
  24823. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24824. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  24825. }
  24826. else {
  24827. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  24828. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  24829. }
  24830. lightIndex++;
  24831. if (lightIndex === maxSimultaneousLights)
  24832. break;
  24833. }
  24834. }
  24835. defines["SPECULARTERM"] = specularEnabled;
  24836. defines["SHADOWS"] = shadowEnabled;
  24837. // Resetting all other lights if any
  24838. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  24839. if (defines["LIGHT" + index] !== undefined) {
  24840. defines["LIGHT" + index] = false;
  24841. defines["HEMILIGHT" + lightIndex] = false;
  24842. defines["POINTLIGHT" + lightIndex] = false;
  24843. defines["DIRLIGHT" + lightIndex] = false;
  24844. defines["SPOTLIGHT" + lightIndex] = false;
  24845. defines["SHADOW" + lightIndex] = false;
  24846. }
  24847. }
  24848. var caps = scene.getEngine().getCaps();
  24849. if (defines["SHADOWFLOAT"] === undefined) {
  24850. needRebuild = true;
  24851. }
  24852. defines["SHADOWFLOAT"] = shadowEnabled &&
  24853. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  24854. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  24855. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  24856. if (needRebuild) {
  24857. defines.rebuild();
  24858. }
  24859. return needNormals;
  24860. };
  24861. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  24862. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24863. var uniformsList, uniformBuffersList, samplersList, defines;
  24864. if (uniformsListOrOptions.uniformsNames) {
  24865. var options = uniformsListOrOptions;
  24866. uniformsList = options.uniformsNames;
  24867. uniformBuffersList = options.uniformBuffersNames;
  24868. samplersList = options.samplers;
  24869. defines = options.defines;
  24870. maxSimultaneousLights = options.maxSimultaneousLights;
  24871. }
  24872. else {
  24873. uniformsList = uniformsListOrOptions;
  24874. }
  24875. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24876. if (!defines["LIGHT" + lightIndex]) {
  24877. break;
  24878. }
  24879. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  24880. if (uniformBuffersList) {
  24881. uniformBuffersList.push("Light" + lightIndex);
  24882. }
  24883. samplersList.push("shadowSampler" + lightIndex);
  24884. }
  24885. if (defines["NUM_MORPH_INFLUENCERS"]) {
  24886. uniformsList.push("morphTargetInfluences");
  24887. }
  24888. };
  24889. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24890. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24891. if (!defines["SHADOWS"]) {
  24892. return;
  24893. }
  24894. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24895. if (!defines["LIGHT" + lightIndex]) {
  24896. break;
  24897. }
  24898. if (lightIndex > 0) {
  24899. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24900. }
  24901. if (defines["SHADOW" + lightIndex]) {
  24902. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24903. }
  24904. if (defines["SHADOWPCF" + lightIndex]) {
  24905. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24906. }
  24907. if (defines["SHADOWESM" + lightIndex]) {
  24908. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  24909. }
  24910. }
  24911. };
  24912. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  24913. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  24914. if (influencers > 0) {
  24915. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  24916. var manager = mesh.morphTargetManager;
  24917. var normal = manager.supportsNormals && defines["NORMAL"];
  24918. var tangent = manager.supportsTangents && defines["TANGENT"];
  24919. for (var index = 0; index < influencers; index++) {
  24920. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  24921. if (normal) {
  24922. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  24923. }
  24924. if (tangent) {
  24925. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  24926. }
  24927. if (attribs.length > maxAttributesCount) {
  24928. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  24929. }
  24930. }
  24931. }
  24932. };
  24933. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24934. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24935. fallbacks.addCPUSkinningFallback(0, mesh);
  24936. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24937. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24938. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24939. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24940. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24941. }
  24942. }
  24943. };
  24944. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24945. if (defines["INSTANCES"]) {
  24946. attribs.push("world0");
  24947. attribs.push("world1");
  24948. attribs.push("world2");
  24949. attribs.push("world3");
  24950. }
  24951. };
  24952. // Bindings
  24953. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  24954. if (light.shadowEnabled && mesh.receiveShadows) {
  24955. var shadowGenerator = light.getShadowGenerator();
  24956. if (shadowGenerator) {
  24957. shadowGenerator.bindShadowLight(lightIndex, effect);
  24958. }
  24959. }
  24960. };
  24961. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24962. light.transferToEffect(effect, lightIndex + "");
  24963. };
  24964. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  24965. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24966. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  24967. var lightIndex = 0;
  24968. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24969. var light = _a[_i];
  24970. var scaledIntensity = light.getScaledIntensity();
  24971. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  24972. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24973. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  24974. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  24975. if (defines["SPECULARTERM"]) {
  24976. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  24977. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  24978. }
  24979. // Shadows
  24980. if (scene.shadowsEnabled) {
  24981. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  24982. }
  24983. light._uniformBuffer.update();
  24984. lightIndex++;
  24985. if (lightIndex === maxSimultaneousLights)
  24986. break;
  24987. }
  24988. };
  24989. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24990. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24991. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24992. effect.setColor3("vFogColor", scene.fogColor);
  24993. }
  24994. };
  24995. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24996. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24997. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  24998. if (matrices) {
  24999. effect.setMatrices("mBones", matrices);
  25000. }
  25001. }
  25002. };
  25003. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25004. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25005. return;
  25006. }
  25007. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25008. };
  25009. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25010. if (defines["LOGARITHMICDEPTH"]) {
  25011. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25012. }
  25013. };
  25014. MaterialHelper.BindClipPlane = function (effect, scene) {
  25015. if (scene.clipPlane) {
  25016. var clipPlane = scene.clipPlane;
  25017. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25018. }
  25019. };
  25020. return MaterialHelper;
  25021. }());
  25022. BABYLON.MaterialHelper = MaterialHelper;
  25023. })(BABYLON || (BABYLON = {}));
  25024. //# sourceMappingURL=babylon.materialHelper.js.map
  25025. var BABYLON;
  25026. (function (BABYLON) {
  25027. var MaterialDefines = (function () {
  25028. function MaterialDefines() {
  25029. this._isDirty = true;
  25030. this._areLightsDirty = true;
  25031. this._areAttributesDirty = true;
  25032. this._areTexturesDirty = true;
  25033. this._areFresnelDirty = true;
  25034. this._areMiscDirty = true;
  25035. this._areImageProcessingDirty = true;
  25036. this._normals = false;
  25037. this._uvs = false;
  25038. this._needNormals = false;
  25039. this._needUVs = false;
  25040. }
  25041. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25042. get: function () {
  25043. return this._isDirty;
  25044. },
  25045. enumerable: true,
  25046. configurable: true
  25047. });
  25048. MaterialDefines.prototype.markAsProcessed = function () {
  25049. this._isDirty = false;
  25050. this._areAttributesDirty = false;
  25051. this._areTexturesDirty = false;
  25052. this._areFresnelDirty = false;
  25053. this._areLightsDirty = false;
  25054. this._areMiscDirty = false;
  25055. this._areImageProcessingDirty = false;
  25056. };
  25057. MaterialDefines.prototype.markAsUnprocessed = function () {
  25058. this._isDirty = true;
  25059. };
  25060. MaterialDefines.prototype.markAllAsDirty = function () {
  25061. this._areTexturesDirty = true;
  25062. this._areAttributesDirty = true;
  25063. this._areLightsDirty = true;
  25064. this._areFresnelDirty = true;
  25065. this._areMiscDirty = true;
  25066. this._areImageProcessingDirty = true;
  25067. this._isDirty = true;
  25068. };
  25069. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25070. this._areImageProcessingDirty = true;
  25071. this._isDirty = true;
  25072. };
  25073. MaterialDefines.prototype.markAsLightDirty = function () {
  25074. this._areLightsDirty = true;
  25075. this._isDirty = true;
  25076. };
  25077. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25078. this._areAttributesDirty = true;
  25079. this._isDirty = true;
  25080. };
  25081. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25082. this._areTexturesDirty = true;
  25083. this._isDirty = true;
  25084. };
  25085. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25086. this._areFresnelDirty = true;
  25087. this._isDirty = true;
  25088. };
  25089. MaterialDefines.prototype.markAsMiscDirty = function () {
  25090. this._areMiscDirty = true;
  25091. this._isDirty = true;
  25092. };
  25093. MaterialDefines.prototype.rebuild = function () {
  25094. if (this._keys) {
  25095. delete this._keys;
  25096. }
  25097. this._keys = [];
  25098. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25099. var key = _a[_i];
  25100. if (key[0] === "_") {
  25101. continue;
  25102. }
  25103. this._keys.push(key);
  25104. }
  25105. };
  25106. MaterialDefines.prototype.isEqual = function (other) {
  25107. if (this._keys.length !== other._keys.length) {
  25108. return false;
  25109. }
  25110. for (var index = 0; index < this._keys.length; index++) {
  25111. var prop = this._keys[index];
  25112. if (this[prop] !== other[prop]) {
  25113. return false;
  25114. }
  25115. }
  25116. return true;
  25117. };
  25118. MaterialDefines.prototype.cloneTo = function (other) {
  25119. if (this._keys.length !== other._keys.length) {
  25120. other._keys = this._keys.slice(0);
  25121. }
  25122. for (var index = 0; index < this._keys.length; index++) {
  25123. var prop = this._keys[index];
  25124. other[prop] = this[prop];
  25125. }
  25126. };
  25127. MaterialDefines.prototype.reset = function () {
  25128. for (var index = 0; index < this._keys.length; index++) {
  25129. var prop = this._keys[index];
  25130. if (typeof (this[prop]) === "number") {
  25131. this[prop] = 0;
  25132. }
  25133. else {
  25134. this[prop] = false;
  25135. }
  25136. }
  25137. };
  25138. MaterialDefines.prototype.toString = function () {
  25139. var result = "";
  25140. for (var index = 0; index < this._keys.length; index++) {
  25141. var prop = this._keys[index];
  25142. var value = this[prop];
  25143. if (typeof (value) === "number") {
  25144. result += "#define " + prop + " " + this[prop] + "\n";
  25145. }
  25146. else if (value) {
  25147. result += "#define " + prop + "\n";
  25148. }
  25149. }
  25150. return result;
  25151. };
  25152. return MaterialDefines;
  25153. }());
  25154. BABYLON.MaterialDefines = MaterialDefines;
  25155. var Material = (function () {
  25156. function Material(name, scene, doNotAdd) {
  25157. this.checkReadyOnEveryCall = false;
  25158. this.checkReadyOnlyOnce = false;
  25159. this.state = "";
  25160. this.alpha = 1.0;
  25161. this._backFaceCulling = true;
  25162. this.doNotSerialize = false;
  25163. this.storeEffectOnSubMeshes = false;
  25164. /**
  25165. * An event triggered when the material is disposed.
  25166. * @type {BABYLON.Observable}
  25167. */
  25168. this.onDisposeObservable = new BABYLON.Observable();
  25169. /**
  25170. * An event triggered when the material is bound.
  25171. * @type {BABYLON.Observable}
  25172. */
  25173. this.onBindObservable = new BABYLON.Observable();
  25174. /**
  25175. * An event triggered when the material is unbound.
  25176. * @type {BABYLON.Observable}
  25177. */
  25178. this.onUnBindObservable = new BABYLON.Observable();
  25179. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25180. this.disableDepthWrite = false;
  25181. this._fogEnabled = true;
  25182. this.pointSize = 1.0;
  25183. this.zOffset = 0;
  25184. this._wasPreviouslyReady = false;
  25185. this._fillMode = Material.TriangleFillMode;
  25186. this.name = name;
  25187. this.id = name || BABYLON.Tools.RandomId();
  25188. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25189. if (this._scene.useRightHandedSystem) {
  25190. this.sideOrientation = Material.ClockWiseSideOrientation;
  25191. }
  25192. else {
  25193. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25194. }
  25195. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25196. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  25197. if (!doNotAdd) {
  25198. this._scene.materials.push(this);
  25199. }
  25200. }
  25201. Object.defineProperty(Material, "TriangleFillMode", {
  25202. get: function () {
  25203. return Material._TriangleFillMode;
  25204. },
  25205. enumerable: true,
  25206. configurable: true
  25207. });
  25208. Object.defineProperty(Material, "WireFrameFillMode", {
  25209. get: function () {
  25210. return Material._WireFrameFillMode;
  25211. },
  25212. enumerable: true,
  25213. configurable: true
  25214. });
  25215. Object.defineProperty(Material, "PointFillMode", {
  25216. get: function () {
  25217. return Material._PointFillMode;
  25218. },
  25219. enumerable: true,
  25220. configurable: true
  25221. });
  25222. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25223. get: function () {
  25224. return Material._ClockWiseSideOrientation;
  25225. },
  25226. enumerable: true,
  25227. configurable: true
  25228. });
  25229. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25230. get: function () {
  25231. return Material._CounterClockWiseSideOrientation;
  25232. },
  25233. enumerable: true,
  25234. configurable: true
  25235. });
  25236. Object.defineProperty(Material, "TextureDirtyFlag", {
  25237. get: function () {
  25238. return Material._TextureDirtyFlag;
  25239. },
  25240. enumerable: true,
  25241. configurable: true
  25242. });
  25243. Object.defineProperty(Material, "LightDirtyFlag", {
  25244. get: function () {
  25245. return Material._LightDirtyFlag;
  25246. },
  25247. enumerable: true,
  25248. configurable: true
  25249. });
  25250. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25251. get: function () {
  25252. return Material._FresnelDirtyFlag;
  25253. },
  25254. enumerable: true,
  25255. configurable: true
  25256. });
  25257. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25258. get: function () {
  25259. return Material._AttributesDirtyFlag;
  25260. },
  25261. enumerable: true,
  25262. configurable: true
  25263. });
  25264. Object.defineProperty(Material, "MiscDirtyFlag", {
  25265. get: function () {
  25266. return Material._MiscDirtyFlag;
  25267. },
  25268. enumerable: true,
  25269. configurable: true
  25270. });
  25271. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25272. get: function () {
  25273. return this._backFaceCulling;
  25274. },
  25275. set: function (value) {
  25276. if (this._backFaceCulling === value) {
  25277. return;
  25278. }
  25279. this._backFaceCulling = value;
  25280. this.markAsDirty(Material.TextureDirtyFlag);
  25281. },
  25282. enumerable: true,
  25283. configurable: true
  25284. });
  25285. Object.defineProperty(Material.prototype, "onDispose", {
  25286. set: function (callback) {
  25287. if (this._onDisposeObserver) {
  25288. this.onDisposeObservable.remove(this._onDisposeObserver);
  25289. }
  25290. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25291. },
  25292. enumerable: true,
  25293. configurable: true
  25294. });
  25295. Object.defineProperty(Material.prototype, "onBind", {
  25296. set: function (callback) {
  25297. if (this._onBindObserver) {
  25298. this.onBindObservable.remove(this._onBindObserver);
  25299. }
  25300. this._onBindObserver = this.onBindObservable.add(callback);
  25301. },
  25302. enumerable: true,
  25303. configurable: true
  25304. });
  25305. Object.defineProperty(Material.prototype, "fogEnabled", {
  25306. get: function () {
  25307. return this._fogEnabled;
  25308. },
  25309. set: function (value) {
  25310. if (this._fogEnabled === value) {
  25311. return;
  25312. }
  25313. this._fogEnabled = value;
  25314. this.markAsDirty(Material.MiscDirtyFlag);
  25315. },
  25316. enumerable: true,
  25317. configurable: true
  25318. });
  25319. Object.defineProperty(Material.prototype, "wireframe", {
  25320. get: function () {
  25321. return this._fillMode === Material.WireFrameFillMode;
  25322. },
  25323. set: function (value) {
  25324. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25325. },
  25326. enumerable: true,
  25327. configurable: true
  25328. });
  25329. Object.defineProperty(Material.prototype, "pointsCloud", {
  25330. get: function () {
  25331. return this._fillMode === Material.PointFillMode;
  25332. },
  25333. set: function (value) {
  25334. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25335. },
  25336. enumerable: true,
  25337. configurable: true
  25338. });
  25339. Object.defineProperty(Material.prototype, "fillMode", {
  25340. get: function () {
  25341. return this._fillMode;
  25342. },
  25343. set: function (value) {
  25344. if (this._fillMode === value) {
  25345. return;
  25346. }
  25347. this._fillMode = value;
  25348. this.markAsDirty(Material.MiscDirtyFlag);
  25349. },
  25350. enumerable: true,
  25351. configurable: true
  25352. });
  25353. /**
  25354. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25355. * subclasses should override adding information pertainent to themselves
  25356. */
  25357. Material.prototype.toString = function (fullDetails) {
  25358. var ret = "Name: " + this.name;
  25359. if (fullDetails) {
  25360. }
  25361. return ret;
  25362. };
  25363. /**
  25364. * Child classes can use it to update shaders
  25365. */
  25366. Material.prototype.getClassName = function () {
  25367. return "Material";
  25368. };
  25369. Object.defineProperty(Material.prototype, "isFrozen", {
  25370. get: function () {
  25371. return this.checkReadyOnlyOnce;
  25372. },
  25373. enumerable: true,
  25374. configurable: true
  25375. });
  25376. Material.prototype.freeze = function () {
  25377. this.checkReadyOnlyOnce = true;
  25378. };
  25379. Material.prototype.unfreeze = function () {
  25380. this.checkReadyOnlyOnce = false;
  25381. };
  25382. Material.prototype.isReady = function (mesh, useInstances) {
  25383. return true;
  25384. };
  25385. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25386. return false;
  25387. };
  25388. Material.prototype.getEffect = function () {
  25389. return this._effect;
  25390. };
  25391. Material.prototype.getScene = function () {
  25392. return this._scene;
  25393. };
  25394. Material.prototype.needAlphaBlending = function () {
  25395. return (this.alpha < 1.0);
  25396. };
  25397. Material.prototype.needAlphaTesting = function () {
  25398. return false;
  25399. };
  25400. Material.prototype.getAlphaTestTexture = function () {
  25401. return null;
  25402. };
  25403. Material.prototype.markDirty = function () {
  25404. this._wasPreviouslyReady = false;
  25405. };
  25406. Material.prototype._preBind = function (effect) {
  25407. var engine = this._scene.getEngine();
  25408. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25409. engine.enableEffect(effect ? effect : this._effect);
  25410. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25411. };
  25412. Material.prototype.bind = function (world, mesh) {
  25413. };
  25414. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25415. };
  25416. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25417. };
  25418. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25419. sceneUbo.bindToEffect(effect, "Scene");
  25420. };
  25421. Material.prototype.bindView = function (effect) {
  25422. if (!this._useUBO) {
  25423. effect.setMatrix("view", this.getScene().getViewMatrix());
  25424. }
  25425. else {
  25426. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25427. }
  25428. };
  25429. Material.prototype.bindViewProjection = function (effect) {
  25430. if (!this._useUBO) {
  25431. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25432. }
  25433. else {
  25434. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25435. }
  25436. };
  25437. Material.prototype._afterBind = function (mesh) {
  25438. this._scene._cachedMaterial = this;
  25439. if (mesh) {
  25440. this._scene._cachedVisibility = mesh.visibility;
  25441. }
  25442. else {
  25443. this._scene._cachedVisibility = 1;
  25444. }
  25445. this.onBindObservable.notifyObservers(mesh);
  25446. if (this.disableDepthWrite) {
  25447. var engine = this._scene.getEngine();
  25448. this._cachedDepthWriteState = engine.getDepthWrite();
  25449. engine.setDepthWrite(false);
  25450. }
  25451. };
  25452. Material.prototype.unbind = function () {
  25453. this.onUnBindObservable.notifyObservers(this);
  25454. if (this.disableDepthWrite) {
  25455. var engine = this._scene.getEngine();
  25456. engine.setDepthWrite(this._cachedDepthWriteState);
  25457. }
  25458. };
  25459. Material.prototype.getActiveTextures = function () {
  25460. return [];
  25461. };
  25462. Material.prototype.hasTexture = function (texture) {
  25463. return false;
  25464. };
  25465. Material.prototype.clone = function (name) {
  25466. return null;
  25467. };
  25468. Material.prototype.getBindedMeshes = function () {
  25469. var result = new Array();
  25470. for (var index = 0; index < this._scene.meshes.length; index++) {
  25471. var mesh = this._scene.meshes[index];
  25472. if (mesh.material === this) {
  25473. result.push(mesh);
  25474. }
  25475. }
  25476. return result;
  25477. };
  25478. /**
  25479. * Force shader compilation including textures ready check
  25480. */
  25481. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25482. var _this = this;
  25483. var subMesh = new BABYLON.BaseSubMesh();
  25484. var scene = this.getScene();
  25485. var engine = scene.getEngine();
  25486. var checkReady = function () {
  25487. if (!_this._scene || !_this._scene.getEngine()) {
  25488. return;
  25489. }
  25490. if (subMesh._materialDefines) {
  25491. subMesh._materialDefines._renderId = -1;
  25492. }
  25493. var alphaTestState = engine.getAlphaTesting();
  25494. var clipPlaneState = scene.clipPlane;
  25495. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25496. if (options && options.clipPlane) {
  25497. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25498. }
  25499. if (_this.storeEffectOnSubMeshes) {
  25500. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25501. if (onCompiled) {
  25502. onCompiled(_this);
  25503. }
  25504. }
  25505. else {
  25506. setTimeout(checkReady, 16);
  25507. }
  25508. }
  25509. else {
  25510. if (_this.isReady(mesh)) {
  25511. if (onCompiled) {
  25512. onCompiled(_this);
  25513. }
  25514. }
  25515. else {
  25516. setTimeout(checkReady, 16);
  25517. }
  25518. }
  25519. engine.setAlphaTesting(alphaTestState);
  25520. if (options && options.clipPlane) {
  25521. scene.clipPlane = clipPlaneState;
  25522. }
  25523. };
  25524. checkReady();
  25525. };
  25526. Material.prototype.markAsDirty = function (flag) {
  25527. if (flag & Material.TextureDirtyFlag) {
  25528. this._markAllSubMeshesAsTexturesDirty();
  25529. }
  25530. if (flag & Material.LightDirtyFlag) {
  25531. this._markAllSubMeshesAsLightsDirty();
  25532. }
  25533. if (flag & Material.FresnelDirtyFlag) {
  25534. this._markAllSubMeshesAsFresnelDirty();
  25535. }
  25536. if (flag & Material.AttributesDirtyFlag) {
  25537. this._markAllSubMeshesAsAttributesDirty();
  25538. }
  25539. if (flag & Material.MiscDirtyFlag) {
  25540. this._markAllSubMeshesAsMiscDirty();
  25541. }
  25542. this.getScene().resetCachedMaterial();
  25543. };
  25544. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25545. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25546. var mesh = _a[_i];
  25547. if (!mesh.subMeshes) {
  25548. continue;
  25549. }
  25550. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25551. var subMesh = _c[_b];
  25552. if (subMesh.getMaterial() !== this) {
  25553. continue;
  25554. }
  25555. if (!subMesh._materialDefines) {
  25556. continue;
  25557. }
  25558. func(subMesh._materialDefines);
  25559. }
  25560. }
  25561. };
  25562. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25563. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25564. };
  25565. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25566. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25567. };
  25568. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25569. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25570. };
  25571. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25572. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25573. };
  25574. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25575. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25576. };
  25577. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  25578. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  25579. };
  25580. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25581. // Animations
  25582. this.getScene().stopAnimation(this);
  25583. // Remove from scene
  25584. var index = this._scene.materials.indexOf(this);
  25585. if (index >= 0) {
  25586. this._scene.materials.splice(index, 1);
  25587. }
  25588. // Remove from meshes
  25589. for (index = 0; index < this._scene.meshes.length; index++) {
  25590. var mesh = this._scene.meshes[index];
  25591. if (mesh.material === this) {
  25592. mesh.material = null;
  25593. if (mesh.geometry) {
  25594. var geometry = mesh.geometry;
  25595. if (this.storeEffectOnSubMeshes) {
  25596. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  25597. var subMesh = _a[_i];
  25598. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  25599. }
  25600. }
  25601. else {
  25602. geometry._releaseVertexArrayObject(this._effect);
  25603. }
  25604. }
  25605. }
  25606. }
  25607. this._uniformBuffer.dispose();
  25608. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25609. if (forceDisposeEffect && this._effect) {
  25610. if (this.storeEffectOnSubMeshes) {
  25611. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25612. var subMesh = _c[_b];
  25613. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  25614. }
  25615. }
  25616. else {
  25617. this._scene.getEngine()._releaseEffect(this._effect);
  25618. }
  25619. this._effect = null;
  25620. }
  25621. // Callback
  25622. this.onDisposeObservable.notifyObservers(this);
  25623. this.onDisposeObservable.clear();
  25624. this.onBindObservable.clear();
  25625. this.onUnBindObservable.clear();
  25626. };
  25627. Material.prototype.serialize = function () {
  25628. return BABYLON.SerializationHelper.Serialize(this);
  25629. };
  25630. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25631. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25632. multiMaterial.id = parsedMultiMaterial.id;
  25633. if (BABYLON.Tags) {
  25634. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25635. }
  25636. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25637. var subMatId = parsedMultiMaterial.materials[matIndex];
  25638. if (subMatId) {
  25639. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25640. }
  25641. else {
  25642. multiMaterial.subMaterials.push(null);
  25643. }
  25644. }
  25645. return multiMaterial;
  25646. };
  25647. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25648. if (!parsedMaterial.customType) {
  25649. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25650. }
  25651. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  25652. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  25653. if (!BABYLON.LegacyPBRMaterial) {
  25654. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25655. return;
  25656. }
  25657. }
  25658. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25659. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25660. ;
  25661. };
  25662. Material._TriangleFillMode = 0;
  25663. Material._WireFrameFillMode = 1;
  25664. Material._PointFillMode = 2;
  25665. Material._ClockWiseSideOrientation = 0;
  25666. Material._CounterClockWiseSideOrientation = 1;
  25667. Material._TextureDirtyFlag = 1;
  25668. Material._LightDirtyFlag = 2;
  25669. Material._FresnelDirtyFlag = 4;
  25670. Material._AttributesDirtyFlag = 8;
  25671. Material._MiscDirtyFlag = 16;
  25672. __decorate([
  25673. BABYLON.serialize()
  25674. ], Material.prototype, "id", void 0);
  25675. __decorate([
  25676. BABYLON.serialize()
  25677. ], Material.prototype, "name", void 0);
  25678. __decorate([
  25679. BABYLON.serialize()
  25680. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25681. __decorate([
  25682. BABYLON.serialize()
  25683. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25684. __decorate([
  25685. BABYLON.serialize()
  25686. ], Material.prototype, "state", void 0);
  25687. __decorate([
  25688. BABYLON.serialize()
  25689. ], Material.prototype, "alpha", void 0);
  25690. __decorate([
  25691. BABYLON.serialize("backFaceCulling")
  25692. ], Material.prototype, "_backFaceCulling", void 0);
  25693. __decorate([
  25694. BABYLON.serialize()
  25695. ], Material.prototype, "sideOrientation", void 0);
  25696. __decorate([
  25697. BABYLON.serialize()
  25698. ], Material.prototype, "alphaMode", void 0);
  25699. __decorate([
  25700. BABYLON.serialize()
  25701. ], Material.prototype, "disableDepthWrite", void 0);
  25702. __decorate([
  25703. BABYLON.serialize("fogEnabled")
  25704. ], Material.prototype, "_fogEnabled", void 0);
  25705. __decorate([
  25706. BABYLON.serialize()
  25707. ], Material.prototype, "pointSize", void 0);
  25708. __decorate([
  25709. BABYLON.serialize()
  25710. ], Material.prototype, "zOffset", void 0);
  25711. __decorate([
  25712. BABYLON.serialize()
  25713. ], Material.prototype, "wireframe", null);
  25714. __decorate([
  25715. BABYLON.serialize()
  25716. ], Material.prototype, "pointsCloud", null);
  25717. __decorate([
  25718. BABYLON.serialize()
  25719. ], Material.prototype, "fillMode", null);
  25720. return Material;
  25721. }());
  25722. BABYLON.Material = Material;
  25723. })(BABYLON || (BABYLON = {}));
  25724. //# sourceMappingURL=babylon.material.js.map
  25725. var BABYLON;
  25726. (function (BABYLON) {
  25727. var UniformBuffer = (function () {
  25728. /**
  25729. * Uniform buffer objects.
  25730. *
  25731. * Handles blocks of uniform on the GPU.
  25732. *
  25733. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  25734. *
  25735. * For more information, please refer to :
  25736. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  25737. */
  25738. function UniformBuffer(engine, data, dynamic) {
  25739. this._engine = engine;
  25740. this._noUBO = engine.webGLVersion === 1;
  25741. this._dynamic = dynamic;
  25742. this._data = data || [];
  25743. this._uniformLocations = {};
  25744. this._uniformSizes = {};
  25745. this._uniformLocationPointer = 0;
  25746. this._needSync = false;
  25747. if (this._noUBO) {
  25748. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  25749. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  25750. this.updateFloat = this._updateFloatForEffect;
  25751. this.updateFloat2 = this._updateFloat2ForEffect;
  25752. this.updateFloat3 = this._updateFloat3ForEffect;
  25753. this.updateFloat4 = this._updateFloat4ForEffect;
  25754. this.updateMatrix = this._updateMatrixForEffect;
  25755. this.updateVector3 = this._updateVector3ForEffect;
  25756. this.updateVector4 = this._updateVector4ForEffect;
  25757. this.updateColor3 = this._updateColor3ForEffect;
  25758. this.updateColor4 = this._updateColor4ForEffect;
  25759. }
  25760. else {
  25761. this._engine._uniformBuffers.push(this);
  25762. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  25763. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  25764. this.updateFloat = this._updateFloatForUniform;
  25765. this.updateFloat2 = this._updateFloat2ForUniform;
  25766. this.updateFloat3 = this._updateFloat3ForUniform;
  25767. this.updateFloat4 = this._updateFloat4ForUniform;
  25768. this.updateMatrix = this._updateMatrixForUniform;
  25769. this.updateVector3 = this._updateVector3ForUniform;
  25770. this.updateVector4 = this._updateVector4ForUniform;
  25771. this.updateColor3 = this._updateColor3ForUniform;
  25772. this.updateColor4 = this._updateColor4ForUniform;
  25773. }
  25774. }
  25775. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  25776. // Properties
  25777. /**
  25778. * Indicates if the buffer is using the WebGL2 UBO implementation,
  25779. * or just falling back on setUniformXXX calls.
  25780. */
  25781. get: function () {
  25782. return !this._noUBO;
  25783. },
  25784. enumerable: true,
  25785. configurable: true
  25786. });
  25787. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  25788. /**
  25789. * Indicates if the WebGL underlying uniform buffer is in sync
  25790. * with the javascript cache data.
  25791. */
  25792. get: function () {
  25793. return !this._needSync;
  25794. },
  25795. enumerable: true,
  25796. configurable: true
  25797. });
  25798. /**
  25799. * Indicates if the WebGL underlying uniform buffer is dynamic.
  25800. * Also, a dynamic UniformBuffer will disable cache verification and always
  25801. * update the underlying WebGL uniform buffer to the GPU.
  25802. */
  25803. UniformBuffer.prototype.isDynamic = function () {
  25804. return this._dynamic;
  25805. };
  25806. /**
  25807. * The data cache on JS side.
  25808. */
  25809. UniformBuffer.prototype.getData = function () {
  25810. return this._bufferData;
  25811. };
  25812. /**
  25813. * The underlying WebGL Uniform buffer.
  25814. */
  25815. UniformBuffer.prototype.getBuffer = function () {
  25816. return this._buffer;
  25817. };
  25818. /**
  25819. * std140 layout specifies how to align data within an UBO structure.
  25820. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  25821. * for specs.
  25822. */
  25823. UniformBuffer.prototype._fillAlignment = function (size) {
  25824. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  25825. // and 4x4 matrices
  25826. // TODO : change if other types are used
  25827. var alignment;
  25828. if (size <= 2) {
  25829. alignment = size;
  25830. }
  25831. else {
  25832. alignment = 4;
  25833. }
  25834. if ((this._uniformLocationPointer % alignment) !== 0) {
  25835. var oldPointer = this._uniformLocationPointer;
  25836. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  25837. var diff = this._uniformLocationPointer - oldPointer;
  25838. for (var i = 0; i < diff; i++) {
  25839. this._data.push(0);
  25840. }
  25841. }
  25842. };
  25843. /**
  25844. * Adds an uniform in the buffer.
  25845. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  25846. * for the layout to be correct !
  25847. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25848. * @param {number|number[]} size Data size, or data directly.
  25849. */
  25850. UniformBuffer.prototype.addUniform = function (name, size) {
  25851. if (this._noUBO) {
  25852. return;
  25853. }
  25854. if (this._uniformLocations[name] !== undefined) {
  25855. // Already existing uniform
  25856. return;
  25857. }
  25858. // This function must be called in the order of the shader layout !
  25859. // size can be the size of the uniform, or data directly
  25860. var data;
  25861. if (size instanceof Array) {
  25862. data = size;
  25863. size = data.length;
  25864. }
  25865. else {
  25866. size = size;
  25867. data = [];
  25868. // Fill with zeros
  25869. for (var i = 0; i < size; i++) {
  25870. data.push(0);
  25871. }
  25872. }
  25873. this._fillAlignment(size);
  25874. this._uniformSizes[name] = size;
  25875. this._uniformLocations[name] = this._uniformLocationPointer;
  25876. this._uniformLocationPointer += size;
  25877. for (var i = 0; i < size; i++) {
  25878. this._data.push(data[i]);
  25879. }
  25880. this._needSync = true;
  25881. };
  25882. /**
  25883. * Wrapper for addUniform.
  25884. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25885. * @param {Matrix} mat A 4x4 matrix.
  25886. */
  25887. UniformBuffer.prototype.addMatrix = function (name, mat) {
  25888. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  25889. };
  25890. /**
  25891. * Wrapper for addUniform.
  25892. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25893. * @param {number} x
  25894. * @param {number} y
  25895. */
  25896. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  25897. var temp = [x, y];
  25898. this.addUniform(name, temp);
  25899. };
  25900. /**
  25901. * Wrapper for addUniform.
  25902. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25903. * @param {number} x
  25904. * @param {number} y
  25905. * @param {number} z
  25906. */
  25907. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  25908. var temp = [x, y, z];
  25909. this.addUniform(name, temp);
  25910. };
  25911. /**
  25912. * Wrapper for addUniform.
  25913. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25914. * @param {Color3} color
  25915. */
  25916. UniformBuffer.prototype.addColor3 = function (name, color) {
  25917. var temp = [];
  25918. color.toArray(temp);
  25919. this.addUniform(name, temp);
  25920. };
  25921. /**
  25922. * Wrapper for addUniform.
  25923. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25924. * @param {Color3} color
  25925. * @param {number} alpha
  25926. */
  25927. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  25928. var temp = [];
  25929. color.toArray(temp);
  25930. temp.push(alpha);
  25931. this.addUniform(name, temp);
  25932. };
  25933. /**
  25934. * Wrapper for addUniform.
  25935. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25936. * @param {Vector3} vector
  25937. */
  25938. UniformBuffer.prototype.addVector3 = function (name, vector) {
  25939. var temp = [];
  25940. vector.toArray(temp);
  25941. this.addUniform(name, temp);
  25942. };
  25943. /**
  25944. * Wrapper for addUniform.
  25945. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25946. */
  25947. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  25948. this.addUniform(name, 12);
  25949. };
  25950. /**
  25951. * Wrapper for addUniform.
  25952. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25953. */
  25954. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  25955. this.addUniform(name, 8);
  25956. };
  25957. /**
  25958. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  25959. */
  25960. UniformBuffer.prototype.create = function () {
  25961. if (this._noUBO) {
  25962. return;
  25963. }
  25964. if (this._buffer) {
  25965. return; // nothing to do
  25966. }
  25967. // See spec, alignment must be filled as a vec4
  25968. this._fillAlignment(4);
  25969. this._bufferData = new Float32Array(this._data);
  25970. this._rebuild();
  25971. this._needSync = true;
  25972. };
  25973. UniformBuffer.prototype._rebuild = function () {
  25974. if (this._noUBO) {
  25975. return;
  25976. }
  25977. if (this._dynamic) {
  25978. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  25979. }
  25980. else {
  25981. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  25982. }
  25983. };
  25984. /**
  25985. * Updates the WebGL Uniform Buffer on the GPU.
  25986. * If the `dynamic` flag is set to true, no cache comparison is done.
  25987. * Otherwise, the buffer will be updated only if the cache differs.
  25988. */
  25989. UniformBuffer.prototype.update = function () {
  25990. if (!this._buffer) {
  25991. this.create();
  25992. return;
  25993. }
  25994. if (!this._dynamic && !this._needSync) {
  25995. return;
  25996. }
  25997. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  25998. this._needSync = false;
  25999. };
  26000. /**
  26001. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26002. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26003. * @param {number[]|Float32Array} data Flattened data
  26004. * @param {number} size Size of the data.
  26005. */
  26006. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26007. var location = this._uniformLocations[uniformName];
  26008. if (location === undefined) {
  26009. if (this._buffer) {
  26010. // Cannot add an uniform if the buffer is already created
  26011. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26012. return;
  26013. }
  26014. this.addUniform(uniformName, size);
  26015. location = this._uniformLocations[uniformName];
  26016. }
  26017. if (!this._buffer) {
  26018. this.create();
  26019. }
  26020. if (!this._dynamic) {
  26021. // Cache for static uniform buffers
  26022. var changed = false;
  26023. for (var i = 0; i < size; i++) {
  26024. if (this._bufferData[location + i] !== data[i]) {
  26025. changed = true;
  26026. this._bufferData[location + i] = data[i];
  26027. }
  26028. }
  26029. this._needSync = this._needSync || changed;
  26030. }
  26031. else {
  26032. // No cache for dynamic
  26033. for (var i = 0; i < size; i++) {
  26034. this._bufferData[location + i] = data[i];
  26035. }
  26036. }
  26037. };
  26038. // Update methods
  26039. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26040. // To match std140, matrix must be realigned
  26041. for (var i = 0; i < 3; i++) {
  26042. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26043. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26044. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26045. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26046. }
  26047. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26048. };
  26049. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26050. this._currentEffect.setMatrix3x3(name, matrix);
  26051. };
  26052. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26053. this._currentEffect.setMatrix2x2(name, matrix);
  26054. };
  26055. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26056. // To match std140, matrix must be realigned
  26057. for (var i = 0; i < 2; i++) {
  26058. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26059. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26060. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26061. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26062. }
  26063. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26064. };
  26065. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26066. this._currentEffect.setFloat(name, x);
  26067. };
  26068. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26069. UniformBuffer._tempBuffer[0] = x;
  26070. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26071. };
  26072. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26073. if (suffix === void 0) { suffix = ""; }
  26074. this._currentEffect.setFloat2(name + suffix, x, y);
  26075. };
  26076. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26077. if (suffix === void 0) { suffix = ""; }
  26078. UniformBuffer._tempBuffer[0] = x;
  26079. UniformBuffer._tempBuffer[1] = y;
  26080. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26081. };
  26082. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26083. if (suffix === void 0) { suffix = ""; }
  26084. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26085. };
  26086. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26087. if (suffix === void 0) { suffix = ""; }
  26088. UniformBuffer._tempBuffer[0] = x;
  26089. UniformBuffer._tempBuffer[1] = y;
  26090. UniformBuffer._tempBuffer[2] = z;
  26091. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26092. };
  26093. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26094. if (suffix === void 0) { suffix = ""; }
  26095. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26096. };
  26097. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26098. if (suffix === void 0) { suffix = ""; }
  26099. UniformBuffer._tempBuffer[0] = x;
  26100. UniformBuffer._tempBuffer[1] = y;
  26101. UniformBuffer._tempBuffer[2] = z;
  26102. UniformBuffer._tempBuffer[3] = w;
  26103. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26104. };
  26105. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26106. this._currentEffect.setMatrix(name, mat);
  26107. };
  26108. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26109. this.updateUniform(name, mat.toArray(), 16);
  26110. };
  26111. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26112. this._currentEffect.setVector3(name, vector);
  26113. };
  26114. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26115. vector.toArray(UniformBuffer._tempBuffer);
  26116. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26117. };
  26118. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26119. this._currentEffect.setVector4(name, vector);
  26120. };
  26121. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26122. vector.toArray(UniformBuffer._tempBuffer);
  26123. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26124. };
  26125. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26126. if (suffix === void 0) { suffix = ""; }
  26127. this._currentEffect.setColor3(name + suffix, color);
  26128. };
  26129. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26130. if (suffix === void 0) { suffix = ""; }
  26131. color.toArray(UniformBuffer._tempBuffer);
  26132. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26133. };
  26134. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26135. if (suffix === void 0) { suffix = ""; }
  26136. this._currentEffect.setColor4(name + suffix, color, alpha);
  26137. };
  26138. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26139. if (suffix === void 0) { suffix = ""; }
  26140. color.toArray(UniformBuffer._tempBuffer);
  26141. UniformBuffer._tempBuffer[3] = alpha;
  26142. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26143. };
  26144. /**
  26145. * Sets a sampler uniform on the effect.
  26146. * @param {string} name Name of the sampler.
  26147. * @param {Texture} texture
  26148. */
  26149. UniformBuffer.prototype.setTexture = function (name, texture) {
  26150. this._currentEffect.setTexture(name, texture);
  26151. };
  26152. /**
  26153. * Directly updates the value of the uniform in the cache AND on the GPU.
  26154. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26155. * @param {number[]|Float32Array} data Flattened data
  26156. */
  26157. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26158. this.updateUniform(uniformName, data, data.length);
  26159. this.update();
  26160. };
  26161. /**
  26162. * Binds this uniform buffer to an effect.
  26163. * @param {Effect} effect
  26164. * @param {string} name Name of the uniform block in the shader.
  26165. */
  26166. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26167. this._currentEffect = effect;
  26168. if (this._noUBO) {
  26169. return;
  26170. }
  26171. effect.bindUniformBuffer(this._buffer, name);
  26172. };
  26173. /**
  26174. * Disposes the uniform buffer.
  26175. */
  26176. UniformBuffer.prototype.dispose = function () {
  26177. if (this._noUBO) {
  26178. return;
  26179. }
  26180. var index = this._engine._uniformBuffers.indexOf(this);
  26181. if (index !== -1) {
  26182. this._engine._uniformBuffers.splice(index, 1);
  26183. }
  26184. if (!this._buffer) {
  26185. return;
  26186. }
  26187. if (this._engine._releaseBuffer(this._buffer)) {
  26188. this._buffer = null;
  26189. }
  26190. };
  26191. // Pool for avoiding memory leaks
  26192. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26193. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26194. return UniformBuffer;
  26195. }());
  26196. BABYLON.UniformBuffer = UniformBuffer;
  26197. })(BABYLON || (BABYLON = {}));
  26198. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26199. var BABYLON;
  26200. (function (BABYLON) {
  26201. var PushMaterial = (function (_super) {
  26202. __extends(PushMaterial, _super);
  26203. function PushMaterial(name, scene) {
  26204. var _this = _super.call(this, name, scene) || this;
  26205. _this.storeEffectOnSubMeshes = true;
  26206. return _this;
  26207. }
  26208. PushMaterial.prototype.getEffect = function () {
  26209. return this._activeEffect;
  26210. };
  26211. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26212. if (!mesh) {
  26213. return false;
  26214. }
  26215. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26216. return true;
  26217. }
  26218. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26219. };
  26220. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26221. this._activeEffect.setMatrix("world", world);
  26222. };
  26223. PushMaterial.prototype.bind = function (world, mesh) {
  26224. if (!mesh) {
  26225. return;
  26226. }
  26227. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26228. };
  26229. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26230. _super.prototype._afterBind.call(this, mesh);
  26231. this.getScene()._cachedEffect = effect;
  26232. };
  26233. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26234. if (visibility === void 0) { visibility = 1; }
  26235. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26236. };
  26237. return PushMaterial;
  26238. }(BABYLON.Material));
  26239. BABYLON.PushMaterial = PushMaterial;
  26240. })(BABYLON || (BABYLON = {}));
  26241. //# sourceMappingURL=babylon.pushMaterial.js.map
  26242. var BABYLON;
  26243. (function (BABYLON) {
  26244. var VertexData = (function () {
  26245. function VertexData() {
  26246. }
  26247. VertexData.prototype.set = function (data, kind) {
  26248. switch (kind) {
  26249. case BABYLON.VertexBuffer.PositionKind:
  26250. this.positions = data;
  26251. break;
  26252. case BABYLON.VertexBuffer.NormalKind:
  26253. this.normals = data;
  26254. break;
  26255. case BABYLON.VertexBuffer.TangentKind:
  26256. this.tangents = data;
  26257. break;
  26258. case BABYLON.VertexBuffer.UVKind:
  26259. this.uvs = data;
  26260. break;
  26261. case BABYLON.VertexBuffer.UV2Kind:
  26262. this.uvs2 = data;
  26263. break;
  26264. case BABYLON.VertexBuffer.UV3Kind:
  26265. this.uvs3 = data;
  26266. break;
  26267. case BABYLON.VertexBuffer.UV4Kind:
  26268. this.uvs4 = data;
  26269. break;
  26270. case BABYLON.VertexBuffer.UV5Kind:
  26271. this.uvs5 = data;
  26272. break;
  26273. case BABYLON.VertexBuffer.UV6Kind:
  26274. this.uvs6 = data;
  26275. break;
  26276. case BABYLON.VertexBuffer.ColorKind:
  26277. this.colors = data;
  26278. break;
  26279. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26280. this.matricesIndices = data;
  26281. break;
  26282. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26283. this.matricesWeights = data;
  26284. break;
  26285. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26286. this.matricesIndicesExtra = data;
  26287. break;
  26288. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26289. this.matricesWeightsExtra = data;
  26290. break;
  26291. }
  26292. };
  26293. /**
  26294. * Associates the vertexData to the passed Mesh.
  26295. * Sets it as updatable or not (default `false`).
  26296. * Returns the VertexData.
  26297. */
  26298. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26299. this._applyTo(mesh, updatable);
  26300. return this;
  26301. };
  26302. /**
  26303. * Associates the vertexData to the passed Geometry.
  26304. * Sets it as updatable or not (default `false`).
  26305. * Returns the VertexData.
  26306. */
  26307. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26308. this._applyTo(geometry, updatable);
  26309. return this;
  26310. };
  26311. /**
  26312. * Updates the associated mesh.
  26313. * Returns the VertexData.
  26314. */
  26315. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26316. this._update(mesh);
  26317. return this;
  26318. };
  26319. /**
  26320. * Updates the associated geometry.
  26321. * Returns the VertexData.
  26322. */
  26323. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26324. this._update(geometry);
  26325. return this;
  26326. };
  26327. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26328. if (this.positions) {
  26329. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26330. }
  26331. if (this.normals) {
  26332. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26333. }
  26334. if (this.tangents) {
  26335. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26336. }
  26337. if (this.uvs) {
  26338. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26339. }
  26340. if (this.uvs2) {
  26341. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26342. }
  26343. if (this.uvs3) {
  26344. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26345. }
  26346. if (this.uvs4) {
  26347. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26348. }
  26349. if (this.uvs5) {
  26350. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26351. }
  26352. if (this.uvs6) {
  26353. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26354. }
  26355. if (this.colors) {
  26356. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26357. }
  26358. if (this.matricesIndices) {
  26359. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26360. }
  26361. if (this.matricesWeights) {
  26362. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26363. }
  26364. if (this.matricesIndicesExtra) {
  26365. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26366. }
  26367. if (this.matricesWeightsExtra) {
  26368. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26369. }
  26370. if (this.indices) {
  26371. meshOrGeometry.setIndices(this.indices);
  26372. }
  26373. return this;
  26374. };
  26375. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26376. if (this.positions) {
  26377. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26378. }
  26379. if (this.normals) {
  26380. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26381. }
  26382. if (this.tangents) {
  26383. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26384. }
  26385. if (this.uvs) {
  26386. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26387. }
  26388. if (this.uvs2) {
  26389. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26390. }
  26391. if (this.uvs3) {
  26392. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26393. }
  26394. if (this.uvs4) {
  26395. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26396. }
  26397. if (this.uvs5) {
  26398. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26399. }
  26400. if (this.uvs6) {
  26401. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26402. }
  26403. if (this.colors) {
  26404. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26405. }
  26406. if (this.matricesIndices) {
  26407. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26408. }
  26409. if (this.matricesWeights) {
  26410. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26411. }
  26412. if (this.matricesIndicesExtra) {
  26413. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26414. }
  26415. if (this.matricesWeightsExtra) {
  26416. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26417. }
  26418. if (this.indices) {
  26419. meshOrGeometry.setIndices(this.indices);
  26420. }
  26421. return this;
  26422. };
  26423. /**
  26424. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26425. * Returns the VertexData.
  26426. */
  26427. VertexData.prototype.transform = function (matrix) {
  26428. var transformed = BABYLON.Vector3.Zero();
  26429. var index;
  26430. if (this.positions) {
  26431. var position = BABYLON.Vector3.Zero();
  26432. for (index = 0; index < this.positions.length; index += 3) {
  26433. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26434. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26435. this.positions[index] = transformed.x;
  26436. this.positions[index + 1] = transformed.y;
  26437. this.positions[index + 2] = transformed.z;
  26438. }
  26439. }
  26440. if (this.normals) {
  26441. var normal = BABYLON.Vector3.Zero();
  26442. for (index = 0; index < this.normals.length; index += 3) {
  26443. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26444. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26445. this.normals[index] = transformed.x;
  26446. this.normals[index + 1] = transformed.y;
  26447. this.normals[index + 2] = transformed.z;
  26448. }
  26449. }
  26450. if (this.tangents) {
  26451. var tangent = BABYLON.Vector4.Zero();
  26452. var tangentTransformed = BABYLON.Vector4.Zero();
  26453. for (index = 0; index < this.tangents.length; index += 4) {
  26454. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26455. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26456. this.tangents[index] = tangentTransformed.x;
  26457. this.tangents[index + 1] = tangentTransformed.y;
  26458. this.tangents[index + 2] = tangentTransformed.z;
  26459. this.tangents[index + 3] = tangentTransformed.w;
  26460. }
  26461. }
  26462. return this;
  26463. };
  26464. /**
  26465. * Merges the passed VertexData into the current one.
  26466. * Returns the modified VertexData.
  26467. */
  26468. VertexData.prototype.merge = function (other) {
  26469. if (other.indices) {
  26470. if (!this.indices) {
  26471. this.indices = [];
  26472. }
  26473. var offset = this.positions ? this.positions.length / 3 : 0;
  26474. for (var index = 0; index < other.indices.length; index++) {
  26475. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26476. this.indices.push(other.indices[index] + offset);
  26477. }
  26478. }
  26479. this.positions = this._mergeElement(this.positions, other.positions);
  26480. this.normals = this._mergeElement(this.normals, other.normals);
  26481. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26482. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26483. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26484. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26485. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26486. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26487. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26488. this.colors = this._mergeElement(this.colors, other.colors);
  26489. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26490. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26491. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26492. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26493. return this;
  26494. };
  26495. VertexData.prototype._mergeElement = function (source, other) {
  26496. if (!other)
  26497. return source;
  26498. if (!source)
  26499. return other;
  26500. var len = other.length + source.length;
  26501. var isSrcTypedArray = source instanceof Float32Array;
  26502. var isOthTypedArray = other instanceof Float32Array;
  26503. // use non-loop method when the source is Float32Array
  26504. if (isSrcTypedArray) {
  26505. var ret32 = new Float32Array(len);
  26506. ret32.set(source);
  26507. ret32.set(other, source.length);
  26508. return ret32;
  26509. // source is number[], when other is also use concat
  26510. }
  26511. else if (!isOthTypedArray) {
  26512. return source.concat(other);
  26513. // source is a number[], but other is a Float32Array, loop required
  26514. }
  26515. else {
  26516. var ret = source.slice(0); // copy source to a separate array
  26517. for (var i = 0, len = other.length; i < len; i++) {
  26518. ret.push(other[i]);
  26519. }
  26520. return ret;
  26521. }
  26522. };
  26523. /**
  26524. * Serializes the VertexData.
  26525. * Returns a serialized object.
  26526. */
  26527. VertexData.prototype.serialize = function () {
  26528. var serializationObject = this.serialize();
  26529. if (this.positions) {
  26530. serializationObject.positions = this.positions;
  26531. }
  26532. if (this.normals) {
  26533. serializationObject.normals = this.normals;
  26534. }
  26535. if (this.tangents) {
  26536. serializationObject.tangents = this.tangents;
  26537. }
  26538. if (this.uvs) {
  26539. serializationObject.uvs = this.uvs;
  26540. }
  26541. if (this.uvs2) {
  26542. serializationObject.uvs2 = this.uvs2;
  26543. }
  26544. if (this.uvs3) {
  26545. serializationObject.uvs3 = this.uvs3;
  26546. }
  26547. if (this.uvs4) {
  26548. serializationObject.uvs4 = this.uvs4;
  26549. }
  26550. if (this.uvs5) {
  26551. serializationObject.uvs5 = this.uvs5;
  26552. }
  26553. if (this.uvs6) {
  26554. serializationObject.uvs6 = this.uvs6;
  26555. }
  26556. if (this.colors) {
  26557. serializationObject.colors = this.colors;
  26558. }
  26559. if (this.matricesIndices) {
  26560. serializationObject.matricesIndices = this.matricesIndices;
  26561. serializationObject.matricesIndices._isExpanded = true;
  26562. }
  26563. if (this.matricesWeights) {
  26564. serializationObject.matricesWeights = this.matricesWeights;
  26565. }
  26566. if (this.matricesIndicesExtra) {
  26567. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26568. serializationObject.matricesIndicesExtra._isExpanded = true;
  26569. }
  26570. if (this.matricesWeightsExtra) {
  26571. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26572. }
  26573. serializationObject.indices = this.indices;
  26574. return serializationObject;
  26575. };
  26576. // Statics
  26577. /**
  26578. * Returns the object VertexData associated to the passed mesh.
  26579. */
  26580. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  26581. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  26582. };
  26583. /**
  26584. * Returns the object VertexData associated to the passed geometry.
  26585. */
  26586. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  26587. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  26588. };
  26589. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  26590. var result = new VertexData();
  26591. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26592. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  26593. }
  26594. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26595. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  26596. }
  26597. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26598. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  26599. }
  26600. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26601. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  26602. }
  26603. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26604. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  26605. }
  26606. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26607. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  26608. }
  26609. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26610. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  26611. }
  26612. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26613. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  26614. }
  26615. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26616. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  26617. }
  26618. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26619. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  26620. }
  26621. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26622. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  26623. }
  26624. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26625. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  26626. }
  26627. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26628. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  26629. }
  26630. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26631. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  26632. }
  26633. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26634. return result;
  26635. };
  26636. /**
  26637. * Creates the vertexData of the Ribbon.
  26638. */
  26639. VertexData.CreateRibbon = function (options) {
  26640. var pathArray = options.pathArray;
  26641. var closeArray = options.closeArray || false;
  26642. var closePath = options.closePath || false;
  26643. var invertUV = options.invertUV || false;
  26644. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26645. var offset = options.offset || defaultOffset;
  26646. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26647. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26648. var customUV = options.uvs;
  26649. var customColors = options.colors;
  26650. var positions = [];
  26651. var indices = [];
  26652. var normals = [];
  26653. var uvs = [];
  26654. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26655. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26656. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26657. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26658. var minlg; // minimal length among all paths from pathArray
  26659. var lg = []; // array of path lengths : nb of vertex per path
  26660. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26661. var p; // path iterator
  26662. var i; // point iterator
  26663. var j; // point iterator
  26664. // if single path in pathArray
  26665. if (pathArray.length < 2) {
  26666. var ar1 = [];
  26667. var ar2 = [];
  26668. for (i = 0; i < pathArray[0].length - offset; i++) {
  26669. ar1.push(pathArray[0][i]);
  26670. ar2.push(pathArray[0][i + offset]);
  26671. }
  26672. pathArray = [ar1, ar2];
  26673. }
  26674. // positions and horizontal distances (u)
  26675. var idc = 0;
  26676. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26677. var path;
  26678. var l;
  26679. minlg = pathArray[0].length;
  26680. var vectlg;
  26681. var dist;
  26682. for (p = 0; p < pathArray.length; p++) {
  26683. uTotalDistance[p] = 0;
  26684. us[p] = [0];
  26685. path = pathArray[p];
  26686. l = path.length;
  26687. minlg = (minlg < l) ? minlg : l;
  26688. j = 0;
  26689. while (j < l) {
  26690. positions.push(path[j].x, path[j].y, path[j].z);
  26691. if (j > 0) {
  26692. vectlg = path[j].subtract(path[j - 1]).length();
  26693. dist = vectlg + uTotalDistance[p];
  26694. us[p].push(dist);
  26695. uTotalDistance[p] = dist;
  26696. }
  26697. j++;
  26698. }
  26699. if (closePath) {
  26700. j--;
  26701. positions.push(path[0].x, path[0].y, path[0].z);
  26702. vectlg = path[j].subtract(path[0]).length();
  26703. dist = vectlg + uTotalDistance[p];
  26704. us[p].push(dist);
  26705. uTotalDistance[p] = dist;
  26706. }
  26707. lg[p] = l + closePathCorr;
  26708. idx[p] = idc;
  26709. idc += (l + closePathCorr);
  26710. }
  26711. // vertical distances (v)
  26712. var path1;
  26713. var path2;
  26714. var vertex1;
  26715. var vertex2;
  26716. for (i = 0; i < minlg + closePathCorr; i++) {
  26717. vTotalDistance[i] = 0;
  26718. vs[i] = [0];
  26719. for (p = 0; p < pathArray.length - 1; p++) {
  26720. path1 = pathArray[p];
  26721. path2 = pathArray[p + 1];
  26722. if (i === minlg) {
  26723. vertex1 = path1[0];
  26724. vertex2 = path2[0];
  26725. }
  26726. else {
  26727. vertex1 = path1[i];
  26728. vertex2 = path2[i];
  26729. }
  26730. vectlg = vertex2.subtract(vertex1).length();
  26731. dist = vectlg + vTotalDistance[i];
  26732. vs[i].push(dist);
  26733. vTotalDistance[i] = dist;
  26734. }
  26735. if (closeArray) {
  26736. path1 = pathArray[p];
  26737. path2 = pathArray[0];
  26738. if (i === minlg) {
  26739. vertex2 = path2[0];
  26740. }
  26741. vectlg = vertex2.subtract(vertex1).length();
  26742. dist = vectlg + vTotalDistance[i];
  26743. vTotalDistance[i] = dist;
  26744. }
  26745. }
  26746. // uvs
  26747. var u;
  26748. var v;
  26749. if (customUV) {
  26750. for (p = 0; p < customUV.length; p++) {
  26751. uvs.push(customUV[p].x, customUV[p].y);
  26752. }
  26753. }
  26754. else {
  26755. for (p = 0; p < pathArray.length; p++) {
  26756. for (i = 0; i < minlg + closePathCorr; i++) {
  26757. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  26758. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  26759. if (invertUV) {
  26760. uvs.push(v, u);
  26761. }
  26762. else {
  26763. uvs.push(u, v);
  26764. }
  26765. }
  26766. }
  26767. }
  26768. // indices
  26769. p = 0; // path index
  26770. var pi = 0; // positions array index
  26771. var l1 = lg[p] - 1; // path1 length
  26772. var l2 = lg[p + 1] - 1; // path2 length
  26773. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26774. var shft = idx[1] - idx[0]; // shift
  26775. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26776. while (pi <= min && p < path1nb) {
  26777. // 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
  26778. indices.push(pi, pi + shft, pi + 1);
  26779. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26780. pi += 1;
  26781. if (pi === min) {
  26782. p++;
  26783. if (p === lg.length - 1) {
  26784. shft = idx[0] - idx[p];
  26785. l1 = lg[p] - 1;
  26786. l2 = lg[0] - 1;
  26787. }
  26788. else {
  26789. shft = idx[p + 1] - idx[p];
  26790. l1 = lg[p] - 1;
  26791. l2 = lg[p + 1] - 1;
  26792. }
  26793. pi = idx[p];
  26794. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26795. }
  26796. }
  26797. // normals
  26798. VertexData.ComputeNormals(positions, indices, normals);
  26799. if (closePath) {
  26800. var indexFirst = 0;
  26801. var indexLast = 0;
  26802. for (p = 0; p < pathArray.length; p++) {
  26803. indexFirst = idx[p] * 3;
  26804. if (p + 1 < pathArray.length) {
  26805. indexLast = (idx[p + 1] - 1) * 3;
  26806. }
  26807. else {
  26808. indexLast = normals.length - 3;
  26809. }
  26810. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26811. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26812. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26813. normals[indexLast] = normals[indexFirst];
  26814. normals[indexLast + 1] = normals[indexFirst + 1];
  26815. normals[indexLast + 2] = normals[indexFirst + 2];
  26816. }
  26817. }
  26818. // sides
  26819. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26820. // Colors
  26821. if (customColors) {
  26822. var colors = new Float32Array(customColors.length * 4);
  26823. for (var c = 0; c < customColors.length; c++) {
  26824. colors[c * 4] = customColors[c].r;
  26825. colors[c * 4 + 1] = customColors[c].g;
  26826. colors[c * 4 + 2] = customColors[c].b;
  26827. colors[c * 4 + 3] = customColors[c].a;
  26828. }
  26829. }
  26830. // Result
  26831. var vertexData = new VertexData();
  26832. var positions32 = new Float32Array(positions);
  26833. var normals32 = new Float32Array(normals);
  26834. var uvs32 = new Float32Array(uvs);
  26835. vertexData.indices = indices;
  26836. vertexData.positions = positions32;
  26837. vertexData.normals = normals32;
  26838. vertexData.uvs = uvs32;
  26839. if (customColors) {
  26840. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  26841. }
  26842. if (closePath) {
  26843. vertexData._idx = idx;
  26844. }
  26845. return vertexData;
  26846. };
  26847. /**
  26848. * Creates the VertexData of the Box.
  26849. */
  26850. VertexData.CreateBox = function (options) {
  26851. var normalsSource = [
  26852. new BABYLON.Vector3(0, 0, 1),
  26853. new BABYLON.Vector3(0, 0, -1),
  26854. new BABYLON.Vector3(1, 0, 0),
  26855. new BABYLON.Vector3(-1, 0, 0),
  26856. new BABYLON.Vector3(0, 1, 0),
  26857. new BABYLON.Vector3(0, -1, 0)
  26858. ];
  26859. var indices = [];
  26860. var positions = [];
  26861. var normals = [];
  26862. var uvs = [];
  26863. var width = options.width || options.size || 1;
  26864. var height = options.height || options.size || 1;
  26865. var depth = options.depth || options.size || 1;
  26866. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26867. var faceUV = options.faceUV || new Array(6);
  26868. var faceColors = options.faceColors;
  26869. var colors = [];
  26870. // default face colors and UV if undefined
  26871. for (var f = 0; f < 6; f++) {
  26872. if (faceUV[f] === undefined) {
  26873. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26874. }
  26875. if (faceColors && faceColors[f] === undefined) {
  26876. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26877. }
  26878. }
  26879. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26880. // Create each face in turn.
  26881. for (var index = 0; index < normalsSource.length; index++) {
  26882. var normal = normalsSource[index];
  26883. // Get two vectors perpendicular to the face normal and to each other.
  26884. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26885. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26886. // Six indices (two triangles) per face.
  26887. var verticesLength = positions.length / 3;
  26888. indices.push(verticesLength);
  26889. indices.push(verticesLength + 1);
  26890. indices.push(verticesLength + 2);
  26891. indices.push(verticesLength);
  26892. indices.push(verticesLength + 2);
  26893. indices.push(verticesLength + 3);
  26894. // Four vertices per face.
  26895. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26896. positions.push(vertex.x, vertex.y, vertex.z);
  26897. normals.push(normal.x, normal.y, normal.z);
  26898. uvs.push(faceUV[index].z, faceUV[index].w);
  26899. if (faceColors) {
  26900. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26901. }
  26902. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26903. positions.push(vertex.x, vertex.y, vertex.z);
  26904. normals.push(normal.x, normal.y, normal.z);
  26905. uvs.push(faceUV[index].x, faceUV[index].w);
  26906. if (faceColors) {
  26907. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26908. }
  26909. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26910. positions.push(vertex.x, vertex.y, vertex.z);
  26911. normals.push(normal.x, normal.y, normal.z);
  26912. uvs.push(faceUV[index].x, faceUV[index].y);
  26913. if (faceColors) {
  26914. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26915. }
  26916. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26917. positions.push(vertex.x, vertex.y, vertex.z);
  26918. normals.push(normal.x, normal.y, normal.z);
  26919. uvs.push(faceUV[index].z, faceUV[index].y);
  26920. if (faceColors) {
  26921. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26922. }
  26923. }
  26924. // sides
  26925. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26926. // Result
  26927. var vertexData = new VertexData();
  26928. vertexData.indices = indices;
  26929. vertexData.positions = positions;
  26930. vertexData.normals = normals;
  26931. vertexData.uvs = uvs;
  26932. if (faceColors) {
  26933. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26934. vertexData.colors = totalColors;
  26935. }
  26936. return vertexData;
  26937. };
  26938. /**
  26939. * Creates the VertexData of the Sphere.
  26940. */
  26941. VertexData.CreateSphere = function (options) {
  26942. var segments = options.segments || 32;
  26943. var diameterX = options.diameterX || options.diameter || 1;
  26944. var diameterY = options.diameterY || options.diameter || 1;
  26945. var diameterZ = options.diameterZ || options.diameter || 1;
  26946. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26947. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26948. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26949. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26950. var totalZRotationSteps = 2 + segments;
  26951. var totalYRotationSteps = 2 * totalZRotationSteps;
  26952. var indices = [];
  26953. var positions = [];
  26954. var normals = [];
  26955. var uvs = [];
  26956. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26957. var normalizedZ = zRotationStep / totalZRotationSteps;
  26958. var angleZ = normalizedZ * Math.PI * slice;
  26959. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26960. var normalizedY = yRotationStep / totalYRotationSteps;
  26961. var angleY = normalizedY * Math.PI * 2 * arc;
  26962. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26963. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26964. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26965. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26966. var vertex = complete.multiply(radius);
  26967. var normal = complete.divide(radius).normalize();
  26968. positions.push(vertex.x, vertex.y, vertex.z);
  26969. normals.push(normal.x, normal.y, normal.z);
  26970. uvs.push(normalizedY, normalizedZ);
  26971. }
  26972. if (zRotationStep > 0) {
  26973. var verticesCount = positions.length / 3;
  26974. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26975. indices.push((firstIndex));
  26976. indices.push((firstIndex + 1));
  26977. indices.push(firstIndex + totalYRotationSteps + 1);
  26978. indices.push((firstIndex + totalYRotationSteps + 1));
  26979. indices.push((firstIndex + 1));
  26980. indices.push((firstIndex + totalYRotationSteps + 2));
  26981. }
  26982. }
  26983. }
  26984. // Sides
  26985. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26986. // Result
  26987. var vertexData = new VertexData();
  26988. vertexData.indices = indices;
  26989. vertexData.positions = positions;
  26990. vertexData.normals = normals;
  26991. vertexData.uvs = uvs;
  26992. return vertexData;
  26993. };
  26994. /**
  26995. * Creates the VertexData of the Cylinder or Cone.
  26996. */
  26997. VertexData.CreateCylinder = function (options) {
  26998. var height = options.height || 2;
  26999. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27000. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27001. var tessellation = options.tessellation || 24;
  27002. var subdivisions = options.subdivisions || 1;
  27003. var hasRings = options.hasRings;
  27004. var enclose = options.enclose;
  27005. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27006. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27007. var faceUV = options.faceUV || new Array(3);
  27008. var faceColors = options.faceColors;
  27009. // default face colors and UV if undefined
  27010. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27011. var ringNb = (hasRings) ? subdivisions : 1;
  27012. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27013. var f;
  27014. for (f = 0; f < surfaceNb; f++) {
  27015. if (faceColors && faceColors[f] === undefined) {
  27016. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27017. }
  27018. }
  27019. for (f = 0; f < surfaceNb; f++) {
  27020. if (faceUV && faceUV[f] === undefined) {
  27021. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27022. }
  27023. }
  27024. var indices = [];
  27025. var positions = [];
  27026. var normals = [];
  27027. var uvs = [];
  27028. var colors = [];
  27029. var angle_step = Math.PI * 2 * arc / tessellation;
  27030. var angle;
  27031. var h;
  27032. var radius;
  27033. var tan = (diameterBottom - diameterTop) / 2 / height;
  27034. var ringVertex = BABYLON.Vector3.Zero();
  27035. var ringNormal = BABYLON.Vector3.Zero();
  27036. var ringFirstVertex = BABYLON.Vector3.Zero();
  27037. var ringFirstNormal = BABYLON.Vector3.Zero();
  27038. var quadNormal = BABYLON.Vector3.Zero();
  27039. var Y = BABYLON.Axis.Y;
  27040. // positions, normals, uvs
  27041. var i;
  27042. var j;
  27043. var r;
  27044. var ringIdx = 1;
  27045. var s = 1; // surface index
  27046. var cs = 0;
  27047. var v = 0;
  27048. for (i = 0; i <= subdivisions; i++) {
  27049. h = i / subdivisions;
  27050. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27051. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27052. for (r = 0; r < ringIdx; r++) {
  27053. if (hasRings) {
  27054. s += r;
  27055. }
  27056. if (enclose) {
  27057. s += 2 * r;
  27058. }
  27059. for (j = 0; j <= tessellation; j++) {
  27060. angle = j * angle_step;
  27061. // position
  27062. ringVertex.x = Math.cos(-angle) * radius;
  27063. ringVertex.y = -height / 2 + h * height;
  27064. ringVertex.z = Math.sin(-angle) * radius;
  27065. // normal
  27066. if (diameterTop === 0 && i === subdivisions) {
  27067. // if no top cap, reuse former normals
  27068. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27069. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27070. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27071. }
  27072. else {
  27073. ringNormal.x = ringVertex.x;
  27074. ringNormal.z = ringVertex.z;
  27075. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27076. ringNormal.normalize();
  27077. }
  27078. // keep first ring vertex values for enclose
  27079. if (j === 0) {
  27080. ringFirstVertex.copyFrom(ringVertex);
  27081. ringFirstNormal.copyFrom(ringNormal);
  27082. }
  27083. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27084. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27085. if (hasRings) {
  27086. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27087. }
  27088. else {
  27089. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27090. }
  27091. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27092. if (faceColors) {
  27093. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27094. }
  27095. }
  27096. // if enclose, add four vertices and their dedicated normals
  27097. if (arc !== 1 && enclose) {
  27098. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27099. positions.push(0, ringVertex.y, 0);
  27100. positions.push(0, ringVertex.y, 0);
  27101. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27102. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27103. quadNormal.normalize();
  27104. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27105. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27106. quadNormal.normalize();
  27107. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27108. if (hasRings) {
  27109. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27110. }
  27111. else {
  27112. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27113. }
  27114. uvs.push(faceUV[s + 1].x, v);
  27115. uvs.push(faceUV[s + 1].z, v);
  27116. if (hasRings) {
  27117. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27118. }
  27119. else {
  27120. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27121. }
  27122. uvs.push(faceUV[s + 2].x, v);
  27123. uvs.push(faceUV[s + 2].z, v);
  27124. if (faceColors) {
  27125. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27126. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27127. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27128. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27129. }
  27130. }
  27131. if (cs !== s) {
  27132. cs = s;
  27133. }
  27134. }
  27135. }
  27136. // indices
  27137. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27138. var s;
  27139. i = 0;
  27140. for (s = 0; s < subdivisions; s++) {
  27141. for (j = 0; j < tessellation; j++) {
  27142. var i0 = i * (e + 1) + j;
  27143. var i1 = (i + 1) * (e + 1) + j;
  27144. var i2 = i * (e + 1) + (j + 1);
  27145. var i3 = (i + 1) * (e + 1) + (j + 1);
  27146. indices.push(i0, i1, i2);
  27147. indices.push(i3, i2, i1);
  27148. }
  27149. if (arc !== 1 && enclose) {
  27150. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27151. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27152. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27153. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27154. }
  27155. i = (hasRings) ? (i + 2) : (i + 1);
  27156. }
  27157. // Caps
  27158. var createCylinderCap = function (isTop) {
  27159. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27160. if (radius === 0) {
  27161. return;
  27162. }
  27163. // Cap positions, normals & uvs
  27164. var angle;
  27165. var circleVector;
  27166. var i;
  27167. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27168. var c;
  27169. if (faceColors) {
  27170. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27171. }
  27172. // cap center
  27173. var vbase = positions.length / 3;
  27174. var offset = isTop ? height / 2 : -height / 2;
  27175. var center = new BABYLON.Vector3(0, offset, 0);
  27176. positions.push(center.x, center.y, center.z);
  27177. normals.push(0, isTop ? 1 : -1, 0);
  27178. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27179. if (faceColors) {
  27180. colors.push(c.r, c.g, c.b, c.a);
  27181. }
  27182. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27183. for (i = 0; i <= tessellation; i++) {
  27184. angle = Math.PI * 2 * i * arc / tessellation;
  27185. var cos = Math.cos(-angle);
  27186. var sin = Math.sin(-angle);
  27187. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27188. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27189. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27190. normals.push(0, isTop ? 1 : -1, 0);
  27191. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27192. if (faceColors) {
  27193. colors.push(c.r, c.g, c.b, c.a);
  27194. }
  27195. }
  27196. // Cap indices
  27197. for (i = 0; i < tessellation; i++) {
  27198. if (!isTop) {
  27199. indices.push(vbase);
  27200. indices.push(vbase + (i + 1));
  27201. indices.push(vbase + (i + 2));
  27202. }
  27203. else {
  27204. indices.push(vbase);
  27205. indices.push(vbase + (i + 2));
  27206. indices.push(vbase + (i + 1));
  27207. }
  27208. }
  27209. };
  27210. // add caps to geometry
  27211. createCylinderCap(false);
  27212. createCylinderCap(true);
  27213. // Sides
  27214. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27215. var vertexData = new VertexData();
  27216. vertexData.indices = indices;
  27217. vertexData.positions = positions;
  27218. vertexData.normals = normals;
  27219. vertexData.uvs = uvs;
  27220. if (faceColors) {
  27221. vertexData.colors = colors;
  27222. }
  27223. return vertexData;
  27224. };
  27225. /**
  27226. * Creates the VertexData of the Torus.
  27227. */
  27228. VertexData.CreateTorus = function (options) {
  27229. var indices = [];
  27230. var positions = [];
  27231. var normals = [];
  27232. var uvs = [];
  27233. var diameter = options.diameter || 1;
  27234. var thickness = options.thickness || 0.5;
  27235. var tessellation = options.tessellation || 16;
  27236. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27237. var stride = tessellation + 1;
  27238. for (var i = 0; i <= tessellation; i++) {
  27239. var u = i / tessellation;
  27240. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27241. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27242. for (var j = 0; j <= tessellation; j++) {
  27243. var v = 1 - j / tessellation;
  27244. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27245. var dx = Math.cos(innerAngle);
  27246. var dy = Math.sin(innerAngle);
  27247. // Create a vertex.
  27248. var normal = new BABYLON.Vector3(dx, dy, 0);
  27249. var position = normal.scale(thickness / 2);
  27250. var textureCoordinate = new BABYLON.Vector2(u, v);
  27251. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27252. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27253. positions.push(position.x, position.y, position.z);
  27254. normals.push(normal.x, normal.y, normal.z);
  27255. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27256. // And create indices for two triangles.
  27257. var nextI = (i + 1) % stride;
  27258. var nextJ = (j + 1) % stride;
  27259. indices.push(i * stride + j);
  27260. indices.push(i * stride + nextJ);
  27261. indices.push(nextI * stride + j);
  27262. indices.push(i * stride + nextJ);
  27263. indices.push(nextI * stride + nextJ);
  27264. indices.push(nextI * stride + j);
  27265. }
  27266. }
  27267. // Sides
  27268. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27269. // Result
  27270. var vertexData = new VertexData();
  27271. vertexData.indices = indices;
  27272. vertexData.positions = positions;
  27273. vertexData.normals = normals;
  27274. vertexData.uvs = uvs;
  27275. return vertexData;
  27276. };
  27277. /**
  27278. * Creates the VertexData of the LineSystem.
  27279. */
  27280. VertexData.CreateLineSystem = function (options) {
  27281. var indices = [];
  27282. var positions = [];
  27283. var lines = options.lines;
  27284. var idx = 0;
  27285. for (var l = 0; l < lines.length; l++) {
  27286. var points = lines[l];
  27287. for (var index = 0; index < points.length; index++) {
  27288. positions.push(points[index].x, points[index].y, points[index].z);
  27289. if (index > 0) {
  27290. indices.push(idx - 1);
  27291. indices.push(idx);
  27292. }
  27293. idx++;
  27294. }
  27295. }
  27296. var vertexData = new VertexData();
  27297. vertexData.indices = indices;
  27298. vertexData.positions = positions;
  27299. return vertexData;
  27300. };
  27301. /**
  27302. * Create the VertexData of the DashedLines.
  27303. */
  27304. VertexData.CreateDashedLines = function (options) {
  27305. var dashSize = options.dashSize || 3;
  27306. var gapSize = options.gapSize || 1;
  27307. var dashNb = options.dashNb || 200;
  27308. var points = options.points;
  27309. var positions = new Array();
  27310. var indices = new Array();
  27311. var curvect = BABYLON.Vector3.Zero();
  27312. var lg = 0;
  27313. var nb = 0;
  27314. var shft = 0;
  27315. var dashshft = 0;
  27316. var curshft = 0;
  27317. var idx = 0;
  27318. var i = 0;
  27319. for (i = 0; i < points.length - 1; i++) {
  27320. points[i + 1].subtractToRef(points[i], curvect);
  27321. lg += curvect.length();
  27322. }
  27323. shft = lg / dashNb;
  27324. dashshft = dashSize * shft / (dashSize + gapSize);
  27325. for (i = 0; i < points.length - 1; i++) {
  27326. points[i + 1].subtractToRef(points[i], curvect);
  27327. nb = Math.floor(curvect.length() / shft);
  27328. curvect.normalize();
  27329. for (var j = 0; j < nb; j++) {
  27330. curshft = shft * j;
  27331. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27332. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27333. indices.push(idx, idx + 1);
  27334. idx += 2;
  27335. }
  27336. }
  27337. // Result
  27338. var vertexData = new VertexData();
  27339. vertexData.positions = positions;
  27340. vertexData.indices = indices;
  27341. return vertexData;
  27342. };
  27343. /**
  27344. * Creates the VertexData of the Ground.
  27345. */
  27346. VertexData.CreateGround = function (options) {
  27347. var indices = [];
  27348. var positions = [];
  27349. var normals = [];
  27350. var uvs = [];
  27351. var row, col;
  27352. var width = options.width || 1;
  27353. var height = options.height || 1;
  27354. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27355. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27356. for (row = 0; row <= subdivisionsY; row++) {
  27357. for (col = 0; col <= subdivisionsX; col++) {
  27358. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27359. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27360. positions.push(position.x, position.y, position.z);
  27361. normals.push(normal.x, normal.y, normal.z);
  27362. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27363. }
  27364. }
  27365. for (row = 0; row < subdivisionsY; row++) {
  27366. for (col = 0; col < subdivisionsX; col++) {
  27367. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27368. indices.push(col + 1 + row * (subdivisionsX + 1));
  27369. indices.push(col + row * (subdivisionsX + 1));
  27370. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27371. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27372. indices.push(col + row * (subdivisionsX + 1));
  27373. }
  27374. }
  27375. // Result
  27376. var vertexData = new VertexData();
  27377. vertexData.indices = indices;
  27378. vertexData.positions = positions;
  27379. vertexData.normals = normals;
  27380. vertexData.uvs = uvs;
  27381. return vertexData;
  27382. };
  27383. /**
  27384. * Creates the VertexData of the TiledGround.
  27385. */
  27386. VertexData.CreateTiledGround = function (options) {
  27387. var xmin = options.xmin || -1.0;
  27388. var zmin = options.zmin || -1.0;
  27389. var xmax = options.xmax || 1.0;
  27390. var zmax = options.zmax || 1.0;
  27391. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27392. var precision = options.precision || { w: 1, h: 1 };
  27393. var indices = [];
  27394. var positions = [];
  27395. var normals = [];
  27396. var uvs = [];
  27397. var row, col, tileRow, tileCol;
  27398. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27399. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27400. precision.w = (precision.w < 1) ? 1 : precision.w;
  27401. precision.h = (precision.h < 1) ? 1 : precision.h;
  27402. var tileSize = {
  27403. 'w': (xmax - xmin) / subdivisions.w,
  27404. 'h': (zmax - zmin) / subdivisions.h
  27405. };
  27406. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27407. // Indices
  27408. var base = positions.length / 3;
  27409. var rowLength = precision.w + 1;
  27410. for (row = 0; row < precision.h; row++) {
  27411. for (col = 0; col < precision.w; col++) {
  27412. var square = [
  27413. base + col + row * rowLength,
  27414. base + (col + 1) + row * rowLength,
  27415. base + (col + 1) + (row + 1) * rowLength,
  27416. base + col + (row + 1) * rowLength
  27417. ];
  27418. indices.push(square[1]);
  27419. indices.push(square[2]);
  27420. indices.push(square[3]);
  27421. indices.push(square[0]);
  27422. indices.push(square[1]);
  27423. indices.push(square[3]);
  27424. }
  27425. }
  27426. // Position, normals and uvs
  27427. var position = BABYLON.Vector3.Zero();
  27428. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27429. for (row = 0; row <= precision.h; row++) {
  27430. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27431. for (col = 0; col <= precision.w; col++) {
  27432. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27433. position.y = 0;
  27434. positions.push(position.x, position.y, position.z);
  27435. normals.push(normal.x, normal.y, normal.z);
  27436. uvs.push(col / precision.w, row / precision.h);
  27437. }
  27438. }
  27439. }
  27440. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27441. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27442. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27443. }
  27444. }
  27445. // Result
  27446. var vertexData = new VertexData();
  27447. vertexData.indices = indices;
  27448. vertexData.positions = positions;
  27449. vertexData.normals = normals;
  27450. vertexData.uvs = uvs;
  27451. return vertexData;
  27452. };
  27453. /**
  27454. * Creates the VertexData of the Ground designed from a heightmap.
  27455. */
  27456. VertexData.CreateGroundFromHeightMap = function (options) {
  27457. var indices = [];
  27458. var positions = [];
  27459. var normals = [];
  27460. var uvs = [];
  27461. var row, col;
  27462. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27463. // Vertices
  27464. for (row = 0; row <= options.subdivisions; row++) {
  27465. for (col = 0; col <= options.subdivisions; col++) {
  27466. 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));
  27467. // Compute height
  27468. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27469. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27470. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27471. var r = options.buffer[pos] / 255.0;
  27472. var g = options.buffer[pos + 1] / 255.0;
  27473. var b = options.buffer[pos + 2] / 255.0;
  27474. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27475. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27476. // Add vertex
  27477. positions.push(position.x, position.y, position.z);
  27478. normals.push(0, 0, 0);
  27479. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27480. }
  27481. }
  27482. // Indices
  27483. for (row = 0; row < options.subdivisions; row++) {
  27484. for (col = 0; col < options.subdivisions; col++) {
  27485. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27486. indices.push(col + 1 + row * (options.subdivisions + 1));
  27487. indices.push(col + row * (options.subdivisions + 1));
  27488. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27489. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27490. indices.push(col + row * (options.subdivisions + 1));
  27491. }
  27492. }
  27493. // Normals
  27494. VertexData.ComputeNormals(positions, indices, normals);
  27495. // Result
  27496. var vertexData = new VertexData();
  27497. vertexData.indices = indices;
  27498. vertexData.positions = positions;
  27499. vertexData.normals = normals;
  27500. vertexData.uvs = uvs;
  27501. return vertexData;
  27502. };
  27503. /**
  27504. * Creates the VertexData of the Plane.
  27505. */
  27506. VertexData.CreatePlane = function (options) {
  27507. var indices = [];
  27508. var positions = [];
  27509. var normals = [];
  27510. var uvs = [];
  27511. var width = options.width || options.size || 1;
  27512. var height = options.height || options.size || 1;
  27513. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27514. // Vertices
  27515. var halfWidth = width / 2.0;
  27516. var halfHeight = height / 2.0;
  27517. positions.push(-halfWidth, -halfHeight, 0);
  27518. normals.push(0, 0, -1.0);
  27519. uvs.push(0.0, 0.0);
  27520. positions.push(halfWidth, -halfHeight, 0);
  27521. normals.push(0, 0, -1.0);
  27522. uvs.push(1.0, 0.0);
  27523. positions.push(halfWidth, halfHeight, 0);
  27524. normals.push(0, 0, -1.0);
  27525. uvs.push(1.0, 1.0);
  27526. positions.push(-halfWidth, halfHeight, 0);
  27527. normals.push(0, 0, -1.0);
  27528. uvs.push(0.0, 1.0);
  27529. // Indices
  27530. indices.push(0);
  27531. indices.push(1);
  27532. indices.push(2);
  27533. indices.push(0);
  27534. indices.push(2);
  27535. indices.push(3);
  27536. // Sides
  27537. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27538. // Result
  27539. var vertexData = new VertexData();
  27540. vertexData.indices = indices;
  27541. vertexData.positions = positions;
  27542. vertexData.normals = normals;
  27543. vertexData.uvs = uvs;
  27544. return vertexData;
  27545. };
  27546. /**
  27547. * Creates the VertexData of the Disc or regular Polygon.
  27548. */
  27549. VertexData.CreateDisc = function (options) {
  27550. var positions = [];
  27551. var indices = [];
  27552. var normals = [];
  27553. var uvs = [];
  27554. var radius = options.radius || 0.5;
  27555. var tessellation = options.tessellation || 64;
  27556. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27557. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27558. // positions and uvs
  27559. positions.push(0, 0, 0); // disc center first
  27560. uvs.push(0.5, 0.5);
  27561. var theta = Math.PI * 2 * arc;
  27562. var step = theta / tessellation;
  27563. for (var a = 0; a < theta; a += step) {
  27564. var x = Math.cos(a);
  27565. var y = Math.sin(a);
  27566. var u = (x + 1) / 2;
  27567. var v = (1 - y) / 2;
  27568. positions.push(radius * x, radius * y, 0);
  27569. uvs.push(u, v);
  27570. }
  27571. if (arc === 1) {
  27572. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27573. uvs.push(uvs[2], uvs[3]);
  27574. }
  27575. //indices
  27576. var vertexNb = positions.length / 3;
  27577. for (var i = 1; i < vertexNb - 1; i++) {
  27578. indices.push(i + 1, 0, i);
  27579. }
  27580. // result
  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.indices = indices;
  27585. vertexData.positions = positions;
  27586. vertexData.normals = normals;
  27587. vertexData.uvs = uvs;
  27588. return vertexData;
  27589. };
  27590. /**
  27591. * Re-creates the VertexData of the Polygon for sideOrientation.
  27592. */
  27593. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  27594. var faceUV = fUV || new Array(3);
  27595. var faceColors = fColors;
  27596. var colors = [];
  27597. // default face colors and UV if undefined
  27598. for (var f = 0; f < 3; f++) {
  27599. if (faceUV[f] === undefined) {
  27600. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27601. }
  27602. if (faceColors && faceColors[f] === undefined) {
  27603. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27604. }
  27605. }
  27606. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27607. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27608. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27609. var indices = polygon.getIndices();
  27610. // set face colours and textures
  27611. var idx = 0;
  27612. var face = 0;
  27613. for (var index = 0; index < normals.length; index += 3) {
  27614. //Edge Face no. 1
  27615. if (Math.abs(normals[index + 1]) < 0.001) {
  27616. face = 1;
  27617. }
  27618. //Top Face no. 0
  27619. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  27620. face = 0;
  27621. }
  27622. //Bottom Face no. 2
  27623. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  27624. face = 2;
  27625. }
  27626. idx = index / 3;
  27627. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  27628. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  27629. if (faceColors) {
  27630. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  27631. }
  27632. }
  27633. // sides
  27634. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  27635. // Result
  27636. var vertexData = new VertexData();
  27637. vertexData.indices = indices;
  27638. vertexData.positions = positions;
  27639. vertexData.normals = normals;
  27640. vertexData.uvs = uvs;
  27641. if (faceColors) {
  27642. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27643. vertexData.colors = totalColors;
  27644. }
  27645. return vertexData;
  27646. };
  27647. /**
  27648. * Creates the VertexData of the IcoSphere.
  27649. */
  27650. VertexData.CreateIcoSphere = function (options) {
  27651. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27652. var radius = options.radius || 1;
  27653. var flat = (options.flat === undefined) ? true : options.flat;
  27654. var subdivisions = options.subdivisions || 4;
  27655. var radiusX = options.radiusX || radius;
  27656. var radiusY = options.radiusY || radius;
  27657. var radiusZ = options.radiusZ || radius;
  27658. var t = (1 + Math.sqrt(5)) / 2;
  27659. // 12 vertex x,y,z
  27660. var ico_vertices = [
  27661. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27662. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27663. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27664. ];
  27665. // index of 3 vertex makes a face of icopshere
  27666. var ico_indices = [
  27667. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27668. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27669. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27670. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27671. ];
  27672. // vertex for uv have aliased position, not for UV
  27673. var vertices_unalias_id = [
  27674. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27675. // vertex alias
  27676. 0,
  27677. 2,
  27678. 3,
  27679. 3,
  27680. 3,
  27681. 4,
  27682. 7,
  27683. 8,
  27684. 9,
  27685. 9,
  27686. 10,
  27687. 11 // 23: B + 12
  27688. ];
  27689. // uv as integer step (not pixels !)
  27690. var ico_vertexuv = [
  27691. 5, 1, 3, 1, 6, 4, 0, 0,
  27692. 5, 3, 4, 2, 2, 2, 4, 0,
  27693. 2, 0, 1, 1, 6, 0, 6, 2,
  27694. // vertex alias (for same vertex on different faces)
  27695. 0, 4,
  27696. 3, 3,
  27697. 4, 4,
  27698. 3, 1,
  27699. 4, 2,
  27700. 4, 4,
  27701. 0, 2,
  27702. 1, 1,
  27703. 2, 2,
  27704. 3, 3,
  27705. 1, 3,
  27706. 2, 4 // 23: B + 12
  27707. ];
  27708. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27709. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27710. // First island of uv mapping
  27711. // v = 4h 3+ 2
  27712. // v = 3h 9+ 4
  27713. // v = 2h 9+ 5 B
  27714. // v = 1h 9 1 0
  27715. // v = 0h 3 8 7 A
  27716. // u = 0 1 2 3 4 5 6 *a
  27717. // Second island of uv mapping
  27718. // v = 4h 0+ B+ 4+
  27719. // v = 3h A+ 2+
  27720. // v = 2h 7+ 6 3+
  27721. // v = 1h 8+ 3+
  27722. // v = 0h
  27723. // u = 0 1 2 3 4 5 6 *a
  27724. // Face layout on texture UV mapping
  27725. // ============
  27726. // \ 4 /\ 16 / ======
  27727. // \ / \ / /\ 11 /
  27728. // \/ 7 \/ / \ /
  27729. // ======= / 10 \/
  27730. // /\ 17 /\ =======
  27731. // / \ / \ \ 15 /\
  27732. // / 8 \/ 12 \ \ / \
  27733. // ============ \/ 6 \
  27734. // \ 18 /\ ============
  27735. // \ / \ \ 5 /\ 0 /
  27736. // \/ 13 \ \ / \ /
  27737. // ======= \/ 1 \/
  27738. // =============
  27739. // /\ 19 /\ 2 /\
  27740. // / \ / \ / \
  27741. // / 14 \/ 9 \/ 3 \
  27742. // ===================
  27743. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27744. var ustep = 138 / 1024;
  27745. var vstep = 239 / 1024;
  27746. var uoffset = 60 / 1024;
  27747. var voffset = 26 / 1024;
  27748. // Second island should have margin, not to touch the first island
  27749. // avoid any borderline artefact in pixel rounding
  27750. var island_u_offset = -40 / 1024;
  27751. var island_v_offset = +20 / 1024;
  27752. // face is either island 0 or 1 :
  27753. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27754. var island = [
  27755. 0, 0, 0, 0, 1,
  27756. 0, 0, 1, 1, 0,
  27757. 0, 0, 1, 1, 0,
  27758. 0, 1, 1, 1, 0 // 15 - 19
  27759. ];
  27760. var indices = [];
  27761. var positions = [];
  27762. var normals = [];
  27763. var uvs = [];
  27764. var current_indice = 0;
  27765. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27766. var face_vertex_pos = new Array(3);
  27767. var face_vertex_uv = new Array(3);
  27768. var v012;
  27769. for (v012 = 0; v012 < 3; v012++) {
  27770. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27771. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27772. }
  27773. // create all with normals
  27774. for (var face = 0; face < 20; face++) {
  27775. // 3 vertex per face
  27776. for (v012 = 0; v012 < 3; v012++) {
  27777. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27778. var v_id = ico_indices[3 * face + v012];
  27779. // vertex have 3D position (x,y,z)
  27780. 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]);
  27781. // Normalize to get normal, then scale to radius
  27782. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27783. // uv Coordinates from vertex ID
  27784. 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);
  27785. }
  27786. // Subdivide the face (interpolate pos, norm, uv)
  27787. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27788. // - norm is linear interpolation of vertex corner normal
  27789. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27790. // - uv is linear interpolation
  27791. //
  27792. // Topology is as below for sub-divide by 2
  27793. // vertex shown as v0,v1,v2
  27794. // interp index is i1 to progress in range [v0,v1[
  27795. // interp index is i2 to progress in range [v0,v2[
  27796. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27797. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27798. //
  27799. //
  27800. // i2 v2
  27801. // ^ ^
  27802. // / / \
  27803. // / / \
  27804. // / / \
  27805. // / / (0,1) \
  27806. // / #---------\
  27807. // / / \ (0,0)'/ \
  27808. // / / \ / \
  27809. // / / \ / \
  27810. // / / (0,0) \ / (1,0) \
  27811. // / #---------#---------\
  27812. // v0 v1
  27813. //
  27814. // --------------------> i1
  27815. //
  27816. // interp of (i1,i2):
  27817. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27818. // along i1 : lerp(x0,x1, i1/(S-i2))
  27819. //
  27820. // centroid of triangle is needed to get help normal computation
  27821. // (c1,c2) are used for centroid location
  27822. var interp_vertex = function (i1, i2, c1, c2) {
  27823. // vertex is interpolated from
  27824. // - face_vertex_pos[0..2]
  27825. // - face_vertex_uv[0..2]
  27826. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  27827. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  27828. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  27829. pos_interp.normalize();
  27830. var vertex_normal;
  27831. if (flat) {
  27832. // in flat mode, recalculate normal as face centroid normal
  27833. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  27834. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  27835. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  27836. }
  27837. else {
  27838. // in smooth mode, recalculate normal from each single vertex position
  27839. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  27840. }
  27841. // Vertex normal need correction due to X,Y,Z radius scaling
  27842. vertex_normal.x /= radiusX;
  27843. vertex_normal.y /= radiusY;
  27844. vertex_normal.z /= radiusZ;
  27845. vertex_normal.normalize();
  27846. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  27847. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  27848. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  27849. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  27850. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  27851. uvs.push(uv_interp.x, uv_interp.y);
  27852. // push each vertex has member of a face
  27853. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  27854. indices.push(current_indice);
  27855. current_indice++;
  27856. };
  27857. for (var i2 = 0; i2 < subdivisions; i2++) {
  27858. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  27859. // face : (i1,i2) for /\ :
  27860. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  27861. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27862. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27863. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27864. if (i1 + i2 + 1 < subdivisions) {
  27865. // face : (i1,i2)' for \/ :
  27866. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27867. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27868. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27869. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27870. }
  27871. }
  27872. }
  27873. }
  27874. // Sides
  27875. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27876. // Result
  27877. var vertexData = new VertexData();
  27878. vertexData.indices = indices;
  27879. vertexData.positions = positions;
  27880. vertexData.normals = normals;
  27881. vertexData.uvs = uvs;
  27882. return vertexData;
  27883. };
  27884. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  27885. /**
  27886. * Creates the VertexData of the Polyhedron.
  27887. */
  27888. VertexData.CreatePolyhedron = function (options) {
  27889. // provided polyhedron types :
  27890. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  27891. // 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)
  27892. var polyhedra = [];
  27893. 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]] };
  27894. 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]] };
  27895. polyhedra[2] = {
  27896. 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]],
  27897. 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]]
  27898. };
  27899. polyhedra[3] = {
  27900. 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]],
  27901. 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]]
  27902. };
  27903. polyhedra[4] = {
  27904. 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]],
  27905. 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]]
  27906. };
  27907. 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]] };
  27908. 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]] };
  27909. 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]] };
  27910. 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]] };
  27911. 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]] };
  27912. 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]] };
  27913. 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]] };
  27914. 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]] };
  27915. 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]] };
  27916. polyhedra[14] = {
  27917. 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]],
  27918. 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]]
  27919. };
  27920. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  27921. var size = options.size;
  27922. var sizeX = options.sizeX || size || 1;
  27923. var sizeY = options.sizeY || size || 1;
  27924. var sizeZ = options.sizeZ || size || 1;
  27925. var data = options.custom || polyhedra[type];
  27926. var nbfaces = data.face.length;
  27927. var faceUV = options.faceUV || new Array(nbfaces);
  27928. var faceColors = options.faceColors;
  27929. var flat = (options.flat === undefined) ? true : options.flat;
  27930. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27931. var positions = [];
  27932. var indices = [];
  27933. var normals = [];
  27934. var uvs = [];
  27935. var colors = [];
  27936. var index = 0;
  27937. var faceIdx = 0; // face cursor in the array "indexes"
  27938. var indexes = [];
  27939. var i = 0;
  27940. var f = 0;
  27941. var u, v, ang, x, y, tmp;
  27942. // default face colors and UV if undefined
  27943. if (flat) {
  27944. for (f = 0; f < nbfaces; f++) {
  27945. if (faceColors && faceColors[f] === undefined) {
  27946. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27947. }
  27948. if (faceUV && faceUV[f] === undefined) {
  27949. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27950. }
  27951. }
  27952. }
  27953. if (!flat) {
  27954. for (i = 0; i < data.vertex.length; i++) {
  27955. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  27956. uvs.push(0, 0);
  27957. }
  27958. for (f = 0; f < nbfaces; f++) {
  27959. for (i = 0; i < data.face[f].length - 2; i++) {
  27960. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  27961. }
  27962. }
  27963. }
  27964. else {
  27965. for (f = 0; f < nbfaces; f++) {
  27966. var fl = data.face[f].length; // number of vertices of the current face
  27967. ang = 2 * Math.PI / fl;
  27968. x = 0.5 * Math.tan(ang / 2);
  27969. y = 0.5;
  27970. // positions, uvs, colors
  27971. for (i = 0; i < fl; i++) {
  27972. // positions
  27973. 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);
  27974. indexes.push(index);
  27975. index++;
  27976. // uvs
  27977. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  27978. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  27979. uvs.push(u, v);
  27980. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  27981. y = x * Math.sin(ang) + y * Math.cos(ang);
  27982. x = tmp;
  27983. // colors
  27984. if (faceColors) {
  27985. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  27986. }
  27987. }
  27988. // indices from indexes
  27989. for (i = 0; i < fl - 2; i++) {
  27990. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  27991. }
  27992. faceIdx += fl;
  27993. }
  27994. }
  27995. VertexData.ComputeNormals(positions, indices, normals);
  27996. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27997. var vertexData = new VertexData();
  27998. vertexData.positions = positions;
  27999. vertexData.indices = indices;
  28000. vertexData.normals = normals;
  28001. vertexData.uvs = uvs;
  28002. if (faceColors && flat) {
  28003. vertexData.colors = colors;
  28004. }
  28005. return vertexData;
  28006. };
  28007. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28008. /**
  28009. * Creates the VertexData of the Torus Knot.
  28010. */
  28011. VertexData.CreateTorusKnot = function (options) {
  28012. var indices = [];
  28013. var positions = [];
  28014. var normals = [];
  28015. var uvs = [];
  28016. var radius = options.radius || 2;
  28017. var tube = options.tube || 0.5;
  28018. var radialSegments = options.radialSegments || 32;
  28019. var tubularSegments = options.tubularSegments || 32;
  28020. var p = options.p || 2;
  28021. var q = options.q || 3;
  28022. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28023. // Helper
  28024. var getPos = function (angle) {
  28025. var cu = Math.cos(angle);
  28026. var su = Math.sin(angle);
  28027. var quOverP = q / p * angle;
  28028. var cs = Math.cos(quOverP);
  28029. var tx = radius * (2 + cs) * 0.5 * cu;
  28030. var ty = radius * (2 + cs) * su * 0.5;
  28031. var tz = radius * Math.sin(quOverP) * 0.5;
  28032. return new BABYLON.Vector3(tx, ty, tz);
  28033. };
  28034. // Vertices
  28035. var i;
  28036. var j;
  28037. for (i = 0; i <= radialSegments; i++) {
  28038. var modI = i % radialSegments;
  28039. var u = modI / radialSegments * 2 * p * Math.PI;
  28040. var p1 = getPos(u);
  28041. var p2 = getPos(u + 0.01);
  28042. var tang = p2.subtract(p1);
  28043. var n = p2.add(p1);
  28044. var bitan = BABYLON.Vector3.Cross(tang, n);
  28045. n = BABYLON.Vector3.Cross(bitan, tang);
  28046. bitan.normalize();
  28047. n.normalize();
  28048. for (j = 0; j < tubularSegments; j++) {
  28049. var modJ = j % tubularSegments;
  28050. var v = modJ / tubularSegments * 2 * Math.PI;
  28051. var cx = -tube * Math.cos(v);
  28052. var cy = tube * Math.sin(v);
  28053. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28054. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28055. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28056. uvs.push(i / radialSegments);
  28057. uvs.push(j / tubularSegments);
  28058. }
  28059. }
  28060. for (i = 0; i < radialSegments; i++) {
  28061. for (j = 0; j < tubularSegments; j++) {
  28062. var jNext = (j + 1) % tubularSegments;
  28063. var a = i * tubularSegments + j;
  28064. var b = (i + 1) * tubularSegments + j;
  28065. var c = (i + 1) * tubularSegments + jNext;
  28066. var d = i * tubularSegments + jNext;
  28067. indices.push(d);
  28068. indices.push(b);
  28069. indices.push(a);
  28070. indices.push(d);
  28071. indices.push(c);
  28072. indices.push(b);
  28073. }
  28074. }
  28075. // Normals
  28076. VertexData.ComputeNormals(positions, indices, normals);
  28077. // Sides
  28078. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28079. // Result
  28080. var vertexData = new VertexData();
  28081. vertexData.indices = indices;
  28082. vertexData.positions = positions;
  28083. vertexData.normals = normals;
  28084. vertexData.uvs = uvs;
  28085. return vertexData;
  28086. };
  28087. // Tools
  28088. /**
  28089. * @param {any} - positions (number[] or Float32Array)
  28090. * @param {any} - indices (number[] or Uint16Array)
  28091. * @param {any} - normals (number[] or Float32Array)
  28092. * options (optional) :
  28093. * facetPositions : optional array of facet positions (vector3)
  28094. * facetNormals : optional array of facet normals (vector3)
  28095. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28096. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28097. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28098. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28099. * bInfo : optional bounding info, required for facetPartitioning computation
  28100. */
  28101. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28102. // temporary scalar variables
  28103. var index = 0; // facet index
  28104. var p1p2x = 0.0; // p1p2 vector x coordinate
  28105. var p1p2y = 0.0; // p1p2 vector y coordinate
  28106. var p1p2z = 0.0; // p1p2 vector z coordinate
  28107. var p3p2x = 0.0; // p3p2 vector x coordinate
  28108. var p3p2y = 0.0; // p3p2 vector y coordinate
  28109. var p3p2z = 0.0; // p3p2 vector z coordinate
  28110. var faceNormalx = 0.0; // facet normal x coordinate
  28111. var faceNormaly = 0.0; // facet normal y coordinate
  28112. var faceNormalz = 0.0; // facet normal z coordinate
  28113. var length = 0.0; // facet normal length before normalization
  28114. var v1x = 0; // vector1 x index in the positions array
  28115. var v1y = 0; // vector1 y index in the positions array
  28116. var v1z = 0; // vector1 z index in the positions array
  28117. var v2x = 0; // vector2 x index in the positions array
  28118. var v2y = 0; // vector2 y index in the positions array
  28119. var v2z = 0; // vector2 z index in the positions array
  28120. var v3x = 0; // vector3 x index in the positions array
  28121. var v3y = 0; // vector3 y index in the positions array
  28122. var v3z = 0; // vector3 z index in the positions array
  28123. var computeFacetNormals = false;
  28124. var computeFacetPositions = false;
  28125. var computeFacetPartitioning = false;
  28126. var faceNormalSign = 1;
  28127. if (options) {
  28128. computeFacetNormals = (options.facetNormals) ? true : false;
  28129. computeFacetPositions = (options.facetPositions) ? true : false;
  28130. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28131. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28132. }
  28133. // facetPartitioning reinit if needed
  28134. if (computeFacetPartitioning) {
  28135. var ox = 0; // X partitioning index for facet position
  28136. var oy = 0; // Y partinioning index for facet position
  28137. var oz = 0; // Z partinioning index for facet position
  28138. var b1x = 0; // X partitioning index for facet v1 vertex
  28139. var b1y = 0; // Y partitioning index for facet v1 vertex
  28140. var b1z = 0; // z partitioning index for facet v1 vertex
  28141. var b2x = 0; // X partitioning index for facet v2 vertex
  28142. var b2y = 0; // Y partitioning index for facet v2 vertex
  28143. var b2z = 0; // Z partitioning index for facet v2 vertex
  28144. var b3x = 0; // X partitioning index for facet v3 vertex
  28145. var b3y = 0; // Y partitioning index for facet v3 vertex
  28146. var b3z = 0; // Z partitioning index for facet v3 vertex
  28147. var block_idx_o = 0; // facet barycenter block index
  28148. var block_idx_v1 = 0; // v1 vertex block index
  28149. var block_idx_v2 = 0; // v2 vertex block index
  28150. var block_idx_v3 = 0; // v3 vertex block index
  28151. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28152. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28153. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28154. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28155. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28156. var subSq = options.subDiv.max * options.subDiv.max;
  28157. options.facetPartitioning.length = 0;
  28158. }
  28159. // reset the normals
  28160. for (index = 0; index < positions.length; index++) {
  28161. normals[index] = 0.0;
  28162. }
  28163. // Loop : 1 indice triplet = 1 facet
  28164. var nbFaces = indices.length / 3;
  28165. for (index = 0; index < nbFaces; index++) {
  28166. // get the indexes of the coordinates of each vertex of the facet
  28167. v1x = indices[index * 3] * 3;
  28168. v1y = v1x + 1;
  28169. v1z = v1x + 2;
  28170. v2x = indices[index * 3 + 1] * 3;
  28171. v2y = v2x + 1;
  28172. v2z = v2x + 2;
  28173. v3x = indices[index * 3 + 2] * 3;
  28174. v3y = v3x + 1;
  28175. v3z = v3x + 2;
  28176. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28177. p1p2y = positions[v1y] - positions[v2y];
  28178. p1p2z = positions[v1z] - positions[v2z];
  28179. p3p2x = positions[v3x] - positions[v2x];
  28180. p3p2y = positions[v3y] - positions[v2y];
  28181. p3p2z = positions[v3z] - positions[v2z];
  28182. // compute the face normal with the cross product
  28183. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28184. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28185. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28186. // normalize this normal and store it in the array facetData
  28187. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28188. length = (length === 0) ? 1.0 : length;
  28189. faceNormalx /= length;
  28190. faceNormaly /= length;
  28191. faceNormalz /= length;
  28192. if (computeFacetNormals) {
  28193. options.facetNormals[index].x = faceNormalx;
  28194. options.facetNormals[index].y = faceNormaly;
  28195. options.facetNormals[index].z = faceNormalz;
  28196. }
  28197. if (computeFacetPositions) {
  28198. // compute and the facet barycenter coordinates in the array facetPositions
  28199. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28200. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28201. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28202. }
  28203. if (computeFacetPartitioning) {
  28204. // store the facet indexes in arrays in the main facetPartitioning array :
  28205. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28206. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28207. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28208. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28209. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28210. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28211. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28212. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28213. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28214. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28215. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28216. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28217. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28218. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28219. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28220. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28221. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28222. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28223. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28224. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28225. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28226. // push each facet index in each block containing the vertex
  28227. options.facetPartitioning[block_idx_v1].push(index);
  28228. if (block_idx_v2 != block_idx_v1) {
  28229. options.facetPartitioning[block_idx_v2].push(index);
  28230. }
  28231. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28232. options.facetPartitioning[block_idx_v3].push(index);
  28233. }
  28234. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28235. options.facetPartitioning[block_idx_o].push(index);
  28236. }
  28237. }
  28238. // compute the normals anyway
  28239. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28240. normals[v1y] += faceNormaly;
  28241. normals[v1z] += faceNormalz;
  28242. normals[v2x] += faceNormalx;
  28243. normals[v2y] += faceNormaly;
  28244. normals[v2z] += faceNormalz;
  28245. normals[v3x] += faceNormalx;
  28246. normals[v3y] += faceNormaly;
  28247. normals[v3z] += faceNormalz;
  28248. }
  28249. // last normalization of each normal
  28250. for (index = 0; index < normals.length / 3; index++) {
  28251. faceNormalx = normals[index * 3];
  28252. faceNormaly = normals[index * 3 + 1];
  28253. faceNormalz = normals[index * 3 + 2];
  28254. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28255. length = (length === 0) ? 1.0 : length;
  28256. faceNormalx /= length;
  28257. faceNormaly /= length;
  28258. faceNormalz /= length;
  28259. normals[index * 3] = faceNormalx;
  28260. normals[index * 3 + 1] = faceNormaly;
  28261. normals[index * 3 + 2] = faceNormalz;
  28262. }
  28263. };
  28264. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28265. var li = indices.length;
  28266. var ln = normals.length;
  28267. var i;
  28268. var n;
  28269. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28270. switch (sideOrientation) {
  28271. case BABYLON.Mesh.FRONTSIDE:
  28272. // nothing changed
  28273. break;
  28274. case BABYLON.Mesh.BACKSIDE:
  28275. var tmp;
  28276. // indices
  28277. for (i = 0; i < li; i += 3) {
  28278. tmp = indices[i];
  28279. indices[i] = indices[i + 2];
  28280. indices[i + 2] = tmp;
  28281. }
  28282. // normals
  28283. for (n = 0; n < ln; n++) {
  28284. normals[n] = -normals[n];
  28285. }
  28286. break;
  28287. case BABYLON.Mesh.DOUBLESIDE:
  28288. // positions
  28289. var lp = positions.length;
  28290. var l = lp / 3;
  28291. for (var p = 0; p < lp; p++) {
  28292. positions[lp + p] = positions[p];
  28293. }
  28294. // indices
  28295. for (i = 0; i < li; i += 3) {
  28296. indices[i + li] = indices[i + 2] + l;
  28297. indices[i + 1 + li] = indices[i + 1] + l;
  28298. indices[i + 2 + li] = indices[i] + l;
  28299. }
  28300. // normals
  28301. for (n = 0; n < ln; n++) {
  28302. normals[ln + n] = -normals[n];
  28303. }
  28304. // uvs
  28305. var lu = uvs.length;
  28306. var u = 0;
  28307. for (u = 0; u < lu; u++) {
  28308. uvs[u + lu] = uvs[u];
  28309. }
  28310. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28311. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28312. u = 0;
  28313. for (i = 0; i < lu / 2; i++) {
  28314. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28315. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28316. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28317. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28318. u += 2;
  28319. }
  28320. break;
  28321. }
  28322. };
  28323. /**
  28324. * Creates a new VertexData from the imported parameters.
  28325. */
  28326. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28327. var vertexData = new VertexData();
  28328. // positions
  28329. var positions = parsedVertexData.positions;
  28330. if (positions) {
  28331. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28332. }
  28333. // normals
  28334. var normals = parsedVertexData.normals;
  28335. if (normals) {
  28336. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28337. }
  28338. // tangents
  28339. var tangents = parsedVertexData.tangents;
  28340. if (tangents) {
  28341. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28342. }
  28343. // uvs
  28344. var uvs = parsedVertexData.uvs;
  28345. if (uvs) {
  28346. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28347. }
  28348. // uv2s
  28349. var uv2s = parsedVertexData.uv2s;
  28350. if (uv2s) {
  28351. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28352. }
  28353. // uv3s
  28354. var uv3s = parsedVertexData.uv3s;
  28355. if (uv3s) {
  28356. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28357. }
  28358. // uv4s
  28359. var uv4s = parsedVertexData.uv4s;
  28360. if (uv4s) {
  28361. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28362. }
  28363. // uv5s
  28364. var uv5s = parsedVertexData.uv5s;
  28365. if (uv5s) {
  28366. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28367. }
  28368. // uv6s
  28369. var uv6s = parsedVertexData.uv6s;
  28370. if (uv6s) {
  28371. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28372. }
  28373. // colors
  28374. var colors = parsedVertexData.colors;
  28375. if (colors) {
  28376. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28377. }
  28378. // matricesIndices
  28379. var matricesIndices = parsedVertexData.matricesIndices;
  28380. if (matricesIndices) {
  28381. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28382. }
  28383. // matricesWeights
  28384. var matricesWeights = parsedVertexData.matricesWeights;
  28385. if (matricesWeights) {
  28386. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28387. }
  28388. // indices
  28389. var indices = parsedVertexData.indices;
  28390. if (indices) {
  28391. vertexData.indices = indices;
  28392. }
  28393. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28394. };
  28395. return VertexData;
  28396. }());
  28397. BABYLON.VertexData = VertexData;
  28398. })(BABYLON || (BABYLON = {}));
  28399. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28400. var BABYLON;
  28401. (function (BABYLON) {
  28402. var Geometry = (function () {
  28403. function Geometry(id, scene, vertexData, updatable, mesh) {
  28404. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28405. this._totalVertices = 0;
  28406. this._isDisposed = false;
  28407. this.id = id;
  28408. this._engine = scene.getEngine();
  28409. this._meshes = [];
  28410. this._scene = scene;
  28411. //Init vertex buffer cache
  28412. this._vertexBuffers = {};
  28413. this._indices = [];
  28414. this._updatable = updatable;
  28415. // vertexData
  28416. if (vertexData) {
  28417. this.setAllVerticesData(vertexData, updatable);
  28418. }
  28419. else {
  28420. this._totalVertices = 0;
  28421. this._indices = [];
  28422. }
  28423. if (this._engine.getCaps().vertexArrayObject) {
  28424. this._vertexArrayObjects = {};
  28425. }
  28426. // applyToMesh
  28427. if (mesh) {
  28428. if (mesh.getClassName() === "LinesMesh") {
  28429. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28430. this.updateExtend();
  28431. }
  28432. this.applyToMesh(mesh);
  28433. mesh.computeWorldMatrix(true);
  28434. }
  28435. }
  28436. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28437. /**
  28438. * 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
  28439. * @returns The Bias Vector
  28440. */
  28441. get: function () {
  28442. return this._boundingBias;
  28443. },
  28444. set: function (value) {
  28445. if (this._boundingBias && this._boundingBias.equals(value)) {
  28446. return;
  28447. }
  28448. this._boundingBias = value.clone();
  28449. this.updateBoundingInfo(true, null);
  28450. },
  28451. enumerable: true,
  28452. configurable: true
  28453. });
  28454. Object.defineProperty(Geometry.prototype, "extend", {
  28455. get: function () {
  28456. return this._extend;
  28457. },
  28458. enumerable: true,
  28459. configurable: true
  28460. });
  28461. Geometry.prototype.getScene = function () {
  28462. return this._scene;
  28463. };
  28464. Geometry.prototype.getEngine = function () {
  28465. return this._engine;
  28466. };
  28467. Geometry.prototype.isReady = function () {
  28468. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28469. };
  28470. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28471. get: function () {
  28472. for (var index = 0; index < this._meshes.length; index++) {
  28473. if (!this._meshes[index].doNotSerialize) {
  28474. return false;
  28475. }
  28476. }
  28477. return true;
  28478. },
  28479. enumerable: true,
  28480. configurable: true
  28481. });
  28482. Geometry.prototype._rebuild = function () {
  28483. if (this._vertexArrayObjects) {
  28484. this._vertexArrayObjects = {};
  28485. }
  28486. // Index buffer
  28487. if (this._meshes.length !== 0 && this._indices) {
  28488. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28489. }
  28490. // Vertex buffers
  28491. for (var key in this._vertexBuffers) {
  28492. var vertexBuffer = this._vertexBuffers[key];
  28493. vertexBuffer._rebuild();
  28494. }
  28495. };
  28496. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28497. vertexData.applyToGeometry(this, updatable);
  28498. this.notifyUpdate();
  28499. };
  28500. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28501. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28502. this.setVerticesBuffer(buffer);
  28503. };
  28504. Geometry.prototype.removeVerticesData = function (kind) {
  28505. if (this._vertexBuffers[kind]) {
  28506. this._vertexBuffers[kind].dispose();
  28507. delete this._vertexBuffers[kind];
  28508. }
  28509. };
  28510. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28511. var kind = buffer.getKind();
  28512. if (this._vertexBuffers[kind]) {
  28513. this._vertexBuffers[kind].dispose();
  28514. }
  28515. this._vertexBuffers[kind] = buffer;
  28516. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28517. var data = buffer.getData();
  28518. var stride = buffer.getStrideSize();
  28519. this._totalVertices = data.length / stride;
  28520. this.updateExtend(data, stride);
  28521. this._resetPointsArrayCache();
  28522. var meshes = this._meshes;
  28523. var numOfMeshes = meshes.length;
  28524. for (var index = 0; index < numOfMeshes; index++) {
  28525. var mesh = meshes[index];
  28526. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28527. mesh._createGlobalSubMesh(false);
  28528. mesh.computeWorldMatrix(true);
  28529. }
  28530. }
  28531. this.notifyUpdate(kind);
  28532. if (this._vertexArrayObjects) {
  28533. this._disposeVertexArrayObjects();
  28534. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28535. }
  28536. };
  28537. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28538. var vertexBuffer = this.getVertexBuffer(kind);
  28539. if (!vertexBuffer) {
  28540. return;
  28541. }
  28542. vertexBuffer.updateDirectly(data, offset);
  28543. this.notifyUpdate(kind);
  28544. };
  28545. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28546. var vertexBuffer = this.getVertexBuffer(kind);
  28547. if (!vertexBuffer) {
  28548. return;
  28549. }
  28550. vertexBuffer.update(data);
  28551. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28552. var stride = vertexBuffer.getStrideSize();
  28553. this._totalVertices = data.length / stride;
  28554. this.updateBoundingInfo(updateExtends, data);
  28555. }
  28556. this.notifyUpdate(kind);
  28557. };
  28558. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28559. if (updateExtends) {
  28560. this.updateExtend(data);
  28561. }
  28562. var meshes = this._meshes;
  28563. var numOfMeshes = meshes.length;
  28564. this._resetPointsArrayCache();
  28565. for (var index = 0; index < numOfMeshes; index++) {
  28566. var mesh = meshes[index];
  28567. if (updateExtends) {
  28568. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28569. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28570. var subMesh = mesh.subMeshes[subIndex];
  28571. subMesh.refreshBoundingInfo();
  28572. }
  28573. }
  28574. }
  28575. };
  28576. Geometry.prototype._bind = function (effect, indexToBind) {
  28577. if (indexToBind === void 0) { indexToBind = undefined; }
  28578. if (indexToBind === undefined) {
  28579. indexToBind = this._indexBuffer;
  28580. }
  28581. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  28582. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  28583. return;
  28584. }
  28585. // Using VAO
  28586. if (!this._vertexArrayObjects[effect.key]) {
  28587. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  28588. }
  28589. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  28590. };
  28591. Geometry.prototype.getTotalVertices = function () {
  28592. if (!this.isReady()) {
  28593. return 0;
  28594. }
  28595. return this._totalVertices;
  28596. };
  28597. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28598. var vertexBuffer = this.getVertexBuffer(kind);
  28599. if (!vertexBuffer) {
  28600. return null;
  28601. }
  28602. var orig = vertexBuffer.getData();
  28603. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  28604. return orig;
  28605. }
  28606. else {
  28607. var len = orig.length;
  28608. var copy = [];
  28609. for (var i = 0; i < len; i++) {
  28610. copy.push(orig[i]);
  28611. }
  28612. return copy;
  28613. }
  28614. };
  28615. Geometry.prototype.getVertexBuffer = function (kind) {
  28616. if (!this.isReady()) {
  28617. return null;
  28618. }
  28619. return this._vertexBuffers[kind];
  28620. };
  28621. Geometry.prototype.getVertexBuffers = function () {
  28622. if (!this.isReady()) {
  28623. return null;
  28624. }
  28625. return this._vertexBuffers;
  28626. };
  28627. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28628. if (!this._vertexBuffers) {
  28629. if (this._delayInfo) {
  28630. return this._delayInfo.indexOf(kind) !== -1;
  28631. }
  28632. return false;
  28633. }
  28634. return this._vertexBuffers[kind] !== undefined;
  28635. };
  28636. Geometry.prototype.getVerticesDataKinds = function () {
  28637. var result = [];
  28638. var kind;
  28639. if (!this._vertexBuffers && this._delayInfo) {
  28640. for (kind in this._delayInfo) {
  28641. result.push(kind);
  28642. }
  28643. }
  28644. else {
  28645. for (kind in this._vertexBuffers) {
  28646. result.push(kind);
  28647. }
  28648. }
  28649. return result;
  28650. };
  28651. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28652. if (this._indexBuffer) {
  28653. this._engine._releaseBuffer(this._indexBuffer);
  28654. }
  28655. this._disposeVertexArrayObjects();
  28656. this._indices = indices;
  28657. if (this._meshes.length !== 0 && this._indices) {
  28658. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28659. }
  28660. if (totalVertices !== undefined) {
  28661. this._totalVertices = totalVertices;
  28662. }
  28663. var meshes = this._meshes;
  28664. var numOfMeshes = meshes.length;
  28665. for (var index = 0; index < numOfMeshes; index++) {
  28666. meshes[index]._createGlobalSubMesh(true);
  28667. }
  28668. this.notifyUpdate();
  28669. };
  28670. Geometry.prototype.getTotalIndices = function () {
  28671. if (!this.isReady()) {
  28672. return 0;
  28673. }
  28674. return this._indices.length;
  28675. };
  28676. Geometry.prototype.getIndices = function (copyWhenShared) {
  28677. if (!this.isReady()) {
  28678. return null;
  28679. }
  28680. var orig = this._indices;
  28681. if (!copyWhenShared || this._meshes.length === 1) {
  28682. return orig;
  28683. }
  28684. else {
  28685. var len = orig.length;
  28686. var copy = [];
  28687. for (var i = 0; i < len; i++) {
  28688. copy.push(orig[i]);
  28689. }
  28690. return copy;
  28691. }
  28692. };
  28693. Geometry.prototype.getIndexBuffer = function () {
  28694. if (!this.isReady()) {
  28695. return null;
  28696. }
  28697. return this._indexBuffer;
  28698. };
  28699. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  28700. if (!effect || !this._vertexArrayObjects) {
  28701. return;
  28702. }
  28703. if (this._vertexArrayObjects[effect.key]) {
  28704. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  28705. delete this._vertexArrayObjects[effect.key];
  28706. }
  28707. };
  28708. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28709. var meshes = this._meshes;
  28710. var index = meshes.indexOf(mesh);
  28711. if (index === -1) {
  28712. return;
  28713. }
  28714. meshes.splice(index, 1);
  28715. mesh._geometry = null;
  28716. if (meshes.length === 0 && shouldDispose) {
  28717. this.dispose();
  28718. }
  28719. };
  28720. Geometry.prototype.applyToMesh = function (mesh) {
  28721. if (mesh._geometry === this) {
  28722. return;
  28723. }
  28724. var previousGeometry = mesh._geometry;
  28725. if (previousGeometry) {
  28726. previousGeometry.releaseForMesh(mesh);
  28727. }
  28728. var meshes = this._meshes;
  28729. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28730. mesh._geometry = this;
  28731. this._scene.pushGeometry(this);
  28732. meshes.push(mesh);
  28733. if (this.isReady()) {
  28734. this._applyToMesh(mesh);
  28735. }
  28736. else {
  28737. mesh._boundingInfo = this._boundingInfo;
  28738. }
  28739. };
  28740. Geometry.prototype.updateExtend = function (data, stride) {
  28741. if (data === void 0) { data = null; }
  28742. if (!data) {
  28743. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  28744. }
  28745. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  28746. };
  28747. Geometry.prototype._applyToMesh = function (mesh) {
  28748. var numOfMeshes = this._meshes.length;
  28749. // vertexBuffers
  28750. for (var kind in this._vertexBuffers) {
  28751. if (numOfMeshes === 1) {
  28752. this._vertexBuffers[kind].create();
  28753. }
  28754. var buffer = this._vertexBuffers[kind].getBuffer();
  28755. if (buffer)
  28756. buffer.references = numOfMeshes;
  28757. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28758. if (!this._extend) {
  28759. this.updateExtend(this._vertexBuffers[kind].getData());
  28760. }
  28761. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28762. mesh._createGlobalSubMesh(false);
  28763. //bounding info was just created again, world matrix should be applied again.
  28764. mesh._updateBoundingInfo();
  28765. }
  28766. }
  28767. // indexBuffer
  28768. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  28769. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28770. }
  28771. if (this._indexBuffer) {
  28772. this._indexBuffer.references = numOfMeshes;
  28773. }
  28774. };
  28775. Geometry.prototype.notifyUpdate = function (kind) {
  28776. if (this.onGeometryUpdated) {
  28777. this.onGeometryUpdated(this, kind);
  28778. }
  28779. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  28780. var mesh = _a[_i];
  28781. mesh._markSubMeshesAsAttributesDirty();
  28782. }
  28783. };
  28784. Geometry.prototype.load = function (scene, onLoaded) {
  28785. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28786. return;
  28787. }
  28788. if (this.isReady()) {
  28789. if (onLoaded) {
  28790. onLoaded();
  28791. }
  28792. return;
  28793. }
  28794. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28795. this._queueLoad(scene, onLoaded);
  28796. };
  28797. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  28798. var _this = this;
  28799. scene._addPendingData(this);
  28800. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28801. _this._delayLoadingFunction(JSON.parse(data), _this);
  28802. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28803. _this._delayInfo = [];
  28804. scene._removePendingData(_this);
  28805. var meshes = _this._meshes;
  28806. var numOfMeshes = meshes.length;
  28807. for (var index = 0; index < numOfMeshes; index++) {
  28808. _this._applyToMesh(meshes[index]);
  28809. }
  28810. if (onLoaded) {
  28811. onLoaded();
  28812. }
  28813. }, function () { }, scene.database);
  28814. };
  28815. /**
  28816. * Invert the geometry to move from a right handed system to a left handed one.
  28817. */
  28818. Geometry.prototype.toLeftHanded = function () {
  28819. // Flip faces
  28820. var tIndices = this.getIndices(false);
  28821. if (tIndices != null && tIndices.length > 0) {
  28822. for (var i = 0; i < tIndices.length; i += 3) {
  28823. var tTemp = tIndices[i + 0];
  28824. tIndices[i + 0] = tIndices[i + 2];
  28825. tIndices[i + 2] = tTemp;
  28826. }
  28827. this.setIndices(tIndices);
  28828. }
  28829. // Negate position.z
  28830. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  28831. if (tPositions != null && tPositions.length > 0) {
  28832. for (var i = 0; i < tPositions.length; i += 3) {
  28833. tPositions[i + 2] = -tPositions[i + 2];
  28834. }
  28835. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  28836. }
  28837. // Negate normal.z
  28838. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  28839. if (tNormals != null && tNormals.length > 0) {
  28840. for (var i = 0; i < tNormals.length; i += 3) {
  28841. tNormals[i + 2] = -tNormals[i + 2];
  28842. }
  28843. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  28844. }
  28845. };
  28846. // Cache
  28847. Geometry.prototype._resetPointsArrayCache = function () {
  28848. this._positions = null;
  28849. };
  28850. Geometry.prototype._generatePointsArray = function () {
  28851. if (this._positions)
  28852. return true;
  28853. this._positions = [];
  28854. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28855. if (!data) {
  28856. return false;
  28857. }
  28858. for (var index = 0; index < data.length; index += 3) {
  28859. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  28860. }
  28861. return true;
  28862. };
  28863. Geometry.prototype.isDisposed = function () {
  28864. return this._isDisposed;
  28865. };
  28866. Geometry.prototype._disposeVertexArrayObjects = function () {
  28867. if (this._vertexArrayObjects) {
  28868. for (var kind in this._vertexArrayObjects) {
  28869. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  28870. }
  28871. this._vertexArrayObjects = {};
  28872. }
  28873. };
  28874. Geometry.prototype.dispose = function () {
  28875. var meshes = this._meshes;
  28876. var numOfMeshes = meshes.length;
  28877. var index;
  28878. for (index = 0; index < numOfMeshes; index++) {
  28879. this.releaseForMesh(meshes[index]);
  28880. }
  28881. this._meshes = [];
  28882. this._disposeVertexArrayObjects();
  28883. for (var kind in this._vertexBuffers) {
  28884. this._vertexBuffers[kind].dispose();
  28885. }
  28886. this._vertexBuffers = {};
  28887. this._totalVertices = 0;
  28888. if (this._indexBuffer) {
  28889. this._engine._releaseBuffer(this._indexBuffer);
  28890. }
  28891. this._indexBuffer = null;
  28892. this._indices = [];
  28893. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28894. this.delayLoadingFile = null;
  28895. this._delayLoadingFunction = null;
  28896. this._delayInfo = [];
  28897. this._boundingInfo = null;
  28898. this._scene.removeGeometry(this);
  28899. this._isDisposed = true;
  28900. };
  28901. Geometry.prototype.copy = function (id) {
  28902. var vertexData = new BABYLON.VertexData();
  28903. vertexData.indices = [];
  28904. var indices = this.getIndices();
  28905. for (var index = 0; index < indices.length; index++) {
  28906. vertexData.indices.push(indices[index]);
  28907. }
  28908. var updatable = false;
  28909. var stopChecking = false;
  28910. var kind;
  28911. for (kind in this._vertexBuffers) {
  28912. // using slice() to make a copy of the array and not just reference it
  28913. var data = this.getVerticesData(kind);
  28914. if (data instanceof Float32Array) {
  28915. vertexData.set(new Float32Array(data), kind);
  28916. }
  28917. else {
  28918. vertexData.set(data.slice(0), kind);
  28919. }
  28920. if (!stopChecking) {
  28921. updatable = this.getVertexBuffer(kind).isUpdatable();
  28922. stopChecking = !updatable;
  28923. }
  28924. }
  28925. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28926. geometry.delayLoadState = this.delayLoadState;
  28927. geometry.delayLoadingFile = this.delayLoadingFile;
  28928. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28929. for (kind in this._delayInfo) {
  28930. geometry._delayInfo = geometry._delayInfo || [];
  28931. geometry._delayInfo.push(kind);
  28932. }
  28933. // Bounding info
  28934. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28935. return geometry;
  28936. };
  28937. Geometry.prototype.serialize = function () {
  28938. var serializationObject = {};
  28939. serializationObject.id = this.id;
  28940. serializationObject.updatable = this._updatable;
  28941. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28942. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28943. }
  28944. return serializationObject;
  28945. };
  28946. Geometry.prototype.toNumberArray = function (origin) {
  28947. if (Array.isArray(origin)) {
  28948. return origin;
  28949. }
  28950. else {
  28951. return Array.prototype.slice.call(origin);
  28952. }
  28953. };
  28954. Geometry.prototype.serializeVerticeData = function () {
  28955. var serializationObject = this.serialize();
  28956. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28957. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  28958. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  28959. serializationObject.positions._updatable = true;
  28960. }
  28961. }
  28962. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28963. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  28964. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  28965. serializationObject.normals._updatable = true;
  28966. }
  28967. }
  28968. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28969. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  28970. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  28971. serializationObject.uvs._updatable = true;
  28972. }
  28973. }
  28974. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28975. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  28976. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  28977. serializationObject.uv2s._updatable = true;
  28978. }
  28979. }
  28980. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28981. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  28982. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  28983. serializationObject.uv3s._updatable = true;
  28984. }
  28985. }
  28986. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28987. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  28988. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  28989. serializationObject.uv4s._updatable = true;
  28990. }
  28991. }
  28992. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28993. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  28994. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  28995. serializationObject.uv5s._updatable = true;
  28996. }
  28997. }
  28998. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28999. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29000. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29001. serializationObject.uv6s._updatable = true;
  29002. }
  29003. }
  29004. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29005. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29006. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29007. serializationObject.colors._updatable = true;
  29008. }
  29009. }
  29010. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29011. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29012. serializationObject.matricesIndices._isExpanded = true;
  29013. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29014. serializationObject.matricesIndices._updatable = true;
  29015. }
  29016. }
  29017. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29018. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29019. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29020. serializationObject.matricesWeights._updatable = true;
  29021. }
  29022. }
  29023. serializationObject.indices = this.toNumberArray(this.getIndices());
  29024. return serializationObject;
  29025. };
  29026. // Statics
  29027. Geometry.ExtractFromMesh = function (mesh, id) {
  29028. var geometry = mesh._geometry;
  29029. if (!geometry) {
  29030. return null;
  29031. }
  29032. return geometry.copy(id);
  29033. };
  29034. /**
  29035. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29036. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29037. * Be aware Math.random() could cause collisions, but:
  29038. * "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"
  29039. */
  29040. Geometry.RandomId = function () {
  29041. return BABYLON.Tools.RandomId();
  29042. };
  29043. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29044. var scene = mesh.getScene();
  29045. // Geometry
  29046. var geometryId = parsedGeometry.geometryId;
  29047. if (geometryId) {
  29048. var geometry = scene.getGeometryByID(geometryId);
  29049. if (geometry) {
  29050. geometry.applyToMesh(mesh);
  29051. }
  29052. }
  29053. else if (parsedGeometry instanceof ArrayBuffer) {
  29054. var binaryInfo = mesh._binaryInfo;
  29055. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29056. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29057. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29058. }
  29059. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29060. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29061. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29062. }
  29063. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29064. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29065. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29066. }
  29067. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29068. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29069. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29070. }
  29071. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29072. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29073. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29074. }
  29075. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29076. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29077. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29078. }
  29079. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29080. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29081. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29082. }
  29083. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29084. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29085. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29086. }
  29087. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29088. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29089. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29090. }
  29091. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29092. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29093. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29094. }
  29095. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29096. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29097. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29098. }
  29099. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29100. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29101. mesh.setIndices(indicesData);
  29102. }
  29103. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29104. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29105. mesh.subMeshes = [];
  29106. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29107. var materialIndex = subMeshesData[(i * 5) + 0];
  29108. var verticesStart = subMeshesData[(i * 5) + 1];
  29109. var verticesCount = subMeshesData[(i * 5) + 2];
  29110. var indexStart = subMeshesData[(i * 5) + 3];
  29111. var indexCount = subMeshesData[(i * 5) + 4];
  29112. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29113. }
  29114. }
  29115. }
  29116. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29117. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29118. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29119. if (parsedGeometry.uvs) {
  29120. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29121. }
  29122. if (parsedGeometry.uvs2) {
  29123. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29124. }
  29125. if (parsedGeometry.uvs3) {
  29126. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29127. }
  29128. if (parsedGeometry.uvs4) {
  29129. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29130. }
  29131. if (parsedGeometry.uvs5) {
  29132. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29133. }
  29134. if (parsedGeometry.uvs6) {
  29135. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29136. }
  29137. if (parsedGeometry.colors) {
  29138. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29139. }
  29140. if (parsedGeometry.matricesIndices) {
  29141. if (!parsedGeometry.matricesIndices._isExpanded) {
  29142. var floatIndices = [];
  29143. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29144. var matricesIndex = parsedGeometry.matricesIndices[i];
  29145. floatIndices.push(matricesIndex & 0x000000FF);
  29146. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29147. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29148. floatIndices.push(matricesIndex >> 24);
  29149. }
  29150. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29151. }
  29152. else {
  29153. delete parsedGeometry.matricesIndices._isExpanded;
  29154. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29155. }
  29156. }
  29157. if (parsedGeometry.matricesIndicesExtra) {
  29158. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29159. var floatIndices = [];
  29160. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29161. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29162. floatIndices.push(matricesIndex & 0x000000FF);
  29163. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29164. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29165. floatIndices.push(matricesIndex >> 24);
  29166. }
  29167. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29168. }
  29169. else {
  29170. delete parsedGeometry.matricesIndices._isExpanded;
  29171. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29172. }
  29173. }
  29174. if (parsedGeometry.matricesWeights) {
  29175. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29176. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29177. }
  29178. if (parsedGeometry.matricesWeightsExtra) {
  29179. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29180. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29181. }
  29182. mesh.setIndices(parsedGeometry.indices);
  29183. }
  29184. // SubMeshes
  29185. if (parsedGeometry.subMeshes) {
  29186. mesh.subMeshes = [];
  29187. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29188. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29189. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29190. }
  29191. }
  29192. // Flat shading
  29193. if (mesh._shouldGenerateFlatShading) {
  29194. mesh.convertToFlatShadedMesh();
  29195. delete mesh._shouldGenerateFlatShading;
  29196. }
  29197. // Update
  29198. mesh.computeWorldMatrix(true);
  29199. // Octree
  29200. if (scene['_selectionOctree']) {
  29201. scene['_selectionOctree'].addMesh(mesh);
  29202. }
  29203. };
  29204. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29205. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29206. return;
  29207. }
  29208. var size = matricesWeights.length;
  29209. for (var i = 0; i < size; i += influencers) {
  29210. var weight = 0;
  29211. var biggerIndex = i;
  29212. var biggerWeight = 0;
  29213. for (var j = 0; j < influencers - 1; j++) {
  29214. weight += matricesWeights[i + j];
  29215. if (matricesWeights[i + j] > biggerWeight) {
  29216. biggerWeight = matricesWeights[i + j];
  29217. biggerIndex = i + j;
  29218. }
  29219. }
  29220. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29221. }
  29222. };
  29223. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29224. if (scene.getGeometryByID(parsedVertexData.id)) {
  29225. return null; // null since geometry could be something else than a box...
  29226. }
  29227. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29228. if (BABYLON.Tags) {
  29229. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29230. }
  29231. if (parsedVertexData.delayLoadingFile) {
  29232. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29233. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29234. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29235. geometry._delayInfo = [];
  29236. if (parsedVertexData.hasUVs) {
  29237. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29238. }
  29239. if (parsedVertexData.hasUVs2) {
  29240. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29241. }
  29242. if (parsedVertexData.hasUVs3) {
  29243. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29244. }
  29245. if (parsedVertexData.hasUVs4) {
  29246. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29247. }
  29248. if (parsedVertexData.hasUVs5) {
  29249. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29250. }
  29251. if (parsedVertexData.hasUVs6) {
  29252. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29253. }
  29254. if (parsedVertexData.hasColors) {
  29255. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29256. }
  29257. if (parsedVertexData.hasMatricesIndices) {
  29258. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29259. }
  29260. if (parsedVertexData.hasMatricesWeights) {
  29261. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29262. }
  29263. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29264. }
  29265. else {
  29266. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29267. }
  29268. scene.pushGeometry(geometry, true);
  29269. return geometry;
  29270. };
  29271. return Geometry;
  29272. }());
  29273. BABYLON.Geometry = Geometry;
  29274. /////// Primitives //////////////////////////////////////////////
  29275. (function (Geometry) {
  29276. var Primitives;
  29277. (function (Primitives) {
  29278. /// Abstract class
  29279. var _Primitive = (function (_super) {
  29280. __extends(_Primitive, _super);
  29281. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29282. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29283. _this._canBeRegenerated = _canBeRegenerated;
  29284. _this._beingRegenerated = true;
  29285. _this.regenerate();
  29286. _this._beingRegenerated = false;
  29287. return _this;
  29288. }
  29289. _Primitive.prototype.canBeRegenerated = function () {
  29290. return this._canBeRegenerated;
  29291. };
  29292. _Primitive.prototype.regenerate = function () {
  29293. if (!this._canBeRegenerated) {
  29294. return;
  29295. }
  29296. this._beingRegenerated = true;
  29297. this.setAllVerticesData(this._regenerateVertexData(), false);
  29298. this._beingRegenerated = false;
  29299. };
  29300. _Primitive.prototype.asNewGeometry = function (id) {
  29301. return _super.prototype.copy.call(this, id);
  29302. };
  29303. // overrides
  29304. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29305. if (!this._beingRegenerated) {
  29306. return;
  29307. }
  29308. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29309. };
  29310. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29311. if (!this._beingRegenerated) {
  29312. return;
  29313. }
  29314. _super.prototype.setVerticesData.call(this, kind, data, false);
  29315. };
  29316. // to override
  29317. // protected
  29318. _Primitive.prototype._regenerateVertexData = function () {
  29319. throw new Error("Abstract method");
  29320. };
  29321. _Primitive.prototype.copy = function (id) {
  29322. throw new Error("Must be overriden in sub-classes.");
  29323. };
  29324. _Primitive.prototype.serialize = function () {
  29325. var serializationObject = _super.prototype.serialize.call(this);
  29326. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29327. return serializationObject;
  29328. };
  29329. return _Primitive;
  29330. }(Geometry));
  29331. Primitives._Primitive = _Primitive;
  29332. var Ribbon = (function (_super) {
  29333. __extends(Ribbon, _super);
  29334. // Members
  29335. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29336. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29337. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29338. _this.pathArray = pathArray;
  29339. _this.closeArray = closeArray;
  29340. _this.closePath = closePath;
  29341. _this.offset = offset;
  29342. _this.side = side;
  29343. return _this;
  29344. }
  29345. Ribbon.prototype._regenerateVertexData = function () {
  29346. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29347. };
  29348. Ribbon.prototype.copy = function (id) {
  29349. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29350. };
  29351. return Ribbon;
  29352. }(_Primitive));
  29353. Primitives.Ribbon = Ribbon;
  29354. var Box = (function (_super) {
  29355. __extends(Box, _super);
  29356. // Members
  29357. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29358. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29359. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29360. _this.size = size;
  29361. _this.side = side;
  29362. return _this;
  29363. }
  29364. Box.prototype._regenerateVertexData = function () {
  29365. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29366. };
  29367. Box.prototype.copy = function (id) {
  29368. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29369. };
  29370. Box.prototype.serialize = function () {
  29371. var serializationObject = _super.prototype.serialize.call(this);
  29372. serializationObject.size = this.size;
  29373. return serializationObject;
  29374. };
  29375. Box.Parse = function (parsedBox, scene) {
  29376. if (scene.getGeometryByID(parsedBox.id)) {
  29377. return null; // null since geometry could be something else than a box...
  29378. }
  29379. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29380. if (BABYLON.Tags) {
  29381. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29382. }
  29383. scene.pushGeometry(box, true);
  29384. return box;
  29385. };
  29386. return Box;
  29387. }(_Primitive));
  29388. Primitives.Box = Box;
  29389. var Sphere = (function (_super) {
  29390. __extends(Sphere, _super);
  29391. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29392. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29393. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29394. _this.segments = segments;
  29395. _this.diameter = diameter;
  29396. _this.side = side;
  29397. return _this;
  29398. }
  29399. Sphere.prototype._regenerateVertexData = function () {
  29400. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29401. };
  29402. Sphere.prototype.copy = function (id) {
  29403. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29404. };
  29405. Sphere.prototype.serialize = function () {
  29406. var serializationObject = _super.prototype.serialize.call(this);
  29407. serializationObject.segments = this.segments;
  29408. serializationObject.diameter = this.diameter;
  29409. return serializationObject;
  29410. };
  29411. Sphere.Parse = function (parsedSphere, scene) {
  29412. if (scene.getGeometryByID(parsedSphere.id)) {
  29413. return null; // null since geometry could be something else than a sphere...
  29414. }
  29415. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29416. if (BABYLON.Tags) {
  29417. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29418. }
  29419. scene.pushGeometry(sphere, true);
  29420. return sphere;
  29421. };
  29422. return Sphere;
  29423. }(_Primitive));
  29424. Primitives.Sphere = Sphere;
  29425. var Disc = (function (_super) {
  29426. __extends(Disc, _super);
  29427. // Members
  29428. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29429. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29430. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29431. _this.radius = radius;
  29432. _this.tessellation = tessellation;
  29433. _this.side = side;
  29434. return _this;
  29435. }
  29436. Disc.prototype._regenerateVertexData = function () {
  29437. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29438. };
  29439. Disc.prototype.copy = function (id) {
  29440. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29441. };
  29442. return Disc;
  29443. }(_Primitive));
  29444. Primitives.Disc = Disc;
  29445. var Cylinder = (function (_super) {
  29446. __extends(Cylinder, _super);
  29447. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29448. if (subdivisions === void 0) { subdivisions = 1; }
  29449. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29450. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29451. _this.height = height;
  29452. _this.diameterTop = diameterTop;
  29453. _this.diameterBottom = diameterBottom;
  29454. _this.tessellation = tessellation;
  29455. _this.subdivisions = subdivisions;
  29456. _this.side = side;
  29457. return _this;
  29458. }
  29459. Cylinder.prototype._regenerateVertexData = function () {
  29460. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29461. };
  29462. Cylinder.prototype.copy = function (id) {
  29463. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29464. };
  29465. Cylinder.prototype.serialize = function () {
  29466. var serializationObject = _super.prototype.serialize.call(this);
  29467. serializationObject.height = this.height;
  29468. serializationObject.diameterTop = this.diameterTop;
  29469. serializationObject.diameterBottom = this.diameterBottom;
  29470. serializationObject.tessellation = this.tessellation;
  29471. return serializationObject;
  29472. };
  29473. Cylinder.Parse = function (parsedCylinder, scene) {
  29474. if (scene.getGeometryByID(parsedCylinder.id)) {
  29475. return null; // null since geometry could be something else than a cylinder...
  29476. }
  29477. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29478. if (BABYLON.Tags) {
  29479. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29480. }
  29481. scene.pushGeometry(cylinder, true);
  29482. return cylinder;
  29483. };
  29484. return Cylinder;
  29485. }(_Primitive));
  29486. Primitives.Cylinder = Cylinder;
  29487. var Torus = (function (_super) {
  29488. __extends(Torus, _super);
  29489. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29490. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29491. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29492. _this.diameter = diameter;
  29493. _this.thickness = thickness;
  29494. _this.tessellation = tessellation;
  29495. _this.side = side;
  29496. return _this;
  29497. }
  29498. Torus.prototype._regenerateVertexData = function () {
  29499. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29500. };
  29501. Torus.prototype.copy = function (id) {
  29502. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29503. };
  29504. Torus.prototype.serialize = function () {
  29505. var serializationObject = _super.prototype.serialize.call(this);
  29506. serializationObject.diameter = this.diameter;
  29507. serializationObject.thickness = this.thickness;
  29508. serializationObject.tessellation = this.tessellation;
  29509. return serializationObject;
  29510. };
  29511. Torus.Parse = function (parsedTorus, scene) {
  29512. if (scene.getGeometryByID(parsedTorus.id)) {
  29513. return null; // null since geometry could be something else than a torus...
  29514. }
  29515. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29516. if (BABYLON.Tags) {
  29517. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29518. }
  29519. scene.pushGeometry(torus, true);
  29520. return torus;
  29521. };
  29522. return Torus;
  29523. }(_Primitive));
  29524. Primitives.Torus = Torus;
  29525. var Ground = (function (_super) {
  29526. __extends(Ground, _super);
  29527. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29528. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29529. _this.width = width;
  29530. _this.height = height;
  29531. _this.subdivisions = subdivisions;
  29532. return _this;
  29533. }
  29534. Ground.prototype._regenerateVertexData = function () {
  29535. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29536. };
  29537. Ground.prototype.copy = function (id) {
  29538. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29539. };
  29540. Ground.prototype.serialize = function () {
  29541. var serializationObject = _super.prototype.serialize.call(this);
  29542. serializationObject.width = this.width;
  29543. serializationObject.height = this.height;
  29544. serializationObject.subdivisions = this.subdivisions;
  29545. return serializationObject;
  29546. };
  29547. Ground.Parse = function (parsedGround, scene) {
  29548. if (scene.getGeometryByID(parsedGround.id)) {
  29549. return null; // null since geometry could be something else than a ground...
  29550. }
  29551. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29552. if (BABYLON.Tags) {
  29553. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29554. }
  29555. scene.pushGeometry(ground, true);
  29556. return ground;
  29557. };
  29558. return Ground;
  29559. }(_Primitive));
  29560. Primitives.Ground = Ground;
  29561. var TiledGround = (function (_super) {
  29562. __extends(TiledGround, _super);
  29563. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29564. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29565. _this.xmin = xmin;
  29566. _this.zmin = zmin;
  29567. _this.xmax = xmax;
  29568. _this.zmax = zmax;
  29569. _this.subdivisions = subdivisions;
  29570. _this.precision = precision;
  29571. return _this;
  29572. }
  29573. TiledGround.prototype._regenerateVertexData = function () {
  29574. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29575. };
  29576. TiledGround.prototype.copy = function (id) {
  29577. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29578. };
  29579. return TiledGround;
  29580. }(_Primitive));
  29581. Primitives.TiledGround = TiledGround;
  29582. var Plane = (function (_super) {
  29583. __extends(Plane, _super);
  29584. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29585. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29586. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29587. _this.size = size;
  29588. _this.side = side;
  29589. return _this;
  29590. }
  29591. Plane.prototype._regenerateVertexData = function () {
  29592. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29593. };
  29594. Plane.prototype.copy = function (id) {
  29595. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29596. };
  29597. Plane.prototype.serialize = function () {
  29598. var serializationObject = _super.prototype.serialize.call(this);
  29599. serializationObject.size = this.size;
  29600. return serializationObject;
  29601. };
  29602. Plane.Parse = function (parsedPlane, scene) {
  29603. if (scene.getGeometryByID(parsedPlane.id)) {
  29604. return null; // null since geometry could be something else than a ground...
  29605. }
  29606. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  29607. if (BABYLON.Tags) {
  29608. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  29609. }
  29610. scene.pushGeometry(plane, true);
  29611. return plane;
  29612. };
  29613. return Plane;
  29614. }(_Primitive));
  29615. Primitives.Plane = Plane;
  29616. var TorusKnot = (function (_super) {
  29617. __extends(TorusKnot, _super);
  29618. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29619. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29620. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29621. _this.radius = radius;
  29622. _this.tube = tube;
  29623. _this.radialSegments = radialSegments;
  29624. _this.tubularSegments = tubularSegments;
  29625. _this.p = p;
  29626. _this.q = q;
  29627. _this.side = side;
  29628. return _this;
  29629. }
  29630. TorusKnot.prototype._regenerateVertexData = function () {
  29631. 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 });
  29632. };
  29633. TorusKnot.prototype.copy = function (id) {
  29634. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29635. };
  29636. TorusKnot.prototype.serialize = function () {
  29637. var serializationObject = _super.prototype.serialize.call(this);
  29638. serializationObject.radius = this.radius;
  29639. serializationObject.tube = this.tube;
  29640. serializationObject.radialSegments = this.radialSegments;
  29641. serializationObject.tubularSegments = this.tubularSegments;
  29642. serializationObject.p = this.p;
  29643. serializationObject.q = this.q;
  29644. return serializationObject;
  29645. };
  29646. ;
  29647. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  29648. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  29649. return null; // null since geometry could be something else than a ground...
  29650. }
  29651. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  29652. if (BABYLON.Tags) {
  29653. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  29654. }
  29655. scene.pushGeometry(torusKnot, true);
  29656. return torusKnot;
  29657. };
  29658. return TorusKnot;
  29659. }(_Primitive));
  29660. Primitives.TorusKnot = TorusKnot;
  29661. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29662. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29663. })(BABYLON || (BABYLON = {}));
  29664. //# sourceMappingURL=babylon.geometry.js.map
  29665. var BABYLON;
  29666. (function (BABYLON) {
  29667. var PostProcessManager = (function () {
  29668. function PostProcessManager(scene) {
  29669. this._vertexBuffers = {};
  29670. this._scene = scene;
  29671. }
  29672. PostProcessManager.prototype._prepareBuffers = function () {
  29673. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29674. return;
  29675. }
  29676. // VBO
  29677. var vertices = [];
  29678. vertices.push(1, 1);
  29679. vertices.push(-1, 1);
  29680. vertices.push(-1, -1);
  29681. vertices.push(1, -1);
  29682. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29683. this._buildIndexBuffer();
  29684. };
  29685. PostProcessManager.prototype._buildIndexBuffer = function () {
  29686. // Indices
  29687. var indices = [];
  29688. indices.push(0);
  29689. indices.push(1);
  29690. indices.push(2);
  29691. indices.push(0);
  29692. indices.push(2);
  29693. indices.push(3);
  29694. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29695. };
  29696. PostProcessManager.prototype._rebuild = function () {
  29697. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29698. return;
  29699. }
  29700. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  29701. this._buildIndexBuffer();
  29702. };
  29703. // Methods
  29704. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  29705. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29706. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29707. return false;
  29708. }
  29709. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  29710. return true;
  29711. };
  29712. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  29713. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  29714. var engine = this._scene.getEngine();
  29715. for (var index = 0; index < postProcesses.length; index++) {
  29716. if (index < postProcesses.length - 1) {
  29717. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29718. }
  29719. else {
  29720. if (targetTexture) {
  29721. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  29722. }
  29723. else {
  29724. engine.restoreDefaultFramebuffer();
  29725. }
  29726. }
  29727. var pp = postProcesses[index];
  29728. var effect = pp.apply();
  29729. if (effect) {
  29730. pp.onBeforeRenderObservable.notifyObservers(effect);
  29731. // VBOs
  29732. this._prepareBuffers();
  29733. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29734. // Draw order
  29735. engine.draw(true, 0, 6);
  29736. pp.onAfterRenderObservable.notifyObservers(effect);
  29737. }
  29738. }
  29739. // Restore depth buffer
  29740. engine.setDepthBuffer(true);
  29741. engine.setDepthWrite(true);
  29742. };
  29743. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29744. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29745. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29746. return;
  29747. }
  29748. var engine = this._scene.getEngine();
  29749. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29750. if (index < len - 1) {
  29751. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29752. }
  29753. else {
  29754. if (targetTexture) {
  29755. engine.bindFramebuffer(targetTexture, faceIndex);
  29756. }
  29757. else {
  29758. engine.restoreDefaultFramebuffer();
  29759. }
  29760. }
  29761. if (doNotPresent) {
  29762. break;
  29763. }
  29764. var pp = postProcesses[index];
  29765. var effect = pp.apply();
  29766. if (effect) {
  29767. pp.onBeforeRenderObservable.notifyObservers(effect);
  29768. // VBOs
  29769. this._prepareBuffers();
  29770. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29771. // Draw order
  29772. engine.draw(true, 0, 6);
  29773. pp.onAfterRenderObservable.notifyObservers(effect);
  29774. }
  29775. }
  29776. // Restore states
  29777. engine.setDepthBuffer(true);
  29778. engine.setDepthWrite(true);
  29779. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29780. };
  29781. PostProcessManager.prototype.dispose = function () {
  29782. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29783. if (buffer) {
  29784. buffer.dispose();
  29785. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29786. }
  29787. if (this._indexBuffer) {
  29788. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29789. this._indexBuffer = null;
  29790. }
  29791. };
  29792. return PostProcessManager;
  29793. }());
  29794. BABYLON.PostProcessManager = PostProcessManager;
  29795. })(BABYLON || (BABYLON = {}));
  29796. //# sourceMappingURL=babylon.postProcessManager.js.map
  29797. var BABYLON;
  29798. (function (BABYLON) {
  29799. /**
  29800. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  29801. */
  29802. var PerformanceMonitor = (function () {
  29803. /**
  29804. * constructor
  29805. * @param frameSampleSize The number of samples required to saturate the sliding window
  29806. */
  29807. function PerformanceMonitor(frameSampleSize) {
  29808. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  29809. this._enabled = true;
  29810. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  29811. }
  29812. /**
  29813. * Samples current frame
  29814. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  29815. */
  29816. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  29817. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  29818. if (!this._enabled)
  29819. return;
  29820. if (this._lastFrameTimeMs != null) {
  29821. var dt = timeMs - this._lastFrameTimeMs;
  29822. this._rollingFrameTime.add(dt);
  29823. }
  29824. this._lastFrameTimeMs = timeMs;
  29825. };
  29826. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  29827. /**
  29828. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29829. * @return Average frame time in milliseconds
  29830. */
  29831. get: function () {
  29832. return this._rollingFrameTime.average;
  29833. },
  29834. enumerable: true,
  29835. configurable: true
  29836. });
  29837. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  29838. /**
  29839. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29840. * @return Frame time variance in milliseconds squared
  29841. */
  29842. get: function () {
  29843. return this._rollingFrameTime.variance;
  29844. },
  29845. enumerable: true,
  29846. configurable: true
  29847. });
  29848. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  29849. /**
  29850. * Returns the frame time of the most recent frame
  29851. * @return Frame time in milliseconds
  29852. */
  29853. get: function () {
  29854. return this._rollingFrameTime.history(0);
  29855. },
  29856. enumerable: true,
  29857. configurable: true
  29858. });
  29859. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  29860. /**
  29861. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  29862. * @return Framerate in frames per second
  29863. */
  29864. get: function () {
  29865. return 1000.0 / this._rollingFrameTime.average;
  29866. },
  29867. enumerable: true,
  29868. configurable: true
  29869. });
  29870. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  29871. /**
  29872. * Returns the average framerate in frames per second using the most recent frame time
  29873. * @return Framerate in frames per second
  29874. */
  29875. get: function () {
  29876. return 1000.0 / this._rollingFrameTime.history(0);
  29877. },
  29878. enumerable: true,
  29879. configurable: true
  29880. });
  29881. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  29882. /**
  29883. * Returns true if enough samples have been taken to completely fill the sliding window
  29884. * @return true if saturated
  29885. */
  29886. get: function () {
  29887. return this._rollingFrameTime.isSaturated();
  29888. },
  29889. enumerable: true,
  29890. configurable: true
  29891. });
  29892. /**
  29893. * Enables contributions to the sliding window sample set
  29894. */
  29895. PerformanceMonitor.prototype.enable = function () {
  29896. this._enabled = true;
  29897. };
  29898. /**
  29899. * Disables contributions to the sliding window sample set
  29900. * Samples will not be interpolated over the disabled period
  29901. */
  29902. PerformanceMonitor.prototype.disable = function () {
  29903. this._enabled = false;
  29904. //clear last sample to avoid interpolating over the disabled period when next enabled
  29905. this._lastFrameTimeMs = null;
  29906. this._lastChangeTimeMs = null;
  29907. };
  29908. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  29909. /**
  29910. * Returns true if sampling is enabled
  29911. * @return true if enabled
  29912. */
  29913. get: function () {
  29914. return this._enabled;
  29915. },
  29916. enumerable: true,
  29917. configurable: true
  29918. });
  29919. /**
  29920. * Resets performance monitor
  29921. */
  29922. PerformanceMonitor.prototype.reset = function () {
  29923. //clear last sample to avoid interpolating over the disabled period when next enabled
  29924. this._lastFrameTimeMs = null;
  29925. this._lastChangeTimeMs = null;
  29926. //wipe record
  29927. this._rollingFrameTime.reset();
  29928. };
  29929. return PerformanceMonitor;
  29930. }());
  29931. BABYLON.PerformanceMonitor = PerformanceMonitor;
  29932. /**
  29933. * RollingAverage
  29934. *
  29935. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  29936. */
  29937. var RollingAverage = (function () {
  29938. /**
  29939. * constructor
  29940. * @param length The number of samples required to saturate the sliding window
  29941. */
  29942. function RollingAverage(length) {
  29943. this._samples = new Array(length);
  29944. this.reset();
  29945. }
  29946. /**
  29947. * Adds a sample to the sample set
  29948. * @param v The sample value
  29949. */
  29950. RollingAverage.prototype.add = function (v) {
  29951. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  29952. var delta;
  29953. //we need to check if we've already wrapped round
  29954. if (this.isSaturated()) {
  29955. //remove bottom of stack from mean
  29956. var bottomValue = this._samples[this._pos];
  29957. delta = bottomValue - this.average;
  29958. this.average -= delta / (this._sampleCount - 1);
  29959. this._m2 -= delta * (bottomValue - this.average);
  29960. }
  29961. else {
  29962. this._sampleCount++;
  29963. }
  29964. //add new value to mean
  29965. delta = v - this.average;
  29966. this.average += delta / (this._sampleCount);
  29967. this._m2 += delta * (v - this.average);
  29968. //set the new variance
  29969. this.variance = this._m2 / (this._sampleCount - 1);
  29970. this._samples[this._pos] = v;
  29971. this._pos++;
  29972. this._pos %= this._samples.length; //positive wrap around
  29973. };
  29974. /**
  29975. * Returns previously added values or null if outside of history or outside the sliding window domain
  29976. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  29977. * @return Value previously recorded with add() or null if outside of range
  29978. */
  29979. RollingAverage.prototype.history = function (i) {
  29980. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  29981. return null;
  29982. }
  29983. var i0 = this._wrapPosition(this._pos - 1.0);
  29984. return this._samples[this._wrapPosition(i0 - i)];
  29985. };
  29986. /**
  29987. * Returns true if enough samples have been taken to completely fill the sliding window
  29988. * @return true if sample-set saturated
  29989. */
  29990. RollingAverage.prototype.isSaturated = function () {
  29991. return this._sampleCount >= this._samples.length;
  29992. };
  29993. /**
  29994. * Resets the rolling average (equivalent to 0 samples taken so far)
  29995. */
  29996. RollingAverage.prototype.reset = function () {
  29997. this.average = 0;
  29998. this.variance = 0;
  29999. this._sampleCount = 0;
  30000. this._pos = 0;
  30001. this._m2 = 0;
  30002. };
  30003. /**
  30004. * Wraps a value around the sample range boundaries
  30005. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30006. * @return Wrapped position in sample range
  30007. */
  30008. RollingAverage.prototype._wrapPosition = function (i) {
  30009. var max = this._samples.length;
  30010. return ((i % max) + max) % max;
  30011. };
  30012. return RollingAverage;
  30013. }());
  30014. BABYLON.RollingAverage = RollingAverage;
  30015. })(BABYLON || (BABYLON = {}));
  30016. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30017. var BABYLON;
  30018. (function (BABYLON) {
  30019. var AnimationRange = (function () {
  30020. function AnimationRange(name, from, to) {
  30021. this.name = name;
  30022. this.from = from;
  30023. this.to = to;
  30024. }
  30025. AnimationRange.prototype.clone = function () {
  30026. return new AnimationRange(this.name, this.from, this.to);
  30027. };
  30028. return AnimationRange;
  30029. }());
  30030. BABYLON.AnimationRange = AnimationRange;
  30031. /**
  30032. * Composed of a frame, and an action function
  30033. */
  30034. var AnimationEvent = (function () {
  30035. function AnimationEvent(frame, action, onlyOnce) {
  30036. this.frame = frame;
  30037. this.action = action;
  30038. this.onlyOnce = onlyOnce;
  30039. this.isDone = false;
  30040. }
  30041. return AnimationEvent;
  30042. }());
  30043. BABYLON.AnimationEvent = AnimationEvent;
  30044. var PathCursor = (function () {
  30045. function PathCursor(path) {
  30046. this.path = path;
  30047. this._onchange = new Array();
  30048. this.value = 0;
  30049. this.animations = new Array();
  30050. }
  30051. PathCursor.prototype.getPoint = function () {
  30052. var point = this.path.getPointAtLengthPosition(this.value);
  30053. return new BABYLON.Vector3(point.x, 0, point.y);
  30054. };
  30055. PathCursor.prototype.moveAhead = function (step) {
  30056. if (step === void 0) { step = 0.002; }
  30057. this.move(step);
  30058. return this;
  30059. };
  30060. PathCursor.prototype.moveBack = function (step) {
  30061. if (step === void 0) { step = 0.002; }
  30062. this.move(-step);
  30063. return this;
  30064. };
  30065. PathCursor.prototype.move = function (step) {
  30066. if (Math.abs(step) > 1) {
  30067. throw "step size should be less than 1.";
  30068. }
  30069. this.value += step;
  30070. this.ensureLimits();
  30071. this.raiseOnChange();
  30072. return this;
  30073. };
  30074. PathCursor.prototype.ensureLimits = function () {
  30075. while (this.value > 1) {
  30076. this.value -= 1;
  30077. }
  30078. while (this.value < 0) {
  30079. this.value += 1;
  30080. }
  30081. return this;
  30082. };
  30083. // used by animation engine
  30084. PathCursor.prototype.markAsDirty = function (propertyName) {
  30085. this.ensureLimits();
  30086. this.raiseOnChange();
  30087. return this;
  30088. };
  30089. PathCursor.prototype.raiseOnChange = function () {
  30090. var _this = this;
  30091. this._onchange.forEach(function (f) { return f(_this); });
  30092. return this;
  30093. };
  30094. PathCursor.prototype.onchange = function (f) {
  30095. this._onchange.push(f);
  30096. return this;
  30097. };
  30098. return PathCursor;
  30099. }());
  30100. BABYLON.PathCursor = PathCursor;
  30101. var Animation = (function () {
  30102. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  30103. this.name = name;
  30104. this.targetProperty = targetProperty;
  30105. this.framePerSecond = framePerSecond;
  30106. this.dataType = dataType;
  30107. this.loopMode = loopMode;
  30108. this.enableBlending = enableBlending;
  30109. this._offsetsCache = {};
  30110. this._highLimitsCache = {};
  30111. this._stopped = false;
  30112. this._blendingFactor = 0;
  30113. // The set of event that will be linked to this animation
  30114. this._events = new Array();
  30115. this.allowMatricesInterpolation = false;
  30116. this.blendingSpeed = 0.01;
  30117. this._ranges = {};
  30118. this.targetPropertyPath = targetProperty.split(".");
  30119. this.dataType = dataType;
  30120. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  30121. }
  30122. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  30123. var dataType = undefined;
  30124. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  30125. dataType = Animation.ANIMATIONTYPE_FLOAT;
  30126. }
  30127. else if (from instanceof BABYLON.Quaternion) {
  30128. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  30129. }
  30130. else if (from instanceof BABYLON.Vector3) {
  30131. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  30132. }
  30133. else if (from instanceof BABYLON.Vector2) {
  30134. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  30135. }
  30136. else if (from instanceof BABYLON.Color3) {
  30137. dataType = Animation.ANIMATIONTYPE_COLOR3;
  30138. }
  30139. else if (from instanceof BABYLON.Size) {
  30140. dataType = Animation.ANIMATIONTYPE_SIZE;
  30141. }
  30142. if (dataType == undefined) {
  30143. return null;
  30144. }
  30145. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  30146. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  30147. animation.setKeys(keys);
  30148. if (easingFunction !== undefined) {
  30149. animation.setEasingFunction(easingFunction);
  30150. }
  30151. return animation;
  30152. };
  30153. /**
  30154. * Sets up an animation.
  30155. * @param property the property to animate
  30156. * @param animationType the animation type to apply
  30157. * @param easingFunction the easing function used in the animation
  30158. * @returns The created animation
  30159. */
  30160. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  30161. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  30162. animation.setEasingFunction(easingFunction);
  30163. return animation;
  30164. };
  30165. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30166. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30167. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30168. };
  30169. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30170. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30171. node.animations.push(animation);
  30172. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30173. };
  30174. /**
  30175. * Transition property of the Camera to the target Value.
  30176. * @param property The property to transition
  30177. * @param targetValue The target Value of the property
  30178. * @param host The object where the property to animate belongs
  30179. * @param scene Scene used to run the animation
  30180. * @param frameRate Framerate (in frame/s) to use
  30181. * @param transition The transition type we want to use
  30182. * @param duration The duration of the animation, in milliseconds
  30183. * @param onAnimationEnd Call back trigger at the end of the animation.
  30184. */
  30185. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  30186. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  30187. if (duration <= 0) {
  30188. host[property] = targetValue;
  30189. if (onAnimationEnd) {
  30190. onAnimationEnd();
  30191. }
  30192. return;
  30193. }
  30194. var endFrame = frameRate * (duration / 1000);
  30195. transition.setKeys([{
  30196. frame: 0,
  30197. value: host[property].clone ? host[property].clone() : host[property]
  30198. },
  30199. {
  30200. frame: endFrame,
  30201. value: targetValue
  30202. }]);
  30203. if (!host.animations) {
  30204. host.animations = [];
  30205. }
  30206. host.animations.push(transition);
  30207. var animation = scene.beginAnimation(host, 0, endFrame, false);
  30208. animation.onAnimationEnd = onAnimationEnd;
  30209. return animation;
  30210. };
  30211. // Methods
  30212. /**
  30213. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30214. */
  30215. Animation.prototype.toString = function (fullDetails) {
  30216. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  30217. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  30218. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  30219. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  30220. if (fullDetails) {
  30221. ret += ", Ranges: {";
  30222. var first = true;
  30223. for (var name in this._ranges) {
  30224. if (first) {
  30225. ret += ", ";
  30226. first = false;
  30227. }
  30228. ret += name;
  30229. }
  30230. ret += "}";
  30231. }
  30232. return ret;
  30233. };
  30234. /**
  30235. * Add an event to this animation.
  30236. */
  30237. Animation.prototype.addEvent = function (event) {
  30238. this._events.push(event);
  30239. };
  30240. /**
  30241. * Remove all events found at the given frame
  30242. * @param frame
  30243. */
  30244. Animation.prototype.removeEvents = function (frame) {
  30245. for (var index = 0; index < this._events.length; index++) {
  30246. if (this._events[index].frame === frame) {
  30247. this._events.splice(index, 1);
  30248. index--;
  30249. }
  30250. }
  30251. };
  30252. Animation.prototype.createRange = function (name, from, to) {
  30253. // check name not already in use; could happen for bones after serialized
  30254. if (!this._ranges[name]) {
  30255. this._ranges[name] = new AnimationRange(name, from, to);
  30256. }
  30257. };
  30258. Animation.prototype.deleteRange = function (name, deleteFrames) {
  30259. if (deleteFrames === void 0) { deleteFrames = true; }
  30260. if (this._ranges[name]) {
  30261. if (deleteFrames) {
  30262. var from = this._ranges[name].from;
  30263. var to = this._ranges[name].to;
  30264. // this loop MUST go high to low for multiple splices to work
  30265. for (var key = this._keys.length - 1; key >= 0; key--) {
  30266. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  30267. this._keys.splice(key, 1);
  30268. }
  30269. }
  30270. }
  30271. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  30272. }
  30273. };
  30274. Animation.prototype.getRange = function (name) {
  30275. return this._ranges[name];
  30276. };
  30277. Animation.prototype.reset = function () {
  30278. this._offsetsCache = {};
  30279. this._highLimitsCache = {};
  30280. this.currentFrame = 0;
  30281. this._blendingFactor = 0;
  30282. this._originalBlendValue = null;
  30283. };
  30284. Animation.prototype.isStopped = function () {
  30285. return this._stopped;
  30286. };
  30287. Animation.prototype.getKeys = function () {
  30288. return this._keys;
  30289. };
  30290. Animation.prototype.getHighestFrame = function () {
  30291. var ret = 0;
  30292. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  30293. if (ret < this._keys[key].frame) {
  30294. ret = this._keys[key].frame;
  30295. }
  30296. }
  30297. return ret;
  30298. };
  30299. Animation.prototype.getEasingFunction = function () {
  30300. return this._easingFunction;
  30301. };
  30302. Animation.prototype.setEasingFunction = function (easingFunction) {
  30303. this._easingFunction = easingFunction;
  30304. };
  30305. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  30306. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  30307. };
  30308. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30309. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30310. };
  30311. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  30312. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  30313. };
  30314. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30315. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  30316. };
  30317. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  30318. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  30319. };
  30320. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30321. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30322. };
  30323. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  30324. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  30325. };
  30326. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30327. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30328. };
  30329. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  30330. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  30331. };
  30332. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  30333. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  30334. };
  30335. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  30336. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  30337. };
  30338. Animation.prototype.clone = function () {
  30339. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  30340. clone.enableBlending = this.enableBlending;
  30341. clone.blendingSpeed = this.blendingSpeed;
  30342. if (this._keys) {
  30343. clone.setKeys(this._keys);
  30344. }
  30345. if (this._ranges) {
  30346. clone._ranges = {};
  30347. for (var name in this._ranges) {
  30348. clone._ranges[name] = this._ranges[name].clone();
  30349. }
  30350. }
  30351. return clone;
  30352. };
  30353. Animation.prototype.setKeys = function (values) {
  30354. this._keys = values.slice(0);
  30355. this._offsetsCache = {};
  30356. this._highLimitsCache = {};
  30357. };
  30358. Animation.prototype._getKeyValue = function (value) {
  30359. if (typeof value === "function") {
  30360. return value();
  30361. }
  30362. return value;
  30363. };
  30364. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  30365. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  30366. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  30367. }
  30368. this.currentFrame = currentFrame;
  30369. // Try to get a hash to find the right key
  30370. 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));
  30371. if (this._keys[startKeyIndex].frame >= currentFrame) {
  30372. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  30373. startKeyIndex--;
  30374. }
  30375. }
  30376. for (var key = startKeyIndex; key < this._keys.length; key++) {
  30377. var endKey = this._keys[key + 1];
  30378. if (endKey.frame >= currentFrame) {
  30379. var startKey = this._keys[key];
  30380. var startValue = this._getKeyValue(startKey.value);
  30381. var endValue = this._getKeyValue(endKey.value);
  30382. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  30383. var frameDelta = endKey.frame - startKey.frame;
  30384. // gradient : percent of currentFrame between the frame inf and the frame sup
  30385. var gradient = (currentFrame - startKey.frame) / frameDelta;
  30386. // check for easingFunction and correction of gradient
  30387. if (this._easingFunction != null) {
  30388. gradient = this._easingFunction.ease(gradient);
  30389. }
  30390. switch (this.dataType) {
  30391. // Float
  30392. case Animation.ANIMATIONTYPE_FLOAT:
  30393. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  30394. switch (loopMode) {
  30395. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30396. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30397. return floatValue;
  30398. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30399. return offsetValue * repeatCount + floatValue;
  30400. }
  30401. break;
  30402. // Quaternion
  30403. case Animation.ANIMATIONTYPE_QUATERNION:
  30404. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30405. switch (loopMode) {
  30406. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30407. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30408. return quatValue;
  30409. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30410. return quatValue.add(offsetValue.scale(repeatCount));
  30411. }
  30412. return quatValue;
  30413. // Vector3
  30414. case Animation.ANIMATIONTYPE_VECTOR3:
  30415. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  30416. switch (loopMode) {
  30417. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30418. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30419. return vec3Value;
  30420. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30421. return vec3Value.add(offsetValue.scale(repeatCount));
  30422. }
  30423. // Vector2
  30424. case Animation.ANIMATIONTYPE_VECTOR2:
  30425. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  30426. switch (loopMode) {
  30427. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30428. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30429. return vec2Value;
  30430. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30431. return vec2Value.add(offsetValue.scale(repeatCount));
  30432. }
  30433. // Size
  30434. case Animation.ANIMATIONTYPE_SIZE:
  30435. switch (loopMode) {
  30436. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30437. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30438. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30439. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30440. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30441. }
  30442. // Color3
  30443. case Animation.ANIMATIONTYPE_COLOR3:
  30444. switch (loopMode) {
  30445. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30446. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30447. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30448. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30449. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30450. }
  30451. // Matrix
  30452. case Animation.ANIMATIONTYPE_MATRIX:
  30453. switch (loopMode) {
  30454. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30455. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30456. if (this.allowMatricesInterpolation) {
  30457. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30458. }
  30459. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30460. return startValue;
  30461. }
  30462. default:
  30463. break;
  30464. }
  30465. break;
  30466. }
  30467. }
  30468. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30469. };
  30470. Animation.prototype.setValue = function (currentValue, blend) {
  30471. if (blend === void 0) { blend = false; }
  30472. // Set value
  30473. var path;
  30474. var destination;
  30475. if (this.targetPropertyPath.length > 1) {
  30476. var property = this._target[this.targetPropertyPath[0]];
  30477. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30478. property = property[this.targetPropertyPath[index]];
  30479. }
  30480. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30481. destination = property;
  30482. }
  30483. else {
  30484. path = this.targetPropertyPath[0];
  30485. destination = this._target;
  30486. }
  30487. // Blending
  30488. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30489. if (!this._originalBlendValue) {
  30490. if (destination[path].clone) {
  30491. this._originalBlendValue = destination[path].clone();
  30492. }
  30493. else {
  30494. this._originalBlendValue = destination[path];
  30495. }
  30496. }
  30497. if (this._originalBlendValue.prototype) {
  30498. if (this._originalBlendValue.prototype.Lerp) {
  30499. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30500. }
  30501. else {
  30502. destination[path] = currentValue;
  30503. }
  30504. }
  30505. else if (this._originalBlendValue.m) {
  30506. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30507. }
  30508. else {
  30509. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30510. }
  30511. this._blendingFactor += this.blendingSpeed;
  30512. }
  30513. else {
  30514. destination[path] = currentValue;
  30515. }
  30516. if (this._target.markAsDirty) {
  30517. this._target.markAsDirty(this.targetProperty);
  30518. }
  30519. };
  30520. Animation.prototype.goToFrame = function (frame) {
  30521. if (frame < this._keys[0].frame) {
  30522. frame = this._keys[0].frame;
  30523. }
  30524. else if (frame > this._keys[this._keys.length - 1].frame) {
  30525. frame = this._keys[this._keys.length - 1].frame;
  30526. }
  30527. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30528. this.setValue(currentValue);
  30529. };
  30530. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30531. if (blend === void 0) { blend = false; }
  30532. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30533. this._stopped = true;
  30534. return false;
  30535. }
  30536. var returnValue = true;
  30537. // Adding a start key at frame 0 if missing
  30538. if (this._keys[0].frame !== 0) {
  30539. var newKey = { frame: 0, value: this._keys[0].value };
  30540. this._keys.splice(0, 0, newKey);
  30541. }
  30542. // Check limits
  30543. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30544. from = this._keys[0].frame;
  30545. }
  30546. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30547. to = this._keys[this._keys.length - 1].frame;
  30548. }
  30549. //to and from cannot be the same key
  30550. if (from === to) {
  30551. from++;
  30552. }
  30553. // Compute ratio
  30554. var range = to - from;
  30555. var offsetValue;
  30556. // ratio represents the frame delta between from and to
  30557. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30558. var highLimitValue = 0;
  30559. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  30560. returnValue = false;
  30561. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30562. }
  30563. else {
  30564. // Get max value if required
  30565. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30566. var keyOffset = to.toString() + from.toString();
  30567. if (!this._offsetsCache[keyOffset]) {
  30568. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30569. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30570. switch (this.dataType) {
  30571. // Float
  30572. case Animation.ANIMATIONTYPE_FLOAT:
  30573. this._offsetsCache[keyOffset] = toValue - fromValue;
  30574. break;
  30575. // Quaternion
  30576. case Animation.ANIMATIONTYPE_QUATERNION:
  30577. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30578. break;
  30579. // Vector3
  30580. case Animation.ANIMATIONTYPE_VECTOR3:
  30581. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30582. // Vector2
  30583. case Animation.ANIMATIONTYPE_VECTOR2:
  30584. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30585. // Size
  30586. case Animation.ANIMATIONTYPE_SIZE:
  30587. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30588. // Color3
  30589. case Animation.ANIMATIONTYPE_COLOR3:
  30590. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30591. default:
  30592. break;
  30593. }
  30594. this._highLimitsCache[keyOffset] = toValue;
  30595. }
  30596. highLimitValue = this._highLimitsCache[keyOffset];
  30597. offsetValue = this._offsetsCache[keyOffset];
  30598. }
  30599. }
  30600. if (offsetValue === undefined) {
  30601. switch (this.dataType) {
  30602. // Float
  30603. case Animation.ANIMATIONTYPE_FLOAT:
  30604. offsetValue = 0;
  30605. break;
  30606. // Quaternion
  30607. case Animation.ANIMATIONTYPE_QUATERNION:
  30608. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30609. break;
  30610. // Vector3
  30611. case Animation.ANIMATIONTYPE_VECTOR3:
  30612. offsetValue = BABYLON.Vector3.Zero();
  30613. break;
  30614. // Vector2
  30615. case Animation.ANIMATIONTYPE_VECTOR2:
  30616. offsetValue = BABYLON.Vector2.Zero();
  30617. break;
  30618. // Size
  30619. case Animation.ANIMATIONTYPE_SIZE:
  30620. offsetValue = BABYLON.Size.Zero();
  30621. break;
  30622. // Color3
  30623. case Animation.ANIMATIONTYPE_COLOR3:
  30624. offsetValue = BABYLON.Color3.Black();
  30625. }
  30626. }
  30627. // Compute value
  30628. var repeatCount = (ratio / range) >> 0;
  30629. var currentFrame = returnValue ? from + ratio % range : to;
  30630. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30631. // Set value
  30632. this.setValue(currentValue);
  30633. // Check events
  30634. for (var index = 0; index < this._events.length; index++) {
  30635. // Make sure current frame has passed event frame and that event frame is within the current range
  30636. // Also, handle both forward and reverse animations
  30637. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  30638. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  30639. var event = this._events[index];
  30640. if (!event.isDone) {
  30641. // If event should be done only once, remove it.
  30642. if (event.onlyOnce) {
  30643. this._events.splice(index, 1);
  30644. index--;
  30645. }
  30646. event.isDone = true;
  30647. event.action();
  30648. } // Don't do anything if the event has already be done.
  30649. }
  30650. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30651. // reset event, the animation is looping
  30652. this._events[index].isDone = false;
  30653. }
  30654. }
  30655. if (!returnValue) {
  30656. this._stopped = true;
  30657. }
  30658. return returnValue;
  30659. };
  30660. Animation.prototype.serialize = function () {
  30661. var serializationObject = {};
  30662. serializationObject.name = this.name;
  30663. serializationObject.property = this.targetProperty;
  30664. serializationObject.framePerSecond = this.framePerSecond;
  30665. serializationObject.dataType = this.dataType;
  30666. serializationObject.loopBehavior = this.loopMode;
  30667. serializationObject.enableBlending = this.enableBlending;
  30668. serializationObject.blendingSpeed = this.blendingSpeed;
  30669. var dataType = this.dataType;
  30670. serializationObject.keys = [];
  30671. var keys = this.getKeys();
  30672. for (var index = 0; index < keys.length; index++) {
  30673. var animationKey = keys[index];
  30674. var key = {};
  30675. key.frame = animationKey.frame;
  30676. switch (dataType) {
  30677. case Animation.ANIMATIONTYPE_FLOAT:
  30678. key.values = [animationKey.value];
  30679. break;
  30680. case Animation.ANIMATIONTYPE_QUATERNION:
  30681. case Animation.ANIMATIONTYPE_MATRIX:
  30682. case Animation.ANIMATIONTYPE_VECTOR3:
  30683. case Animation.ANIMATIONTYPE_COLOR3:
  30684. key.values = animationKey.value.asArray();
  30685. break;
  30686. }
  30687. serializationObject.keys.push(key);
  30688. }
  30689. serializationObject.ranges = [];
  30690. for (var name in this._ranges) {
  30691. var range = {};
  30692. range.name = name;
  30693. range.from = this._ranges[name].from;
  30694. range.to = this._ranges[name].to;
  30695. serializationObject.ranges.push(range);
  30696. }
  30697. return serializationObject;
  30698. };
  30699. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30700. get: function () {
  30701. return Animation._ANIMATIONTYPE_FLOAT;
  30702. },
  30703. enumerable: true,
  30704. configurable: true
  30705. });
  30706. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30707. get: function () {
  30708. return Animation._ANIMATIONTYPE_VECTOR3;
  30709. },
  30710. enumerable: true,
  30711. configurable: true
  30712. });
  30713. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30714. get: function () {
  30715. return Animation._ANIMATIONTYPE_VECTOR2;
  30716. },
  30717. enumerable: true,
  30718. configurable: true
  30719. });
  30720. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30721. get: function () {
  30722. return Animation._ANIMATIONTYPE_SIZE;
  30723. },
  30724. enumerable: true,
  30725. configurable: true
  30726. });
  30727. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30728. get: function () {
  30729. return Animation._ANIMATIONTYPE_QUATERNION;
  30730. },
  30731. enumerable: true,
  30732. configurable: true
  30733. });
  30734. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30735. get: function () {
  30736. return Animation._ANIMATIONTYPE_MATRIX;
  30737. },
  30738. enumerable: true,
  30739. configurable: true
  30740. });
  30741. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30742. get: function () {
  30743. return Animation._ANIMATIONTYPE_COLOR3;
  30744. },
  30745. enumerable: true,
  30746. configurable: true
  30747. });
  30748. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30749. get: function () {
  30750. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30751. },
  30752. enumerable: true,
  30753. configurable: true
  30754. });
  30755. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30756. get: function () {
  30757. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30758. },
  30759. enumerable: true,
  30760. configurable: true
  30761. });
  30762. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30763. get: function () {
  30764. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30765. },
  30766. enumerable: true,
  30767. configurable: true
  30768. });
  30769. Animation.Parse = function (parsedAnimation) {
  30770. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30771. var dataType = parsedAnimation.dataType;
  30772. var keys = [];
  30773. var data;
  30774. var index;
  30775. if (parsedAnimation.enableBlending) {
  30776. animation.enableBlending = parsedAnimation.enableBlending;
  30777. }
  30778. if (parsedAnimation.blendingSpeed) {
  30779. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30780. }
  30781. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30782. var key = parsedAnimation.keys[index];
  30783. switch (dataType) {
  30784. case Animation.ANIMATIONTYPE_FLOAT:
  30785. data = key.values[0];
  30786. break;
  30787. case Animation.ANIMATIONTYPE_QUATERNION:
  30788. data = BABYLON.Quaternion.FromArray(key.values);
  30789. break;
  30790. case Animation.ANIMATIONTYPE_MATRIX:
  30791. data = BABYLON.Matrix.FromArray(key.values);
  30792. break;
  30793. case Animation.ANIMATIONTYPE_COLOR3:
  30794. data = BABYLON.Color3.FromArray(key.values);
  30795. break;
  30796. case Animation.ANIMATIONTYPE_VECTOR3:
  30797. default:
  30798. data = BABYLON.Vector3.FromArray(key.values);
  30799. break;
  30800. }
  30801. keys.push({
  30802. frame: key.frame,
  30803. value: data
  30804. });
  30805. }
  30806. animation.setKeys(keys);
  30807. if (parsedAnimation.ranges) {
  30808. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30809. data = parsedAnimation.ranges[index];
  30810. animation.createRange(data.name, data.from, data.to);
  30811. }
  30812. }
  30813. return animation;
  30814. };
  30815. Animation.AppendSerializedAnimations = function (source, destination) {
  30816. if (source.animations) {
  30817. destination.animations = [];
  30818. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30819. var animation = source.animations[animationIndex];
  30820. destination.animations.push(animation.serialize());
  30821. }
  30822. }
  30823. };
  30824. // Statics
  30825. Animation._ANIMATIONTYPE_FLOAT = 0;
  30826. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  30827. Animation._ANIMATIONTYPE_QUATERNION = 2;
  30828. Animation._ANIMATIONTYPE_MATRIX = 3;
  30829. Animation._ANIMATIONTYPE_COLOR3 = 4;
  30830. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  30831. Animation._ANIMATIONTYPE_SIZE = 6;
  30832. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  30833. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  30834. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  30835. return Animation;
  30836. }());
  30837. BABYLON.Animation = Animation;
  30838. })(BABYLON || (BABYLON = {}));
  30839. //# sourceMappingURL=babylon.animation.js.map
  30840. var BABYLON;
  30841. (function (BABYLON) {
  30842. var Animatable = (function () {
  30843. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  30844. if (fromFrame === void 0) { fromFrame = 0; }
  30845. if (toFrame === void 0) { toFrame = 100; }
  30846. if (loopAnimation === void 0) { loopAnimation = false; }
  30847. if (speedRatio === void 0) { speedRatio = 1.0; }
  30848. this.target = target;
  30849. this.fromFrame = fromFrame;
  30850. this.toFrame = toFrame;
  30851. this.loopAnimation = loopAnimation;
  30852. this.speedRatio = speedRatio;
  30853. this.onAnimationEnd = onAnimationEnd;
  30854. this._localDelayOffset = null;
  30855. this._pausedDelay = null;
  30856. this._animations = new Array();
  30857. this._paused = false;
  30858. this.animationStarted = false;
  30859. if (animations) {
  30860. this.appendAnimations(target, animations);
  30861. }
  30862. this._scene = scene;
  30863. scene._activeAnimatables.push(this);
  30864. }
  30865. // Methods
  30866. Animatable.prototype.getAnimations = function () {
  30867. return this._animations;
  30868. };
  30869. Animatable.prototype.appendAnimations = function (target, animations) {
  30870. for (var index = 0; index < animations.length; index++) {
  30871. var animation = animations[index];
  30872. animation._target = target;
  30873. this._animations.push(animation);
  30874. }
  30875. };
  30876. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  30877. var animations = this._animations;
  30878. for (var index = 0; index < animations.length; index++) {
  30879. if (animations[index].targetProperty === property) {
  30880. return animations[index];
  30881. }
  30882. }
  30883. return null;
  30884. };
  30885. Animatable.prototype.reset = function () {
  30886. var animations = this._animations;
  30887. for (var index = 0; index < animations.length; index++) {
  30888. animations[index].reset();
  30889. }
  30890. this._localDelayOffset = null;
  30891. this._pausedDelay = null;
  30892. };
  30893. Animatable.prototype.enableBlending = function (blendingSpeed) {
  30894. var animations = this._animations;
  30895. for (var index = 0; index < animations.length; index++) {
  30896. animations[index].enableBlending = true;
  30897. animations[index].blendingSpeed = blendingSpeed;
  30898. }
  30899. };
  30900. Animatable.prototype.disableBlending = function () {
  30901. var animations = this._animations;
  30902. for (var index = 0; index < animations.length; index++) {
  30903. animations[index].enableBlending = false;
  30904. }
  30905. };
  30906. Animatable.prototype.goToFrame = function (frame) {
  30907. var animations = this._animations;
  30908. if (animations[0]) {
  30909. var fps = animations[0].framePerSecond;
  30910. var currentFrame = animations[0].currentFrame;
  30911. var adjustTime = frame - currentFrame;
  30912. var delay = adjustTime * 1000 / fps;
  30913. this._localDelayOffset -= delay;
  30914. }
  30915. for (var index = 0; index < animations.length; index++) {
  30916. animations[index].goToFrame(frame);
  30917. }
  30918. };
  30919. Animatable.prototype.pause = function () {
  30920. if (this._paused) {
  30921. return;
  30922. }
  30923. this._paused = true;
  30924. };
  30925. Animatable.prototype.restart = function () {
  30926. this._paused = false;
  30927. };
  30928. Animatable.prototype.stop = function (animationName) {
  30929. if (animationName) {
  30930. var idx = this._scene._activeAnimatables.indexOf(this);
  30931. if (idx > -1) {
  30932. var animations = this._animations;
  30933. for (var index = animations.length - 1; index >= 0; index--) {
  30934. if (typeof animationName === "string" && animations[index].name != animationName) {
  30935. continue;
  30936. }
  30937. animations[index].reset();
  30938. animations.splice(index, 1);
  30939. }
  30940. if (animations.length == 0) {
  30941. this._scene._activeAnimatables.splice(idx, 1);
  30942. if (this.onAnimationEnd) {
  30943. this.onAnimationEnd();
  30944. }
  30945. }
  30946. }
  30947. }
  30948. else {
  30949. var index = this._scene._activeAnimatables.indexOf(this);
  30950. if (index > -1) {
  30951. this._scene._activeAnimatables.splice(index, 1);
  30952. var animations = this._animations;
  30953. for (var index = 0; index < animations.length; index++) {
  30954. animations[index].reset();
  30955. }
  30956. if (this.onAnimationEnd) {
  30957. this.onAnimationEnd();
  30958. }
  30959. }
  30960. }
  30961. };
  30962. Animatable.prototype._animate = function (delay) {
  30963. if (this._paused) {
  30964. this.animationStarted = false;
  30965. if (this._pausedDelay === null) {
  30966. this._pausedDelay = delay;
  30967. }
  30968. return true;
  30969. }
  30970. if (this._localDelayOffset === null) {
  30971. this._localDelayOffset = delay;
  30972. }
  30973. else if (this._pausedDelay !== null) {
  30974. this._localDelayOffset += delay - this._pausedDelay;
  30975. this._pausedDelay = null;
  30976. }
  30977. // Animating
  30978. var running = false;
  30979. var animations = this._animations;
  30980. var index;
  30981. for (index = 0; index < animations.length; index++) {
  30982. var animation = animations[index];
  30983. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  30984. running = running || isRunning;
  30985. }
  30986. this.animationStarted = running;
  30987. if (!running) {
  30988. // Remove from active animatables
  30989. index = this._scene._activeAnimatables.indexOf(this);
  30990. this._scene._activeAnimatables.splice(index, 1);
  30991. }
  30992. if (!running && this.onAnimationEnd) {
  30993. this.onAnimationEnd();
  30994. this.onAnimationEnd = null;
  30995. }
  30996. return running;
  30997. };
  30998. return Animatable;
  30999. }());
  31000. BABYLON.Animatable = Animatable;
  31001. })(BABYLON || (BABYLON = {}));
  31002. //# sourceMappingURL=babylon.animatable.js.map
  31003. var BABYLON;
  31004. (function (BABYLON) {
  31005. var EasingFunction = (function () {
  31006. function EasingFunction() {
  31007. // Properties
  31008. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  31009. }
  31010. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  31011. get: function () {
  31012. return EasingFunction._EASINGMODE_EASEIN;
  31013. },
  31014. enumerable: true,
  31015. configurable: true
  31016. });
  31017. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  31018. get: function () {
  31019. return EasingFunction._EASINGMODE_EASEOUT;
  31020. },
  31021. enumerable: true,
  31022. configurable: true
  31023. });
  31024. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  31025. get: function () {
  31026. return EasingFunction._EASINGMODE_EASEINOUT;
  31027. },
  31028. enumerable: true,
  31029. configurable: true
  31030. });
  31031. EasingFunction.prototype.setEasingMode = function (easingMode) {
  31032. var n = Math.min(Math.max(easingMode, 0), 2);
  31033. this._easingMode = n;
  31034. };
  31035. EasingFunction.prototype.getEasingMode = function () {
  31036. return this._easingMode;
  31037. };
  31038. EasingFunction.prototype.easeInCore = function (gradient) {
  31039. throw new Error('You must implement this method');
  31040. };
  31041. EasingFunction.prototype.ease = function (gradient) {
  31042. switch (this._easingMode) {
  31043. case EasingFunction.EASINGMODE_EASEIN:
  31044. return this.easeInCore(gradient);
  31045. case EasingFunction.EASINGMODE_EASEOUT:
  31046. return (1 - this.easeInCore(1 - gradient));
  31047. }
  31048. if (gradient >= 0.5) {
  31049. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  31050. }
  31051. return (this.easeInCore(gradient * 2) * 0.5);
  31052. };
  31053. //Statics
  31054. EasingFunction._EASINGMODE_EASEIN = 0;
  31055. EasingFunction._EASINGMODE_EASEOUT = 1;
  31056. EasingFunction._EASINGMODE_EASEINOUT = 2;
  31057. return EasingFunction;
  31058. }());
  31059. BABYLON.EasingFunction = EasingFunction;
  31060. var CircleEase = (function (_super) {
  31061. __extends(CircleEase, _super);
  31062. function CircleEase() {
  31063. return _super !== null && _super.apply(this, arguments) || this;
  31064. }
  31065. CircleEase.prototype.easeInCore = function (gradient) {
  31066. gradient = Math.max(0, Math.min(1, gradient));
  31067. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  31068. };
  31069. return CircleEase;
  31070. }(EasingFunction));
  31071. BABYLON.CircleEase = CircleEase;
  31072. var BackEase = (function (_super) {
  31073. __extends(BackEase, _super);
  31074. function BackEase(amplitude) {
  31075. if (amplitude === void 0) { amplitude = 1; }
  31076. var _this = _super.call(this) || this;
  31077. _this.amplitude = amplitude;
  31078. return _this;
  31079. }
  31080. BackEase.prototype.easeInCore = function (gradient) {
  31081. var num = Math.max(0, this.amplitude);
  31082. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  31083. };
  31084. return BackEase;
  31085. }(EasingFunction));
  31086. BABYLON.BackEase = BackEase;
  31087. var BounceEase = (function (_super) {
  31088. __extends(BounceEase, _super);
  31089. function BounceEase(bounces, bounciness) {
  31090. if (bounces === void 0) { bounces = 3; }
  31091. if (bounciness === void 0) { bounciness = 2; }
  31092. var _this = _super.call(this) || this;
  31093. _this.bounces = bounces;
  31094. _this.bounciness = bounciness;
  31095. return _this;
  31096. }
  31097. BounceEase.prototype.easeInCore = function (gradient) {
  31098. var y = Math.max(0.0, this.bounces);
  31099. var bounciness = this.bounciness;
  31100. if (bounciness <= 1.0) {
  31101. bounciness = 1.001;
  31102. }
  31103. var num9 = Math.pow(bounciness, y);
  31104. var num5 = 1.0 - bounciness;
  31105. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  31106. var num15 = gradient * num4;
  31107. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  31108. var num3 = Math.floor(num65);
  31109. var num13 = num3 + 1.0;
  31110. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  31111. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  31112. var num7 = (num8 + num12) * 0.5;
  31113. var num6 = gradient - num7;
  31114. var num2 = num7 - num8;
  31115. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  31116. };
  31117. return BounceEase;
  31118. }(EasingFunction));
  31119. BABYLON.BounceEase = BounceEase;
  31120. var CubicEase = (function (_super) {
  31121. __extends(CubicEase, _super);
  31122. function CubicEase() {
  31123. return _super !== null && _super.apply(this, arguments) || this;
  31124. }
  31125. CubicEase.prototype.easeInCore = function (gradient) {
  31126. return (gradient * gradient * gradient);
  31127. };
  31128. return CubicEase;
  31129. }(EasingFunction));
  31130. BABYLON.CubicEase = CubicEase;
  31131. var ElasticEase = (function (_super) {
  31132. __extends(ElasticEase, _super);
  31133. function ElasticEase(oscillations, springiness) {
  31134. if (oscillations === void 0) { oscillations = 3; }
  31135. if (springiness === void 0) { springiness = 3; }
  31136. var _this = _super.call(this) || this;
  31137. _this.oscillations = oscillations;
  31138. _this.springiness = springiness;
  31139. return _this;
  31140. }
  31141. ElasticEase.prototype.easeInCore = function (gradient) {
  31142. var num2;
  31143. var num3 = Math.max(0.0, this.oscillations);
  31144. var num = Math.max(0.0, this.springiness);
  31145. if (num == 0) {
  31146. num2 = gradient;
  31147. }
  31148. else {
  31149. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  31150. }
  31151. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  31152. };
  31153. return ElasticEase;
  31154. }(EasingFunction));
  31155. BABYLON.ElasticEase = ElasticEase;
  31156. var ExponentialEase = (function (_super) {
  31157. __extends(ExponentialEase, _super);
  31158. function ExponentialEase(exponent) {
  31159. if (exponent === void 0) { exponent = 2; }
  31160. var _this = _super.call(this) || this;
  31161. _this.exponent = exponent;
  31162. return _this;
  31163. }
  31164. ExponentialEase.prototype.easeInCore = function (gradient) {
  31165. if (this.exponent <= 0) {
  31166. return gradient;
  31167. }
  31168. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  31169. };
  31170. return ExponentialEase;
  31171. }(EasingFunction));
  31172. BABYLON.ExponentialEase = ExponentialEase;
  31173. var PowerEase = (function (_super) {
  31174. __extends(PowerEase, _super);
  31175. function PowerEase(power) {
  31176. if (power === void 0) { power = 2; }
  31177. var _this = _super.call(this) || this;
  31178. _this.power = power;
  31179. return _this;
  31180. }
  31181. PowerEase.prototype.easeInCore = function (gradient) {
  31182. var y = Math.max(0.0, this.power);
  31183. return Math.pow(gradient, y);
  31184. };
  31185. return PowerEase;
  31186. }(EasingFunction));
  31187. BABYLON.PowerEase = PowerEase;
  31188. var QuadraticEase = (function (_super) {
  31189. __extends(QuadraticEase, _super);
  31190. function QuadraticEase() {
  31191. return _super !== null && _super.apply(this, arguments) || this;
  31192. }
  31193. QuadraticEase.prototype.easeInCore = function (gradient) {
  31194. return (gradient * gradient);
  31195. };
  31196. return QuadraticEase;
  31197. }(EasingFunction));
  31198. BABYLON.QuadraticEase = QuadraticEase;
  31199. var QuarticEase = (function (_super) {
  31200. __extends(QuarticEase, _super);
  31201. function QuarticEase() {
  31202. return _super !== null && _super.apply(this, arguments) || this;
  31203. }
  31204. QuarticEase.prototype.easeInCore = function (gradient) {
  31205. return (gradient * gradient * gradient * gradient);
  31206. };
  31207. return QuarticEase;
  31208. }(EasingFunction));
  31209. BABYLON.QuarticEase = QuarticEase;
  31210. var QuinticEase = (function (_super) {
  31211. __extends(QuinticEase, _super);
  31212. function QuinticEase() {
  31213. return _super !== null && _super.apply(this, arguments) || this;
  31214. }
  31215. QuinticEase.prototype.easeInCore = function (gradient) {
  31216. return (gradient * gradient * gradient * gradient * gradient);
  31217. };
  31218. return QuinticEase;
  31219. }(EasingFunction));
  31220. BABYLON.QuinticEase = QuinticEase;
  31221. var SineEase = (function (_super) {
  31222. __extends(SineEase, _super);
  31223. function SineEase() {
  31224. return _super !== null && _super.apply(this, arguments) || this;
  31225. }
  31226. SineEase.prototype.easeInCore = function (gradient) {
  31227. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  31228. };
  31229. return SineEase;
  31230. }(EasingFunction));
  31231. BABYLON.SineEase = SineEase;
  31232. var BezierCurveEase = (function (_super) {
  31233. __extends(BezierCurveEase, _super);
  31234. function BezierCurveEase(x1, y1, x2, y2) {
  31235. if (x1 === void 0) { x1 = 0; }
  31236. if (y1 === void 0) { y1 = 0; }
  31237. if (x2 === void 0) { x2 = 1; }
  31238. if (y2 === void 0) { y2 = 1; }
  31239. var _this = _super.call(this) || this;
  31240. _this.x1 = x1;
  31241. _this.y1 = y1;
  31242. _this.x2 = x2;
  31243. _this.y2 = y2;
  31244. return _this;
  31245. }
  31246. BezierCurveEase.prototype.easeInCore = function (gradient) {
  31247. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  31248. };
  31249. return BezierCurveEase;
  31250. }(EasingFunction));
  31251. BABYLON.BezierCurveEase = BezierCurveEase;
  31252. })(BABYLON || (BABYLON = {}));
  31253. //# sourceMappingURL=babylon.easing.js.map
  31254. var BABYLON;
  31255. (function (BABYLON) {
  31256. BABYLON.CameraInputTypes = {};
  31257. var CameraInputsManager = (function () {
  31258. function CameraInputsManager(camera) {
  31259. this.attached = {};
  31260. this.camera = camera;
  31261. this.checkInputs = function () { };
  31262. }
  31263. CameraInputsManager.prototype.add = function (input) {
  31264. var type = input.getSimpleName();
  31265. if (this.attached[type]) {
  31266. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  31267. return;
  31268. }
  31269. this.attached[type] = input;
  31270. input.camera = this.camera;
  31271. //for checkInputs, we are dynamically creating a function
  31272. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  31273. if (input.checkInputs) {
  31274. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31275. }
  31276. if (this.attachedElement) {
  31277. input.attachControl(this.attachedElement);
  31278. }
  31279. };
  31280. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31281. for (var cam in this.attached) {
  31282. var input = this.attached[cam];
  31283. if (input === inputToRemove) {
  31284. input.detachControl(this.attachedElement);
  31285. input.camera = null;
  31286. delete this.attached[cam];
  31287. this.rebuildInputCheck();
  31288. }
  31289. }
  31290. };
  31291. CameraInputsManager.prototype.removeByType = function (inputType) {
  31292. for (var cam in this.attached) {
  31293. var input = this.attached[cam];
  31294. if (input.getClassName() === inputType) {
  31295. input.detachControl(this.attachedElement);
  31296. input.camera = null;
  31297. delete this.attached[cam];
  31298. this.rebuildInputCheck();
  31299. }
  31300. }
  31301. };
  31302. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31303. var current = this.checkInputs;
  31304. return function () {
  31305. current();
  31306. fn();
  31307. };
  31308. };
  31309. CameraInputsManager.prototype.attachInput = function (input) {
  31310. input.attachControl(this.attachedElement, this.noPreventDefault);
  31311. };
  31312. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31313. if (this.attachedElement) {
  31314. return;
  31315. }
  31316. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31317. this.attachedElement = element;
  31318. this.noPreventDefault = noPreventDefault;
  31319. for (var cam in this.attached) {
  31320. var input = this.attached[cam];
  31321. this.attached[cam].attachControl(element, noPreventDefault);
  31322. }
  31323. };
  31324. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  31325. if (disconnect === void 0) { disconnect = false; }
  31326. if (this.attachedElement !== element) {
  31327. return;
  31328. }
  31329. for (var cam in this.attached) {
  31330. var input = this.attached[cam];
  31331. this.attached[cam].detachControl(element);
  31332. if (disconnect) {
  31333. this.attached[cam].camera = null;
  31334. }
  31335. }
  31336. this.attachedElement = null;
  31337. };
  31338. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31339. this.checkInputs = function () { };
  31340. for (var cam in this.attached) {
  31341. var input = this.attached[cam];
  31342. if (input.checkInputs) {
  31343. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31344. }
  31345. }
  31346. };
  31347. CameraInputsManager.prototype.clear = function () {
  31348. if (this.attachedElement) {
  31349. this.detachElement(this.attachedElement, true);
  31350. }
  31351. this.attached = {};
  31352. this.attachedElement = null;
  31353. this.checkInputs = function () { };
  31354. };
  31355. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31356. var inputs = {};
  31357. for (var cam in this.attached) {
  31358. var input = this.attached[cam];
  31359. var res = BABYLON.SerializationHelper.Serialize(input);
  31360. inputs[input.getClassName()] = res;
  31361. }
  31362. serializedCamera.inputsmgr = inputs;
  31363. };
  31364. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31365. var parsedInputs = parsedCamera.inputsmgr;
  31366. if (parsedInputs) {
  31367. this.clear();
  31368. for (var n in parsedInputs) {
  31369. var construct = BABYLON.CameraInputTypes[n];
  31370. if (construct) {
  31371. var parsedinput = parsedInputs[n];
  31372. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31373. this.add(input);
  31374. }
  31375. }
  31376. }
  31377. else {
  31378. //2016-03-08 this part is for managing backward compatibility
  31379. for (var n in this.attached) {
  31380. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  31381. if (construct) {
  31382. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31383. this.remove(this.attached[n]);
  31384. this.add(input);
  31385. }
  31386. }
  31387. }
  31388. };
  31389. return CameraInputsManager;
  31390. }());
  31391. BABYLON.CameraInputsManager = CameraInputsManager;
  31392. })(BABYLON || (BABYLON = {}));
  31393. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31394. /// <reference path="babylon.camera.ts" />
  31395. var BABYLON;
  31396. (function (BABYLON) {
  31397. var TargetCamera = (function (_super) {
  31398. __extends(TargetCamera, _super);
  31399. function TargetCamera(name, position, scene) {
  31400. var _this = _super.call(this, name, position, scene) || this;
  31401. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  31402. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  31403. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  31404. _this.speed = 2.0;
  31405. _this.noRotationConstraint = false;
  31406. _this.lockedTarget = null;
  31407. _this._currentTarget = BABYLON.Vector3.Zero();
  31408. _this._viewMatrix = BABYLON.Matrix.Zero();
  31409. _this._camMatrix = BABYLON.Matrix.Zero();
  31410. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  31411. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  31412. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  31413. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  31414. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  31415. _this._lookAtTemp = BABYLON.Matrix.Zero();
  31416. _this._tempMatrix = BABYLON.Matrix.Zero();
  31417. return _this;
  31418. }
  31419. TargetCamera.prototype.getFrontPosition = function (distance) {
  31420. var direction = this.getTarget().subtract(this.position);
  31421. direction.normalize();
  31422. direction.scaleInPlace(distance);
  31423. return this.globalPosition.add(direction);
  31424. };
  31425. TargetCamera.prototype._getLockedTargetPosition = function () {
  31426. if (!this.lockedTarget) {
  31427. return null;
  31428. }
  31429. if (this.lockedTarget.absolutePosition) {
  31430. this.lockedTarget.computeWorldMatrix();
  31431. }
  31432. return this.lockedTarget.absolutePosition || this.lockedTarget;
  31433. };
  31434. // Cache
  31435. TargetCamera.prototype._initCache = function () {
  31436. _super.prototype._initCache.call(this);
  31437. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31438. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31439. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31440. };
  31441. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31442. if (!ignoreParentClass) {
  31443. _super.prototype._updateCache.call(this);
  31444. }
  31445. var lockedTargetPosition = this._getLockedTargetPosition();
  31446. if (!lockedTargetPosition) {
  31447. this._cache.lockedTarget = null;
  31448. }
  31449. else {
  31450. if (!this._cache.lockedTarget) {
  31451. this._cache.lockedTarget = lockedTargetPosition.clone();
  31452. }
  31453. else {
  31454. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31455. }
  31456. }
  31457. this._cache.rotation.copyFrom(this.rotation);
  31458. if (this.rotationQuaternion)
  31459. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31460. };
  31461. // Synchronized
  31462. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31463. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31464. return false;
  31465. }
  31466. var lockedTargetPosition = this._getLockedTargetPosition();
  31467. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31468. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31469. };
  31470. // Methods
  31471. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31472. var engine = this.getEngine();
  31473. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31474. };
  31475. // Target
  31476. TargetCamera.prototype.setTarget = function (target) {
  31477. this.upVector.normalize();
  31478. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31479. this._camMatrix.invert();
  31480. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31481. var vDir = target.subtract(this.position);
  31482. if (vDir.x >= 0.0) {
  31483. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31484. }
  31485. else {
  31486. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31487. }
  31488. this.rotation.z = 0;
  31489. if (isNaN(this.rotation.x)) {
  31490. this.rotation.x = 0;
  31491. }
  31492. if (isNaN(this.rotation.y)) {
  31493. this.rotation.y = 0;
  31494. }
  31495. if (isNaN(this.rotation.z)) {
  31496. this.rotation.z = 0;
  31497. }
  31498. if (this.rotationQuaternion) {
  31499. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31500. }
  31501. };
  31502. /**
  31503. * Return the current target position of the camera. This value is expressed in local space.
  31504. */
  31505. TargetCamera.prototype.getTarget = function () {
  31506. return this._currentTarget;
  31507. };
  31508. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31509. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31510. };
  31511. TargetCamera.prototype._updatePosition = function () {
  31512. if (this.parent) {
  31513. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31514. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31515. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31516. return;
  31517. }
  31518. this.position.addInPlace(this.cameraDirection);
  31519. };
  31520. TargetCamera.prototype._checkInputs = function () {
  31521. var needToMove = this._decideIfNeedsToMove();
  31522. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31523. // Move
  31524. if (needToMove) {
  31525. this._updatePosition();
  31526. }
  31527. // Rotate
  31528. if (needToRotate) {
  31529. this.rotation.x += this.cameraRotation.x;
  31530. this.rotation.y += this.cameraRotation.y;
  31531. //rotate, if quaternion is set and rotation was used
  31532. if (this.rotationQuaternion) {
  31533. var len = this.rotation.lengthSquared();
  31534. if (len) {
  31535. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31536. }
  31537. }
  31538. if (!this.noRotationConstraint) {
  31539. var limit = (Math.PI / 2) * 0.95;
  31540. if (this.rotation.x > limit)
  31541. this.rotation.x = limit;
  31542. if (this.rotation.x < -limit)
  31543. this.rotation.x = -limit;
  31544. }
  31545. }
  31546. // Inertia
  31547. if (needToMove) {
  31548. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31549. this.cameraDirection.x = 0;
  31550. }
  31551. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31552. this.cameraDirection.y = 0;
  31553. }
  31554. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31555. this.cameraDirection.z = 0;
  31556. }
  31557. this.cameraDirection.scaleInPlace(this.inertia);
  31558. }
  31559. if (needToRotate) {
  31560. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31561. this.cameraRotation.x = 0;
  31562. }
  31563. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31564. this.cameraRotation.y = 0;
  31565. }
  31566. this.cameraRotation.scaleInPlace(this.inertia);
  31567. }
  31568. _super.prototype._checkInputs.call(this);
  31569. };
  31570. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31571. if (this.rotationQuaternion) {
  31572. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31573. //update the up vector!
  31574. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31575. }
  31576. else {
  31577. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31578. }
  31579. };
  31580. TargetCamera.prototype._getViewMatrix = function () {
  31581. if (!this.lockedTarget) {
  31582. // Compute
  31583. this._updateCameraRotationMatrix();
  31584. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31585. // Computing target and final matrix
  31586. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  31587. }
  31588. else {
  31589. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  31590. }
  31591. if (this.getScene().useRightHandedSystem) {
  31592. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31593. }
  31594. else {
  31595. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31596. }
  31597. return this._viewMatrix;
  31598. };
  31599. /**
  31600. * @override
  31601. * Override Camera.createRigCamera
  31602. */
  31603. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31604. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  31605. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  31606. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  31607. if (!this.rotationQuaternion) {
  31608. this.rotationQuaternion = new BABYLON.Quaternion();
  31609. }
  31610. rigCamera._cameraRigParams = {};
  31611. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  31612. }
  31613. return rigCamera;
  31614. }
  31615. return null;
  31616. };
  31617. /**
  31618. * @override
  31619. * Override Camera._updateRigCameras
  31620. */
  31621. TargetCamera.prototype._updateRigCameras = function () {
  31622. var camLeft = this._rigCameras[0];
  31623. var camRight = this._rigCameras[1];
  31624. switch (this.cameraRigMode) {
  31625. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31626. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31627. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31628. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31629. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  31630. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  31631. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  31632. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  31633. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  31634. camLeft.setTarget(this.getTarget());
  31635. camRight.setTarget(this.getTarget());
  31636. break;
  31637. case BABYLON.Camera.RIG_MODE_VR:
  31638. if (camLeft.rotationQuaternion) {
  31639. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31640. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31641. }
  31642. else {
  31643. camLeft.rotation.copyFrom(this.rotation);
  31644. camRight.rotation.copyFrom(this.rotation);
  31645. }
  31646. camLeft.position.copyFrom(this.position);
  31647. camRight.position.copyFrom(this.position);
  31648. break;
  31649. }
  31650. _super.prototype._updateRigCameras.call(this);
  31651. };
  31652. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  31653. if (!this._rigCamTransformMatrix) {
  31654. this._rigCamTransformMatrix = new BABYLON.Matrix();
  31655. }
  31656. var target = this.getTarget();
  31657. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  31658. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  31659. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  31660. };
  31661. TargetCamera.prototype.getClassName = function () {
  31662. return "TargetCamera";
  31663. };
  31664. __decorate([
  31665. BABYLON.serializeAsVector3()
  31666. ], TargetCamera.prototype, "rotation", void 0);
  31667. __decorate([
  31668. BABYLON.serialize()
  31669. ], TargetCamera.prototype, "speed", void 0);
  31670. __decorate([
  31671. BABYLON.serializeAsMeshReference("lockedTargetId")
  31672. ], TargetCamera.prototype, "lockedTarget", void 0);
  31673. return TargetCamera;
  31674. }(BABYLON.Camera));
  31675. BABYLON.TargetCamera = TargetCamera;
  31676. })(BABYLON || (BABYLON = {}));
  31677. //# sourceMappingURL=babylon.targetCamera.js.map
  31678. var BABYLON;
  31679. (function (BABYLON) {
  31680. var ArcRotateCameraKeyboardMoveInput = (function () {
  31681. function ArcRotateCameraKeyboardMoveInput() {
  31682. this._keys = [];
  31683. this.keysUp = [38];
  31684. this.keysDown = [40];
  31685. this.keysLeft = [37];
  31686. this.keysRight = [39];
  31687. }
  31688. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31689. var _this = this;
  31690. element.tabIndex = 1;
  31691. this._onKeyDown = function (evt) {
  31692. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31693. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31694. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31695. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31696. var index = _this._keys.indexOf(evt.keyCode);
  31697. if (index === -1) {
  31698. _this._keys.push(evt.keyCode);
  31699. }
  31700. if (evt.preventDefault) {
  31701. if (!noPreventDefault) {
  31702. evt.preventDefault();
  31703. }
  31704. }
  31705. }
  31706. };
  31707. this._onKeyUp = function (evt) {
  31708. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31709. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31710. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31711. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31712. var index = _this._keys.indexOf(evt.keyCode);
  31713. if (index >= 0) {
  31714. _this._keys.splice(index, 1);
  31715. }
  31716. if (evt.preventDefault) {
  31717. if (!noPreventDefault) {
  31718. evt.preventDefault();
  31719. }
  31720. }
  31721. }
  31722. };
  31723. this._onLostFocus = function () {
  31724. _this._keys = [];
  31725. };
  31726. this._onFocus = function () {
  31727. element.addEventListener("keydown", _this._onKeyDown, false);
  31728. element.addEventListener("keyup", _this._onKeyUp, false);
  31729. };
  31730. this._onBlur = function () {
  31731. element.removeEventListener("keydown", _this._onKeyDown);
  31732. element.removeEventListener("keyup", _this._onKeyUp);
  31733. };
  31734. element.addEventListener("focus", this._onFocus);
  31735. element.addEventListener("blur", this._onBlur);
  31736. BABYLON.Tools.RegisterTopRootEvents([
  31737. { name: "blur", handler: this._onLostFocus }
  31738. ]);
  31739. };
  31740. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31741. if (element && this._onBlur) {
  31742. this._onBlur();
  31743. element.removeEventListener("focus", this._onFocus);
  31744. element.removeEventListener("blur", this._onBlur);
  31745. }
  31746. BABYLON.Tools.UnregisterTopRootEvents([
  31747. { name: "blur", handler: this._onLostFocus }
  31748. ]);
  31749. this._keys = [];
  31750. this._onKeyDown = null;
  31751. this._onKeyUp = null;
  31752. this._onLostFocus = null;
  31753. this._onBlur = null;
  31754. this._onFocus = null;
  31755. };
  31756. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31757. if (this._onKeyDown) {
  31758. var camera = this.camera;
  31759. for (var index = 0; index < this._keys.length; index++) {
  31760. var keyCode = this._keys[index];
  31761. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31762. camera.inertialAlphaOffset -= 0.01;
  31763. }
  31764. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31765. camera.inertialBetaOffset -= 0.01;
  31766. }
  31767. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31768. camera.inertialAlphaOffset += 0.01;
  31769. }
  31770. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31771. camera.inertialBetaOffset += 0.01;
  31772. }
  31773. }
  31774. }
  31775. };
  31776. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  31777. return "ArcRotateCameraKeyboardMoveInput";
  31778. };
  31779. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31780. return "keyboard";
  31781. };
  31782. __decorate([
  31783. BABYLON.serialize()
  31784. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  31785. __decorate([
  31786. BABYLON.serialize()
  31787. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  31788. __decorate([
  31789. BABYLON.serialize()
  31790. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  31791. __decorate([
  31792. BABYLON.serialize()
  31793. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  31794. return ArcRotateCameraKeyboardMoveInput;
  31795. }());
  31796. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  31797. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  31798. })(BABYLON || (BABYLON = {}));
  31799. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  31800. var BABYLON;
  31801. (function (BABYLON) {
  31802. var ArcRotateCameraMouseWheelInput = (function () {
  31803. function ArcRotateCameraMouseWheelInput() {
  31804. this.wheelPrecision = 3.0;
  31805. }
  31806. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  31807. var _this = this;
  31808. this._wheel = function (p, s) {
  31809. //sanity check - this should be a PointerWheel event.
  31810. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  31811. return;
  31812. var event = p.event;
  31813. var delta = 0;
  31814. if (event.wheelDelta) {
  31815. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  31816. }
  31817. else if (event.detail) {
  31818. delta = -event.detail / _this.wheelPrecision;
  31819. }
  31820. if (delta)
  31821. _this.camera.inertialRadiusOffset += delta;
  31822. if (event.preventDefault) {
  31823. if (!noPreventDefault) {
  31824. event.preventDefault();
  31825. }
  31826. }
  31827. };
  31828. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  31829. };
  31830. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  31831. if (this._observer && element) {
  31832. this.camera.getScene().onPointerObservable.remove(this._observer);
  31833. this._observer = null;
  31834. this._wheel = null;
  31835. }
  31836. };
  31837. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  31838. return "ArcRotateCameraMouseWheelInput";
  31839. };
  31840. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  31841. return "mousewheel";
  31842. };
  31843. __decorate([
  31844. BABYLON.serialize()
  31845. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  31846. return ArcRotateCameraMouseWheelInput;
  31847. }());
  31848. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  31849. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  31850. })(BABYLON || (BABYLON = {}));
  31851. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  31852. var BABYLON;
  31853. (function (BABYLON) {
  31854. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  31855. var ArcRotateCameraPointersInput = (function () {
  31856. function ArcRotateCameraPointersInput() {
  31857. this.buttons = [0, 1, 2];
  31858. this.angularSensibilityX = 1000.0;
  31859. this.angularSensibilityY = 1000.0;
  31860. this.pinchPrecision = 6.0;
  31861. this.panningSensibility = 50.0;
  31862. this._isPanClick = false;
  31863. this.pinchInwards = true;
  31864. }
  31865. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  31866. var _this = this;
  31867. var engine = this.camera.getEngine();
  31868. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  31869. var pointA, pointB;
  31870. var previousPinchDistance = 0;
  31871. this._pointerInput = function (p, s) {
  31872. var evt = p.event;
  31873. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31874. return;
  31875. }
  31876. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31877. try {
  31878. evt.srcElement.setPointerCapture(evt.pointerId);
  31879. }
  31880. catch (e) {
  31881. //Nothing to do with the error. Execution will continue.
  31882. }
  31883. // Manage panning with pan button click
  31884. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  31885. // manage pointers
  31886. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  31887. if (pointA === undefined) {
  31888. pointA = cacheSoloPointer;
  31889. }
  31890. else if (pointB === undefined) {
  31891. pointB = cacheSoloPointer;
  31892. }
  31893. if (!noPreventDefault) {
  31894. evt.preventDefault();
  31895. element.focus();
  31896. }
  31897. }
  31898. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  31899. try {
  31900. evt.srcElement.releasePointerCapture(evt.pointerId);
  31901. }
  31902. catch (e) {
  31903. //Nothing to do with the error.
  31904. }
  31905. cacheSoloPointer = null;
  31906. previousPinchDistance = 0;
  31907. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  31908. //but emptying completly pointers collection is required to fix a bug on iPhone :
  31909. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  31910. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  31911. pointA = pointB = undefined;
  31912. if (!noPreventDefault) {
  31913. evt.preventDefault();
  31914. }
  31915. }
  31916. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  31917. if (!noPreventDefault) {
  31918. evt.preventDefault();
  31919. }
  31920. // One button down
  31921. if (pointA && pointB === undefined) {
  31922. if (_this.panningSensibility !== 0 &&
  31923. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  31924. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  31925. _this.camera
  31926. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  31927. _this.camera
  31928. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  31929. }
  31930. else {
  31931. var offsetX = evt.clientX - cacheSoloPointer.x;
  31932. var offsetY = evt.clientY - cacheSoloPointer.y;
  31933. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31934. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31935. }
  31936. cacheSoloPointer.x = evt.clientX;
  31937. cacheSoloPointer.y = evt.clientY;
  31938. }
  31939. else if (pointA && pointB) {
  31940. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  31941. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  31942. ed.x = evt.clientX;
  31943. ed.y = evt.clientY;
  31944. var direction = _this.pinchInwards ? 1 : -1;
  31945. var distX = pointA.x - pointB.x;
  31946. var distY = pointA.y - pointB.y;
  31947. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  31948. if (previousPinchDistance === 0) {
  31949. previousPinchDistance = pinchSquaredDistance;
  31950. return;
  31951. }
  31952. if (pinchSquaredDistance !== previousPinchDistance) {
  31953. _this.camera
  31954. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  31955. (_this.pinchPrecision *
  31956. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  31957. direction);
  31958. previousPinchDistance = pinchSquaredDistance;
  31959. }
  31960. }
  31961. }
  31962. };
  31963. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  31964. this._onContextMenu = function (evt) {
  31965. evt.preventDefault();
  31966. };
  31967. if (!this.camera._useCtrlForPanning) {
  31968. element.addEventListener("contextmenu", this._onContextMenu, false);
  31969. }
  31970. this._onLostFocus = function () {
  31971. //this._keys = [];
  31972. pointA = pointB = undefined;
  31973. previousPinchDistance = 0;
  31974. cacheSoloPointer = null;
  31975. };
  31976. this._onMouseMove = function (evt) {
  31977. if (!engine.isPointerLock) {
  31978. return;
  31979. }
  31980. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  31981. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  31982. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31983. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31984. if (!noPreventDefault) {
  31985. evt.preventDefault();
  31986. }
  31987. };
  31988. this._onGestureStart = function (e) {
  31989. if (window.MSGesture === undefined) {
  31990. return;
  31991. }
  31992. if (!_this._MSGestureHandler) {
  31993. _this._MSGestureHandler = new MSGesture();
  31994. _this._MSGestureHandler.target = element;
  31995. }
  31996. _this._MSGestureHandler.addPointer(e.pointerId);
  31997. };
  31998. this._onGesture = function (e) {
  31999. _this.camera.radius *= e.scale;
  32000. if (e.preventDefault) {
  32001. if (!noPreventDefault) {
  32002. e.stopPropagation();
  32003. e.preventDefault();
  32004. }
  32005. }
  32006. };
  32007. element.addEventListener("mousemove", this._onMouseMove, false);
  32008. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  32009. element.addEventListener("MSGestureChange", this._onGesture, false);
  32010. BABYLON.Tools.RegisterTopRootEvents([
  32011. { name: "blur", handler: this._onLostFocus }
  32012. ]);
  32013. };
  32014. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  32015. BABYLON.Tools.UnregisterTopRootEvents([
  32016. { name: "blur", handler: this._onLostFocus }
  32017. ]);
  32018. if (element && this._observer) {
  32019. this.camera.getScene().onPointerObservable.remove(this._observer);
  32020. this._observer = null;
  32021. element.removeEventListener("contextmenu", this._onContextMenu);
  32022. element.removeEventListener("mousemove", this._onMouseMove);
  32023. element.removeEventListener("MSPointerDown", this._onGestureStart);
  32024. element.removeEventListener("MSGestureChange", this._onGesture);
  32025. this._isPanClick = false;
  32026. this.pinchInwards = true;
  32027. this._onMouseMove = null;
  32028. this._onGestureStart = null;
  32029. this._onGesture = null;
  32030. this._MSGestureHandler = null;
  32031. this._onLostFocus = null;
  32032. this._onContextMenu = null;
  32033. }
  32034. };
  32035. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  32036. return "ArcRotateCameraPointersInput";
  32037. };
  32038. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  32039. return "pointers";
  32040. };
  32041. __decorate([
  32042. BABYLON.serialize()
  32043. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  32044. __decorate([
  32045. BABYLON.serialize()
  32046. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  32047. __decorate([
  32048. BABYLON.serialize()
  32049. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  32050. __decorate([
  32051. BABYLON.serialize()
  32052. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  32053. __decorate([
  32054. BABYLON.serialize()
  32055. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  32056. return ArcRotateCameraPointersInput;
  32057. }());
  32058. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  32059. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  32060. })(BABYLON || (BABYLON = {}));
  32061. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  32062. /// <reference path="babylon.targetCamera.ts" />
  32063. /// <reference path="..\Tools\babylon.tools.ts" />
  32064. var BABYLON;
  32065. (function (BABYLON) {
  32066. var ArcRotateCamera = (function (_super) {
  32067. __extends(ArcRotateCamera, _super);
  32068. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  32069. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  32070. _this.inertialAlphaOffset = 0;
  32071. _this.inertialBetaOffset = 0;
  32072. _this.inertialRadiusOffset = 0;
  32073. _this.lowerAlphaLimit = null;
  32074. _this.upperAlphaLimit = null;
  32075. _this.lowerBetaLimit = 0.01;
  32076. _this.upperBetaLimit = Math.PI;
  32077. _this.lowerRadiusLimit = null;
  32078. _this.upperRadiusLimit = null;
  32079. _this.inertialPanningX = 0;
  32080. _this.inertialPanningY = 0;
  32081. _this.panningInertia = 0.9;
  32082. //-- end properties for backward compatibility for inputs
  32083. _this.zoomOnFactor = 1;
  32084. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  32085. _this.allowUpsideDown = true;
  32086. _this._viewMatrix = new BABYLON.Matrix();
  32087. // Panning
  32088. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  32089. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  32090. _this.checkCollisions = false;
  32091. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  32092. _this._previousPosition = BABYLON.Vector3.Zero();
  32093. _this._collisionVelocity = BABYLON.Vector3.Zero();
  32094. _this._newPosition = BABYLON.Vector3.Zero();
  32095. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32096. if (collidedMesh === void 0) { collidedMesh = null; }
  32097. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  32098. newPosition.multiplyInPlace(_this._collider.radius);
  32099. }
  32100. if (!collidedMesh) {
  32101. _this._previousPosition.copyFrom(_this.position);
  32102. }
  32103. else {
  32104. _this.setPosition(newPosition);
  32105. if (_this.onCollide) {
  32106. _this.onCollide(collidedMesh);
  32107. }
  32108. }
  32109. // Recompute because of constraints
  32110. var cosa = Math.cos(_this.alpha);
  32111. var sina = Math.sin(_this.alpha);
  32112. var cosb = Math.cos(_this.beta);
  32113. var sinb = Math.sin(_this.beta);
  32114. if (sinb === 0) {
  32115. sinb = 0.0001;
  32116. }
  32117. var target = _this._getTargetPosition();
  32118. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  32119. _this.position.copyFrom(_this._newPosition);
  32120. var up = _this.upVector;
  32121. if (_this.allowUpsideDown && _this.beta < 0) {
  32122. up = up.clone();
  32123. up = up.negate();
  32124. }
  32125. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  32126. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  32127. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  32128. _this._collisionTriggered = false;
  32129. };
  32130. _this._target = BABYLON.Vector3.Zero();
  32131. if (target) {
  32132. _this.setTarget(target);
  32133. }
  32134. _this.alpha = alpha;
  32135. _this.beta = beta;
  32136. _this.radius = radius;
  32137. _this.getViewMatrix();
  32138. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  32139. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  32140. return _this;
  32141. }
  32142. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  32143. get: function () {
  32144. return this._target;
  32145. },
  32146. set: function (value) {
  32147. this.setTarget(value);
  32148. },
  32149. enumerable: true,
  32150. configurable: true
  32151. });
  32152. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  32153. //-- begin properties for backward compatibility for inputs
  32154. get: function () {
  32155. var pointers = this.inputs.attached["pointers"];
  32156. if (pointers)
  32157. return pointers.angularSensibilityX;
  32158. },
  32159. set: function (value) {
  32160. var pointers = this.inputs.attached["pointers"];
  32161. if (pointers) {
  32162. pointers.angularSensibilityX = value;
  32163. }
  32164. },
  32165. enumerable: true,
  32166. configurable: true
  32167. });
  32168. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  32169. get: function () {
  32170. var pointers = this.inputs.attached["pointers"];
  32171. if (pointers)
  32172. return pointers.angularSensibilityY;
  32173. },
  32174. set: function (value) {
  32175. var pointers = this.inputs.attached["pointers"];
  32176. if (pointers) {
  32177. pointers.angularSensibilityY = value;
  32178. }
  32179. },
  32180. enumerable: true,
  32181. configurable: true
  32182. });
  32183. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  32184. get: function () {
  32185. var pointers = this.inputs.attached["pointers"];
  32186. if (pointers)
  32187. return pointers.pinchPrecision;
  32188. },
  32189. set: function (value) {
  32190. var pointers = this.inputs.attached["pointers"];
  32191. if (pointers) {
  32192. pointers.pinchPrecision = value;
  32193. }
  32194. },
  32195. enumerable: true,
  32196. configurable: true
  32197. });
  32198. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  32199. get: function () {
  32200. var pointers = this.inputs.attached["pointers"];
  32201. if (pointers)
  32202. return pointers.panningSensibility;
  32203. },
  32204. set: function (value) {
  32205. var pointers = this.inputs.attached["pointers"];
  32206. if (pointers) {
  32207. pointers.panningSensibility = value;
  32208. }
  32209. },
  32210. enumerable: true,
  32211. configurable: true
  32212. });
  32213. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  32214. get: function () {
  32215. var keyboard = this.inputs.attached["keyboard"];
  32216. if (keyboard)
  32217. return keyboard.keysUp;
  32218. },
  32219. set: function (value) {
  32220. var keyboard = this.inputs.attached["keyboard"];
  32221. if (keyboard)
  32222. keyboard.keysUp = value;
  32223. },
  32224. enumerable: true,
  32225. configurable: true
  32226. });
  32227. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  32228. get: function () {
  32229. var keyboard = this.inputs.attached["keyboard"];
  32230. if (keyboard)
  32231. return keyboard.keysDown;
  32232. },
  32233. set: function (value) {
  32234. var keyboard = this.inputs.attached["keyboard"];
  32235. if (keyboard)
  32236. keyboard.keysDown = value;
  32237. },
  32238. enumerable: true,
  32239. configurable: true
  32240. });
  32241. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  32242. get: function () {
  32243. var keyboard = this.inputs.attached["keyboard"];
  32244. if (keyboard)
  32245. return keyboard.keysLeft;
  32246. },
  32247. set: function (value) {
  32248. var keyboard = this.inputs.attached["keyboard"];
  32249. if (keyboard)
  32250. keyboard.keysLeft = value;
  32251. },
  32252. enumerable: true,
  32253. configurable: true
  32254. });
  32255. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  32256. get: function () {
  32257. var keyboard = this.inputs.attached["keyboard"];
  32258. if (keyboard)
  32259. return keyboard.keysRight;
  32260. },
  32261. set: function (value) {
  32262. var keyboard = this.inputs.attached["keyboard"];
  32263. if (keyboard)
  32264. keyboard.keysRight = value;
  32265. },
  32266. enumerable: true,
  32267. configurable: true
  32268. });
  32269. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  32270. get: function () {
  32271. var mousewheel = this.inputs.attached["mousewheel"];
  32272. if (mousewheel)
  32273. return mousewheel.wheelPrecision;
  32274. },
  32275. set: function (value) {
  32276. var mousewheel = this.inputs.attached["mousewheel"];
  32277. if (mousewheel)
  32278. mousewheel.wheelPrecision = value;
  32279. },
  32280. enumerable: true,
  32281. configurable: true
  32282. });
  32283. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  32284. get: function () {
  32285. return this._bouncingBehavior;
  32286. },
  32287. enumerable: true,
  32288. configurable: true
  32289. });
  32290. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  32291. get: function () {
  32292. return this._bouncingBehavior != null;
  32293. },
  32294. set: function (value) {
  32295. if (value === this.useBouncingBehavior) {
  32296. return;
  32297. }
  32298. if (value) {
  32299. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  32300. this.addBehavior(this._bouncingBehavior);
  32301. }
  32302. else {
  32303. this.removeBehavior(this._bouncingBehavior);
  32304. this._bouncingBehavior = null;
  32305. }
  32306. },
  32307. enumerable: true,
  32308. configurable: true
  32309. });
  32310. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  32311. get: function () {
  32312. return this._framingBehavior;
  32313. },
  32314. enumerable: true,
  32315. configurable: true
  32316. });
  32317. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  32318. get: function () {
  32319. return this._framingBehavior != null;
  32320. },
  32321. set: function (value) {
  32322. if (value === this.useFramingBehavior) {
  32323. return;
  32324. }
  32325. if (value) {
  32326. this._framingBehavior = new BABYLON.FramingBehavior();
  32327. this.addBehavior(this._framingBehavior);
  32328. }
  32329. else {
  32330. this.removeBehavior(this._framingBehavior);
  32331. this._framingBehavior = null;
  32332. }
  32333. },
  32334. enumerable: true,
  32335. configurable: true
  32336. });
  32337. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  32338. get: function () {
  32339. return this._autoRotationBehavior;
  32340. },
  32341. enumerable: true,
  32342. configurable: true
  32343. });
  32344. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  32345. get: function () {
  32346. return this._autoRotationBehavior != null;
  32347. },
  32348. set: function (value) {
  32349. if (value === this.useAutoRotationBehavior) {
  32350. return;
  32351. }
  32352. if (value) {
  32353. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  32354. this.addBehavior(this._autoRotationBehavior);
  32355. }
  32356. else {
  32357. this.removeBehavior(this._autoRotationBehavior);
  32358. this._autoRotationBehavior = null;
  32359. }
  32360. },
  32361. enumerable: true,
  32362. configurable: true
  32363. });
  32364. // Cache
  32365. ArcRotateCamera.prototype._initCache = function () {
  32366. _super.prototype._initCache.call(this);
  32367. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32368. this._cache.alpha = undefined;
  32369. this._cache.beta = undefined;
  32370. this._cache.radius = undefined;
  32371. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  32372. };
  32373. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  32374. if (!ignoreParentClass) {
  32375. _super.prototype._updateCache.call(this);
  32376. }
  32377. this._cache._target.copyFrom(this._getTargetPosition());
  32378. this._cache.alpha = this.alpha;
  32379. this._cache.beta = this.beta;
  32380. this._cache.radius = this.radius;
  32381. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  32382. };
  32383. ArcRotateCamera.prototype._getTargetPosition = function () {
  32384. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  32385. var pos = this._targetHost.getAbsolutePosition();
  32386. if (this._targetBoundingCenter) {
  32387. pos.addToRef(this._targetBoundingCenter, this._target);
  32388. }
  32389. else {
  32390. this._target.copyFrom(pos);
  32391. }
  32392. }
  32393. var lockedTargetPosition = this._getLockedTargetPosition();
  32394. if (lockedTargetPosition) {
  32395. return lockedTargetPosition;
  32396. }
  32397. return this._target;
  32398. };
  32399. // Synchronized
  32400. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  32401. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  32402. return false;
  32403. return this._cache._target.equals(this._getTargetPosition())
  32404. && this._cache.alpha === this.alpha
  32405. && this._cache.beta === this.beta
  32406. && this._cache.radius === this.radius
  32407. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  32408. };
  32409. // Methods
  32410. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  32411. var _this = this;
  32412. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  32413. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  32414. this._useCtrlForPanning = useCtrlForPanning;
  32415. this._panningMouseButton = panningMouseButton;
  32416. this.inputs.attachElement(element, noPreventDefault);
  32417. this._reset = function () {
  32418. _this.inertialAlphaOffset = 0;
  32419. _this.inertialBetaOffset = 0;
  32420. _this.inertialRadiusOffset = 0;
  32421. };
  32422. };
  32423. ArcRotateCamera.prototype.detachControl = function (element) {
  32424. this.inputs.detachElement(element);
  32425. if (this._reset) {
  32426. this._reset();
  32427. }
  32428. };
  32429. ArcRotateCamera.prototype._checkInputs = function () {
  32430. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  32431. if (this._collisionTriggered) {
  32432. return;
  32433. }
  32434. this.inputs.checkInputs();
  32435. // Inertia
  32436. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  32437. if (this.getScene().useRightHandedSystem) {
  32438. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32439. }
  32440. else {
  32441. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32442. }
  32443. this.beta += this.inertialBetaOffset;
  32444. this.radius -= this.inertialRadiusOffset;
  32445. this.inertialAlphaOffset *= this.inertia;
  32446. this.inertialBetaOffset *= this.inertia;
  32447. this.inertialRadiusOffset *= this.inertia;
  32448. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  32449. this.inertialAlphaOffset = 0;
  32450. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  32451. this.inertialBetaOffset = 0;
  32452. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  32453. this.inertialRadiusOffset = 0;
  32454. }
  32455. // Panning inertia
  32456. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  32457. if (!this._localDirection) {
  32458. this._localDirection = BABYLON.Vector3.Zero();
  32459. this._transformedDirection = BABYLON.Vector3.Zero();
  32460. }
  32461. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  32462. this._localDirection.multiplyInPlace(this.panningAxis);
  32463. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  32464. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  32465. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  32466. if (!this.panningAxis.y) {
  32467. this._transformedDirection.y = 0;
  32468. }
  32469. if (!this._targetHost) {
  32470. this._target.addInPlace(this._transformedDirection);
  32471. }
  32472. this.inertialPanningX *= this.panningInertia;
  32473. this.inertialPanningY *= this.panningInertia;
  32474. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  32475. this.inertialPanningX = 0;
  32476. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  32477. this.inertialPanningY = 0;
  32478. }
  32479. // Limits
  32480. this._checkLimits();
  32481. _super.prototype._checkInputs.call(this);
  32482. };
  32483. ArcRotateCamera.prototype._checkLimits = function () {
  32484. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32485. if (this.allowUpsideDown && this.beta > Math.PI) {
  32486. this.beta = this.beta - (2 * Math.PI);
  32487. }
  32488. }
  32489. else {
  32490. if (this.beta < this.lowerBetaLimit) {
  32491. this.beta = this.lowerBetaLimit;
  32492. }
  32493. }
  32494. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  32495. if (this.allowUpsideDown && this.beta < -Math.PI) {
  32496. this.beta = this.beta + (2 * Math.PI);
  32497. }
  32498. }
  32499. else {
  32500. if (this.beta > this.upperBetaLimit) {
  32501. this.beta = this.upperBetaLimit;
  32502. }
  32503. }
  32504. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  32505. this.alpha = this.lowerAlphaLimit;
  32506. }
  32507. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  32508. this.alpha = this.upperAlphaLimit;
  32509. }
  32510. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  32511. this.radius = this.lowerRadiusLimit;
  32512. }
  32513. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  32514. this.radius = this.upperRadiusLimit;
  32515. }
  32516. };
  32517. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  32518. var radiusv3 = this.position.subtract(this._getTargetPosition());
  32519. this.radius = radiusv3.length();
  32520. if (this.radius === 0) {
  32521. this.radius = 0.0001; // Just to avoid division by zero
  32522. }
  32523. // Alpha
  32524. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  32525. if (radiusv3.z < 0) {
  32526. this.alpha = 2 * Math.PI - this.alpha;
  32527. }
  32528. // Beta
  32529. this.beta = Math.acos(radiusv3.y / this.radius);
  32530. this._checkLimits();
  32531. };
  32532. ArcRotateCamera.prototype.setPosition = function (position) {
  32533. if (this.position.equals(position)) {
  32534. return;
  32535. }
  32536. this.position.copyFrom(position);
  32537. this.rebuildAnglesAndRadius();
  32538. };
  32539. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  32540. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  32541. if (allowSamePosition === void 0) { allowSamePosition = false; }
  32542. if (target.getBoundingInfo) {
  32543. if (toBoundingCenter) {
  32544. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  32545. }
  32546. else {
  32547. this._targetBoundingCenter = null;
  32548. }
  32549. this._targetHost = target;
  32550. this._target = this._getTargetPosition();
  32551. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  32552. }
  32553. else {
  32554. var newTarget = target;
  32555. var currentTarget = this._getTargetPosition();
  32556. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  32557. return;
  32558. }
  32559. this._targetHost = null;
  32560. this._target = newTarget;
  32561. this._targetBoundingCenter = null;
  32562. this.onMeshTargetChangedObservable.notifyObservers(null);
  32563. }
  32564. this.rebuildAnglesAndRadius();
  32565. };
  32566. ArcRotateCamera.prototype._getViewMatrix = function () {
  32567. // Compute
  32568. var cosa = Math.cos(this.alpha);
  32569. var sina = Math.sin(this.alpha);
  32570. var cosb = Math.cos(this.beta);
  32571. var sinb = Math.sin(this.beta);
  32572. if (sinb === 0) {
  32573. sinb = 0.0001;
  32574. }
  32575. var target = this._getTargetPosition();
  32576. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  32577. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  32578. if (!this._collider) {
  32579. this._collider = new BABYLON.Collider();
  32580. }
  32581. this._collider.radius = this.collisionRadius;
  32582. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  32583. this._collisionTriggered = true;
  32584. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32585. }
  32586. else {
  32587. this.position.copyFrom(this._newPosition);
  32588. var up = this.upVector;
  32589. if (this.allowUpsideDown && sinb < 0) {
  32590. up = up.clone();
  32591. up = up.negate();
  32592. }
  32593. if (this.getScene().useRightHandedSystem) {
  32594. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  32595. }
  32596. else {
  32597. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  32598. }
  32599. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  32600. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  32601. }
  32602. this._currentTarget = target;
  32603. return this._viewMatrix;
  32604. };
  32605. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  32606. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32607. meshes = meshes || this.getScene().meshes;
  32608. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  32609. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  32610. this.radius = distance * this.zoomOnFactor;
  32611. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  32612. };
  32613. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  32614. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32615. var meshesOrMinMaxVector;
  32616. var distance;
  32617. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  32618. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  32619. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  32620. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  32621. }
  32622. else {
  32623. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  32624. distance = meshesOrMinMaxVectorAndDistance.distance;
  32625. }
  32626. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  32627. if (!doNotUpdateMaxZ) {
  32628. this.maxZ = distance * 2;
  32629. }
  32630. };
  32631. /**
  32632. * @override
  32633. * Override Camera.createRigCamera
  32634. */
  32635. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32636. var alphaShift;
  32637. switch (this.cameraRigMode) {
  32638. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32639. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32640. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32641. case BABYLON.Camera.RIG_MODE_VR:
  32642. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  32643. break;
  32644. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32645. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  32646. break;
  32647. }
  32648. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  32649. rigCam._cameraRigParams = {};
  32650. return rigCam;
  32651. };
  32652. /**
  32653. * @override
  32654. * Override Camera._updateRigCameras
  32655. */
  32656. ArcRotateCamera.prototype._updateRigCameras = function () {
  32657. var camLeft = this._rigCameras[0];
  32658. var camRight = this._rigCameras[1];
  32659. camLeft.beta = camRight.beta = this.beta;
  32660. camLeft.radius = camRight.radius = this.radius;
  32661. switch (this.cameraRigMode) {
  32662. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32663. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32664. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32665. case BABYLON.Camera.RIG_MODE_VR:
  32666. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32667. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32668. break;
  32669. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32670. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32671. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32672. break;
  32673. }
  32674. _super.prototype._updateRigCameras.call(this);
  32675. };
  32676. ArcRotateCamera.prototype.dispose = function () {
  32677. this.inputs.clear();
  32678. _super.prototype.dispose.call(this);
  32679. };
  32680. ArcRotateCamera.prototype.getClassName = function () {
  32681. return "ArcRotateCamera";
  32682. };
  32683. __decorate([
  32684. BABYLON.serialize()
  32685. ], ArcRotateCamera.prototype, "alpha", void 0);
  32686. __decorate([
  32687. BABYLON.serialize()
  32688. ], ArcRotateCamera.prototype, "beta", void 0);
  32689. __decorate([
  32690. BABYLON.serialize()
  32691. ], ArcRotateCamera.prototype, "radius", void 0);
  32692. __decorate([
  32693. BABYLON.serializeAsVector3("target")
  32694. ], ArcRotateCamera.prototype, "_target", void 0);
  32695. __decorate([
  32696. BABYLON.serialize()
  32697. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  32698. __decorate([
  32699. BABYLON.serialize()
  32700. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  32701. __decorate([
  32702. BABYLON.serialize()
  32703. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  32704. __decorate([
  32705. BABYLON.serialize()
  32706. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  32707. __decorate([
  32708. BABYLON.serialize()
  32709. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  32710. __decorate([
  32711. BABYLON.serialize()
  32712. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  32713. __decorate([
  32714. BABYLON.serialize()
  32715. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  32716. __decorate([
  32717. BABYLON.serialize()
  32718. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  32719. __decorate([
  32720. BABYLON.serialize()
  32721. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  32722. __decorate([
  32723. BABYLON.serialize()
  32724. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  32725. __decorate([
  32726. BABYLON.serialize()
  32727. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  32728. __decorate([
  32729. BABYLON.serialize()
  32730. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  32731. __decorate([
  32732. BABYLON.serialize()
  32733. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  32734. __decorate([
  32735. BABYLON.serialize()
  32736. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  32737. return ArcRotateCamera;
  32738. }(BABYLON.TargetCamera));
  32739. BABYLON.ArcRotateCamera = ArcRotateCamera;
  32740. })(BABYLON || (BABYLON = {}));
  32741. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  32742. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  32743. var BABYLON;
  32744. (function (BABYLON) {
  32745. var ArcRotateCameraInputsManager = (function (_super) {
  32746. __extends(ArcRotateCameraInputsManager, _super);
  32747. function ArcRotateCameraInputsManager(camera) {
  32748. return _super.call(this, camera) || this;
  32749. }
  32750. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  32751. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  32752. return this;
  32753. };
  32754. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  32755. this.add(new BABYLON.ArcRotateCameraPointersInput());
  32756. return this;
  32757. };
  32758. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  32759. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  32760. return this;
  32761. };
  32762. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  32763. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  32764. return this;
  32765. };
  32766. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  32767. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  32768. return this;
  32769. };
  32770. return ArcRotateCameraInputsManager;
  32771. }(BABYLON.CameraInputsManager));
  32772. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  32773. })(BABYLON || (BABYLON = {}));
  32774. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  32775. var BABYLON;
  32776. (function (BABYLON) {
  32777. var CubeTexture = (function (_super) {
  32778. __extends(CubeTexture, _super);
  32779. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  32780. if (onLoad === void 0) { onLoad = null; }
  32781. if (onError === void 0) { onError = null; }
  32782. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32783. if (prefiltered === void 0) { prefiltered = false; }
  32784. if (forcedExtension === void 0) { forcedExtension = null; }
  32785. var _this = _super.call(this, scene) || this;
  32786. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  32787. _this.name = rootUrl;
  32788. _this.url = rootUrl;
  32789. _this._noMipmap = noMipmap;
  32790. _this.hasAlpha = false;
  32791. _this._format = format;
  32792. _this._prefiltered = prefiltered;
  32793. _this.isCube = true;
  32794. _this._textureMatrix = BABYLON.Matrix.Identity();
  32795. if (prefiltered) {
  32796. _this.gammaSpace = false;
  32797. }
  32798. if (!rootUrl && !files) {
  32799. return _this;
  32800. }
  32801. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  32802. if (!files) {
  32803. if (!extensions) {
  32804. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  32805. }
  32806. files = [];
  32807. for (var index = 0; index < extensions.length; index++) {
  32808. files.push(rootUrl + extensions[index]);
  32809. }
  32810. _this._extensions = extensions;
  32811. }
  32812. _this._files = files;
  32813. if (!_this._texture) {
  32814. if (!scene.useDelayedTextureLoading) {
  32815. if (prefiltered) {
  32816. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  32817. }
  32818. else {
  32819. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  32820. }
  32821. }
  32822. else {
  32823. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32824. }
  32825. }
  32826. else if (onLoad) {
  32827. if (_this._texture.isReady) {
  32828. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  32829. }
  32830. else {
  32831. _this._texture.onLoadedObservable.add(onLoad);
  32832. }
  32833. }
  32834. return _this;
  32835. }
  32836. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  32837. return new CubeTexture("", scene, null, noMipmap, files);
  32838. };
  32839. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  32840. if (forcedExtension === void 0) { forcedExtension = null; }
  32841. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  32842. };
  32843. // Methods
  32844. CubeTexture.prototype.delayLoad = function () {
  32845. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32846. return;
  32847. }
  32848. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32849. this._texture = this._getFromCache(this.url, this._noMipmap);
  32850. if (!this._texture) {
  32851. if (this._prefiltered) {
  32852. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  32853. }
  32854. else {
  32855. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  32856. }
  32857. }
  32858. };
  32859. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  32860. return this._textureMatrix;
  32861. };
  32862. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  32863. this._textureMatrix = value;
  32864. };
  32865. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32866. var texture = BABYLON.SerializationHelper.Parse(function () {
  32867. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  32868. }, parsedTexture, scene);
  32869. // Animations
  32870. if (parsedTexture.animations) {
  32871. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  32872. var parsedAnimation = parsedTexture.animations[animationIndex];
  32873. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32874. }
  32875. }
  32876. return texture;
  32877. };
  32878. CubeTexture.prototype.clone = function () {
  32879. var _this = this;
  32880. return BABYLON.SerializationHelper.Clone(function () {
  32881. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  32882. }, this);
  32883. };
  32884. return CubeTexture;
  32885. }(BABYLON.BaseTexture));
  32886. BABYLON.CubeTexture = CubeTexture;
  32887. })(BABYLON || (BABYLON = {}));
  32888. //# sourceMappingURL=babylon.cubeTexture.js.map
  32889. var BABYLON;
  32890. (function (BABYLON) {
  32891. var RenderTargetTexture = (function (_super) {
  32892. __extends(RenderTargetTexture, _super);
  32893. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  32894. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  32895. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32896. if (isCube === void 0) { isCube = false; }
  32897. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32898. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  32899. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  32900. if (isMulti === void 0) { isMulti = false; }
  32901. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  32902. _this.isCube = isCube;
  32903. /**
  32904. * Use this list to define the list of mesh you want to render.
  32905. */
  32906. _this.renderList = new Array();
  32907. _this.renderParticles = true;
  32908. _this.renderSprites = false;
  32909. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  32910. _this.ignoreCameraViewport = false;
  32911. // Events
  32912. /**
  32913. * An event triggered when the texture is unbind.
  32914. * @type {BABYLON.Observable}
  32915. */
  32916. _this.onBeforeBindObservable = new BABYLON.Observable();
  32917. /**
  32918. * An event triggered when the texture is unbind.
  32919. * @type {BABYLON.Observable}
  32920. */
  32921. _this.onAfterUnbindObservable = new BABYLON.Observable();
  32922. /**
  32923. * An event triggered before rendering the texture
  32924. * @type {BABYLON.Observable}
  32925. */
  32926. _this.onBeforeRenderObservable = new BABYLON.Observable();
  32927. /**
  32928. * An event triggered after rendering the texture
  32929. * @type {BABYLON.Observable}
  32930. */
  32931. _this.onAfterRenderObservable = new BABYLON.Observable();
  32932. /**
  32933. * An event triggered after the texture clear
  32934. * @type {BABYLON.Observable}
  32935. */
  32936. _this.onClearObservable = new BABYLON.Observable();
  32937. _this._currentRefreshId = -1;
  32938. _this._refreshRate = 1;
  32939. _this._samples = 1;
  32940. scene = _this.getScene();
  32941. _this.name = name;
  32942. _this.isRenderTarget = true;
  32943. _this._size = size;
  32944. _this._generateMipMaps = generateMipMaps;
  32945. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  32946. // Rendering groups
  32947. _this._renderingManager = new BABYLON.RenderingManager(scene);
  32948. if (isMulti) {
  32949. return _this;
  32950. }
  32951. _this._renderTargetOptions = {
  32952. generateMipMaps: generateMipMaps,
  32953. type: type,
  32954. samplingMode: samplingMode,
  32955. generateDepthBuffer: generateDepthBuffer,
  32956. generateStencilBuffer: generateStencilBuffer
  32957. };
  32958. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  32959. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32960. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32961. }
  32962. if (isCube) {
  32963. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  32964. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  32965. _this._textureMatrix = BABYLON.Matrix.Identity();
  32966. }
  32967. else {
  32968. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  32969. }
  32970. return _this;
  32971. }
  32972. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  32973. get: function () {
  32974. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  32975. },
  32976. enumerable: true,
  32977. configurable: true
  32978. });
  32979. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  32980. get: function () {
  32981. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  32982. },
  32983. enumerable: true,
  32984. configurable: true
  32985. });
  32986. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  32987. get: function () {
  32988. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  32989. },
  32990. enumerable: true,
  32991. configurable: true
  32992. });
  32993. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  32994. set: function (callback) {
  32995. if (this._onAfterUnbindObserver) {
  32996. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  32997. }
  32998. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  32999. },
  33000. enumerable: true,
  33001. configurable: true
  33002. });
  33003. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  33004. set: function (callback) {
  33005. if (this._onBeforeRenderObserver) {
  33006. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  33007. }
  33008. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  33009. },
  33010. enumerable: true,
  33011. configurable: true
  33012. });
  33013. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  33014. set: function (callback) {
  33015. if (this._onAfterRenderObserver) {
  33016. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  33017. }
  33018. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  33019. },
  33020. enumerable: true,
  33021. configurable: true
  33022. });
  33023. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  33024. set: function (callback) {
  33025. if (this._onClearObserver) {
  33026. this.onClearObservable.remove(this._onClearObserver);
  33027. }
  33028. this._onClearObserver = this.onClearObservable.add(callback);
  33029. },
  33030. enumerable: true,
  33031. configurable: true
  33032. });
  33033. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  33034. get: function () {
  33035. return this._renderTargetOptions;
  33036. },
  33037. enumerable: true,
  33038. configurable: true
  33039. });
  33040. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  33041. get: function () {
  33042. return this._samples;
  33043. },
  33044. set: function (value) {
  33045. if (this._samples === value) {
  33046. return;
  33047. }
  33048. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  33049. },
  33050. enumerable: true,
  33051. configurable: true
  33052. });
  33053. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  33054. this._currentRefreshId = -1;
  33055. };
  33056. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  33057. get: function () {
  33058. return this._refreshRate;
  33059. },
  33060. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  33061. set: function (value) {
  33062. this._refreshRate = value;
  33063. this.resetRefreshCounter();
  33064. },
  33065. enumerable: true,
  33066. configurable: true
  33067. });
  33068. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  33069. if (!this._postProcessManager) {
  33070. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  33071. this._postProcesses = new Array();
  33072. }
  33073. this._postProcesses.push(postProcess);
  33074. this._postProcesses[0].autoClear = false;
  33075. };
  33076. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  33077. if (!this._postProcesses) {
  33078. return;
  33079. }
  33080. if (dispose) {
  33081. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  33082. var postProcess = _a[_i];
  33083. postProcess.dispose();
  33084. postProcess = null;
  33085. }
  33086. }
  33087. this._postProcesses = [];
  33088. };
  33089. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  33090. if (!this._postProcesses) {
  33091. return;
  33092. }
  33093. var index = this._postProcesses.indexOf(postProcess);
  33094. if (index === -1) {
  33095. return;
  33096. }
  33097. this._postProcesses.splice(index, 1);
  33098. if (this._postProcesses.length > 0) {
  33099. this._postProcesses[0].autoClear = false;
  33100. }
  33101. };
  33102. RenderTargetTexture.prototype._shouldRender = function () {
  33103. if (this._currentRefreshId === -1) {
  33104. this._currentRefreshId = 1;
  33105. return true;
  33106. }
  33107. if (this.refreshRate === this._currentRefreshId) {
  33108. this._currentRefreshId = 1;
  33109. return true;
  33110. }
  33111. this._currentRefreshId++;
  33112. return false;
  33113. };
  33114. RenderTargetTexture.prototype.getRenderSize = function () {
  33115. return this._size;
  33116. };
  33117. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  33118. get: function () {
  33119. return true;
  33120. },
  33121. enumerable: true,
  33122. configurable: true
  33123. });
  33124. RenderTargetTexture.prototype.scale = function (ratio) {
  33125. var newSize = this._size * ratio;
  33126. this.resize(newSize);
  33127. };
  33128. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  33129. if (this.isCube) {
  33130. return this._textureMatrix;
  33131. }
  33132. return _super.prototype.getReflectionTextureMatrix.call(this);
  33133. };
  33134. RenderTargetTexture.prototype.resize = function (size) {
  33135. this.releaseInternalTexture();
  33136. if (this.isCube) {
  33137. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  33138. }
  33139. else {
  33140. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  33141. }
  33142. };
  33143. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  33144. var scene = this.getScene();
  33145. var engine = scene.getEngine();
  33146. if (this.useCameraPostProcesses !== undefined) {
  33147. useCameraPostProcess = this.useCameraPostProcesses;
  33148. }
  33149. if (this._waitingRenderList) {
  33150. this.renderList = [];
  33151. for (var index = 0; index < this._waitingRenderList.length; index++) {
  33152. var id = this._waitingRenderList[index];
  33153. this.renderList.push(scene.getMeshByID(id));
  33154. }
  33155. delete this._waitingRenderList;
  33156. }
  33157. // Is predicate defined?
  33158. if (this.renderListPredicate) {
  33159. this.renderList.splice(0); // Clear previous renderList
  33160. var sceneMeshes = this.getScene().meshes;
  33161. for (var index = 0; index < sceneMeshes.length; index++) {
  33162. var mesh = sceneMeshes[index];
  33163. if (this.renderListPredicate(mesh)) {
  33164. this.renderList.push(mesh);
  33165. }
  33166. }
  33167. }
  33168. if (this.renderList && this.renderList.length === 0) {
  33169. return;
  33170. }
  33171. this.onBeforeBindObservable.notifyObservers(this);
  33172. // Set custom projection.
  33173. // Needs to be before binding to prevent changing the aspect ratio.
  33174. var camera;
  33175. if (this.activeCamera) {
  33176. camera = this.activeCamera;
  33177. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  33178. if (this.activeCamera !== scene.activeCamera) {
  33179. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  33180. }
  33181. }
  33182. else {
  33183. camera = scene.activeCamera;
  33184. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  33185. }
  33186. // Prepare renderingManager
  33187. this._renderingManager.reset();
  33188. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  33189. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  33190. var sceneRenderId = scene.getRenderId();
  33191. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  33192. var mesh = currentRenderList[meshIndex];
  33193. if (mesh) {
  33194. if (!mesh.isReady()) {
  33195. // Reset _currentRefreshId
  33196. this.resetRefreshCounter();
  33197. continue;
  33198. }
  33199. mesh._preActivateForIntermediateRendering(sceneRenderId);
  33200. var isMasked = void 0;
  33201. if (!this.renderList) {
  33202. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  33203. }
  33204. else {
  33205. isMasked = false;
  33206. }
  33207. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  33208. mesh._activate(sceneRenderId);
  33209. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33210. var subMesh = mesh.subMeshes[subIndex];
  33211. scene._activeIndices.addCount(subMesh.indexCount, false);
  33212. this._renderingManager.dispatch(subMesh);
  33213. }
  33214. }
  33215. }
  33216. }
  33217. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  33218. var particleSystem = scene.particleSystems[particleIndex];
  33219. var emitter = particleSystem.emitter;
  33220. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  33221. continue;
  33222. }
  33223. if (currentRenderList.indexOf(emitter) >= 0) {
  33224. this._renderingManager.dispatchParticles(particleSystem);
  33225. }
  33226. }
  33227. if (this.isCube) {
  33228. for (var face = 0; face < 6; face++) {
  33229. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  33230. scene.incrementRenderId();
  33231. scene.resetCachedMaterial();
  33232. }
  33233. }
  33234. else {
  33235. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  33236. }
  33237. this.onAfterUnbindObservable.notifyObservers(this);
  33238. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  33239. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  33240. }
  33241. engine.setViewport(scene.activeCamera.viewport);
  33242. scene.resetCachedMaterial();
  33243. };
  33244. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  33245. var _this = this;
  33246. var scene = this.getScene();
  33247. var engine = scene.getEngine();
  33248. // Bind
  33249. if (this._postProcessManager) {
  33250. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  33251. }
  33252. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  33253. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  33254. }
  33255. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  33256. // Clear
  33257. if (this.onClearObservable.hasObservers()) {
  33258. this.onClearObservable.notifyObservers(engine);
  33259. }
  33260. else {
  33261. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  33262. }
  33263. if (!this._doNotChangeAspectRatio) {
  33264. scene.updateTransformMatrix(true);
  33265. }
  33266. // Render
  33267. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  33268. if (this._postProcessManager) {
  33269. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  33270. }
  33271. else if (useCameraPostProcess) {
  33272. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  33273. }
  33274. if (!this._doNotChangeAspectRatio) {
  33275. scene.updateTransformMatrix(true);
  33276. }
  33277. // Dump ?
  33278. if (dumpForDebug) {
  33279. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  33280. }
  33281. // Unbind
  33282. if (!this.isCube || faceIndex === 5) {
  33283. if (this.isCube) {
  33284. if (faceIndex === 5) {
  33285. engine.generateMipMapsForCubemap(this._texture);
  33286. }
  33287. }
  33288. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  33289. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  33290. });
  33291. }
  33292. else {
  33293. this.onAfterRenderObservable.notifyObservers(faceIndex);
  33294. }
  33295. };
  33296. /**
  33297. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  33298. * This allowed control for front to back rendering or reversly depending of the special needs.
  33299. *
  33300. * @param renderingGroupId The rendering group id corresponding to its index
  33301. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  33302. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  33303. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  33304. */
  33305. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  33306. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  33307. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  33308. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  33309. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  33310. };
  33311. /**
  33312. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  33313. *
  33314. * @param renderingGroupId The rendering group id corresponding to its index
  33315. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  33316. */
  33317. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  33318. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  33319. };
  33320. RenderTargetTexture.prototype.clone = function () {
  33321. var textureSize = this.getSize();
  33322. 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);
  33323. // Base texture
  33324. newTexture.hasAlpha = this.hasAlpha;
  33325. newTexture.level = this.level;
  33326. // RenderTarget Texture
  33327. newTexture.coordinatesMode = this.coordinatesMode;
  33328. newTexture.renderList = this.renderList.slice(0);
  33329. return newTexture;
  33330. };
  33331. RenderTargetTexture.prototype.serialize = function () {
  33332. if (!this.name) {
  33333. return null;
  33334. }
  33335. var serializationObject = _super.prototype.serialize.call(this);
  33336. serializationObject.renderTargetSize = this.getRenderSize();
  33337. serializationObject.renderList = [];
  33338. for (var index = 0; index < this.renderList.length; index++) {
  33339. serializationObject.renderList.push(this.renderList[index].id);
  33340. }
  33341. return serializationObject;
  33342. };
  33343. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  33344. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  33345. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  33346. };
  33347. RenderTargetTexture.prototype.dispose = function () {
  33348. if (this._postProcessManager) {
  33349. this._postProcessManager.dispose();
  33350. this._postProcessManager = null;
  33351. }
  33352. this.clearPostProcesses(true);
  33353. this.renderList = null;
  33354. // Remove from custom render targets
  33355. var scene = this.getScene();
  33356. var index = scene.customRenderTargets.indexOf(this);
  33357. if (index >= 0) {
  33358. scene.customRenderTargets.splice(index, 1);
  33359. }
  33360. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  33361. var camera = _a[_i];
  33362. index = camera.customRenderTargets.indexOf(this);
  33363. if (index >= 0) {
  33364. camera.customRenderTargets.splice(index, 1);
  33365. }
  33366. }
  33367. _super.prototype.dispose.call(this);
  33368. };
  33369. RenderTargetTexture.prototype._rebuild = function () {
  33370. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  33371. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  33372. }
  33373. if (this._postProcessManager) {
  33374. this._postProcessManager._rebuild();
  33375. }
  33376. };
  33377. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  33378. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  33379. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  33380. return RenderTargetTexture;
  33381. }(BABYLON.Texture));
  33382. BABYLON.RenderTargetTexture = RenderTargetTexture;
  33383. })(BABYLON || (BABYLON = {}));
  33384. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  33385. var BABYLON;
  33386. (function (BABYLON) {
  33387. ;
  33388. var MultiRenderTarget = (function (_super) {
  33389. __extends(MultiRenderTarget, _super);
  33390. function MultiRenderTarget(name, size, count, scene, options) {
  33391. var _this = this;
  33392. options = options || {};
  33393. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  33394. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  33395. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  33396. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  33397. if (!_this.isSupported) {
  33398. _this.dispose();
  33399. return;
  33400. }
  33401. var types = [];
  33402. var samplingModes = [];
  33403. for (var i = 0; i < count; i++) {
  33404. if (options.types && options.types[i]) {
  33405. types.push(options.types[i]);
  33406. }
  33407. else {
  33408. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  33409. }
  33410. if (options.samplingModes && options.samplingModes[i]) {
  33411. samplingModes.push(options.samplingModes[i]);
  33412. }
  33413. else {
  33414. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33415. }
  33416. }
  33417. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  33418. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  33419. _this._count = count;
  33420. _this._size = size;
  33421. _this._multiRenderTargetOptions = {
  33422. samplingModes: samplingModes,
  33423. generateMipMaps: generateMipMaps,
  33424. generateDepthBuffer: generateDepthBuffer,
  33425. generateStencilBuffer: generateStencilBuffer,
  33426. generateDepthTexture: generateDepthTexture,
  33427. types: types,
  33428. textureCount: count
  33429. };
  33430. _this._internalTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  33431. _this._createInternalTextures();
  33432. return _this;
  33433. }
  33434. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  33435. get: function () {
  33436. var engine = this.getScene().getEngine();
  33437. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  33438. },
  33439. enumerable: true,
  33440. configurable: true
  33441. });
  33442. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  33443. get: function () {
  33444. return this._textures;
  33445. },
  33446. enumerable: true,
  33447. configurable: true
  33448. });
  33449. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  33450. get: function () {
  33451. return this._textures[this._textures.length - 1];
  33452. },
  33453. enumerable: true,
  33454. configurable: true
  33455. });
  33456. MultiRenderTarget.prototype._createInternalTextures = function () {
  33457. this._textures = [];
  33458. for (var i = 0; i < this._internalTextures.length; i++) {
  33459. var texture = new BABYLON.Texture(null, this.getScene());
  33460. texture._texture = this._internalTextures[i];
  33461. this._textures.push(texture);
  33462. }
  33463. // Keeps references to frame buffer and stencil/depth buffer
  33464. this._texture = this._internalTextures[0];
  33465. };
  33466. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  33467. get: function () {
  33468. return this._samples;
  33469. },
  33470. set: function (value) {
  33471. if (this._samples === value) {
  33472. return;
  33473. }
  33474. for (var i = 0; i < this._internalTextures.length; i++) {
  33475. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  33476. }
  33477. },
  33478. enumerable: true,
  33479. configurable: true
  33480. });
  33481. MultiRenderTarget.prototype.resize = function (size) {
  33482. this.releaseInternalTextures();
  33483. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  33484. this._createInternalTextures();
  33485. };
  33486. MultiRenderTarget.prototype.dispose = function () {
  33487. this.releaseInternalTextures();
  33488. _super.prototype.dispose.call(this);
  33489. };
  33490. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  33491. if (!this._internalTextures) {
  33492. return;
  33493. }
  33494. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  33495. if (this._internalTextures[i] !== undefined) {
  33496. this._internalTextures[i].dispose();
  33497. this._internalTextures.splice(i, 1);
  33498. }
  33499. }
  33500. };
  33501. return MultiRenderTarget;
  33502. }(BABYLON.RenderTargetTexture));
  33503. BABYLON.MultiRenderTarget = MultiRenderTarget;
  33504. })(BABYLON || (BABYLON = {}));
  33505. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  33506. /// <reference path="babylon.renderTargetTexture.ts" />
  33507. var BABYLON;
  33508. (function (BABYLON) {
  33509. var MirrorTexture = (function (_super) {
  33510. __extends(MirrorTexture, _super);
  33511. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  33512. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33513. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33514. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  33515. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  33516. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  33517. _this._transformMatrix = BABYLON.Matrix.Zero();
  33518. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  33519. _this._blurKernelX = 0;
  33520. _this._blurKernelY = 0;
  33521. _this._blurRatio = 1.0;
  33522. _this.onBeforeRenderObservable.add(function () {
  33523. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  33524. _this._savedViewMatrix = scene.getViewMatrix();
  33525. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  33526. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  33527. scene.clipPlane = _this.mirrorPlane;
  33528. scene.getEngine().cullBackFaces = false;
  33529. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  33530. });
  33531. _this.onAfterRenderObservable.add(function () {
  33532. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  33533. scene.getEngine().cullBackFaces = true;
  33534. scene._mirroredCameraPosition = null;
  33535. delete scene.clipPlane;
  33536. });
  33537. return _this;
  33538. }
  33539. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  33540. get: function () {
  33541. return this._blurRatio;
  33542. },
  33543. set: function (value) {
  33544. if (this._blurRatio === value) {
  33545. return;
  33546. }
  33547. this._blurRatio = value;
  33548. this._preparePostProcesses();
  33549. },
  33550. enumerable: true,
  33551. configurable: true
  33552. });
  33553. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  33554. set: function (value) {
  33555. this.blurKernelX = value;
  33556. this.blurKernelY = value;
  33557. },
  33558. enumerable: true,
  33559. configurable: true
  33560. });
  33561. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  33562. get: function () {
  33563. return this._blurKernelX;
  33564. },
  33565. set: function (value) {
  33566. if (this._blurKernelX === value) {
  33567. return;
  33568. }
  33569. this._blurKernelX = value;
  33570. this._preparePostProcesses();
  33571. },
  33572. enumerable: true,
  33573. configurable: true
  33574. });
  33575. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  33576. get: function () {
  33577. return this._blurKernelY;
  33578. },
  33579. set: function (value) {
  33580. if (this._blurKernelY === value) {
  33581. return;
  33582. }
  33583. this._blurKernelY = value;
  33584. this._preparePostProcesses();
  33585. },
  33586. enumerable: true,
  33587. configurable: true
  33588. });
  33589. MirrorTexture.prototype._preparePostProcesses = function () {
  33590. this.clearPostProcesses(true);
  33591. if (this._blurKernelX && this._blurKernelY) {
  33592. var engine = this.getScene().getEngine();
  33593. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33594. 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);
  33595. this._blurX.autoClear = false;
  33596. if (this._blurRatio === 1 && this.samples < 2) {
  33597. this._blurX.outputTexture = this._texture;
  33598. }
  33599. else {
  33600. this._blurX.alwaysForcePOT = true;
  33601. }
  33602. 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);
  33603. this._blurY.autoClear = false;
  33604. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  33605. this.addPostProcess(this._blurX);
  33606. this.addPostProcess(this._blurY);
  33607. }
  33608. };
  33609. MirrorTexture.prototype.clone = function () {
  33610. var textureSize = this.getSize();
  33611. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  33612. // Base texture
  33613. newTexture.hasAlpha = this.hasAlpha;
  33614. newTexture.level = this.level;
  33615. // Mirror Texture
  33616. newTexture.mirrorPlane = this.mirrorPlane.clone();
  33617. newTexture.renderList = this.renderList.slice(0);
  33618. return newTexture;
  33619. };
  33620. MirrorTexture.prototype.serialize = function () {
  33621. if (!this.name) {
  33622. return null;
  33623. }
  33624. var serializationObject = _super.prototype.serialize.call(this);
  33625. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  33626. return serializationObject;
  33627. };
  33628. return MirrorTexture;
  33629. }(BABYLON.RenderTargetTexture));
  33630. BABYLON.MirrorTexture = MirrorTexture;
  33631. })(BABYLON || (BABYLON = {}));
  33632. //# sourceMappingURL=babylon.mirrorTexture.js.map
  33633. /// <reference path="babylon.renderTargetTexture.ts" />
  33634. var BABYLON;
  33635. (function (BABYLON) {
  33636. /**
  33637. * Creates a refraction texture used by refraction channel of the standard material.
  33638. * @param name the texture name
  33639. * @param size size of the underlying texture
  33640. * @param scene root scene
  33641. */
  33642. var RefractionTexture = (function (_super) {
  33643. __extends(RefractionTexture, _super);
  33644. function RefractionTexture(name, size, scene, generateMipMaps) {
  33645. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  33646. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  33647. _this.depth = 2.0;
  33648. _this.onBeforeRenderObservable.add(function () {
  33649. scene.clipPlane = _this.refractionPlane;
  33650. });
  33651. _this.onAfterRenderObservable.add(function () {
  33652. delete scene.clipPlane;
  33653. });
  33654. return _this;
  33655. }
  33656. RefractionTexture.prototype.clone = function () {
  33657. var textureSize = this.getSize();
  33658. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  33659. // Base texture
  33660. newTexture.hasAlpha = this.hasAlpha;
  33661. newTexture.level = this.level;
  33662. // Refraction Texture
  33663. newTexture.refractionPlane = this.refractionPlane.clone();
  33664. newTexture.renderList = this.renderList.slice(0);
  33665. newTexture.depth = this.depth;
  33666. return newTexture;
  33667. };
  33668. RefractionTexture.prototype.serialize = function () {
  33669. if (!this.name) {
  33670. return null;
  33671. }
  33672. var serializationObject = _super.prototype.serialize.call(this);
  33673. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  33674. serializationObject.depth = this.depth;
  33675. return serializationObject;
  33676. };
  33677. return RefractionTexture;
  33678. }(BABYLON.RenderTargetTexture));
  33679. BABYLON.RefractionTexture = RefractionTexture;
  33680. })(BABYLON || (BABYLON = {}));
  33681. //# sourceMappingURL=babylon.refractionTexture.js.map
  33682. /// <reference path="babylon.texture.ts" />
  33683. var BABYLON;
  33684. (function (BABYLON) {
  33685. var DynamicTexture = (function (_super) {
  33686. __extends(DynamicTexture, _super);
  33687. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  33688. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33689. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  33690. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  33691. _this.name = name;
  33692. var engine = _this.getScene().getEngine();
  33693. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33694. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33695. _this._generateMipMaps = generateMipMaps;
  33696. if (options.getContext) {
  33697. _this._canvas = options;
  33698. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33699. }
  33700. else {
  33701. _this._canvas = document.createElement("canvas");
  33702. if (options.width) {
  33703. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33704. }
  33705. else {
  33706. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  33707. }
  33708. }
  33709. var textureSize = _this.getSize();
  33710. _this._canvas.width = textureSize.width;
  33711. _this._canvas.height = textureSize.height;
  33712. _this._context = _this._canvas.getContext("2d");
  33713. return _this;
  33714. }
  33715. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  33716. get: function () {
  33717. return true;
  33718. },
  33719. enumerable: true,
  33720. configurable: true
  33721. });
  33722. DynamicTexture.prototype._recreate = function (textureSize) {
  33723. this._canvas.width = textureSize.width;
  33724. this._canvas.height = textureSize.height;
  33725. this.releaseInternalTexture();
  33726. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  33727. };
  33728. DynamicTexture.prototype.scale = function (ratio) {
  33729. var textureSize = this.getSize();
  33730. textureSize.width *= ratio;
  33731. textureSize.height *= ratio;
  33732. this._recreate(textureSize);
  33733. };
  33734. DynamicTexture.prototype.scaleTo = function (width, height) {
  33735. var textureSize = this.getSize();
  33736. textureSize.width = width;
  33737. textureSize.height = height;
  33738. this._recreate(textureSize);
  33739. };
  33740. DynamicTexture.prototype.getContext = function () {
  33741. return this._context;
  33742. };
  33743. DynamicTexture.prototype.clear = function () {
  33744. var size = this.getSize();
  33745. this._context.fillRect(0, 0, size.width, size.height);
  33746. };
  33747. DynamicTexture.prototype.update = function (invertY) {
  33748. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  33749. };
  33750. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  33751. if (update === void 0) { update = true; }
  33752. var size = this.getSize();
  33753. if (clearColor) {
  33754. this._context.fillStyle = clearColor;
  33755. this._context.fillRect(0, 0, size.width, size.height);
  33756. }
  33757. this._context.font = font;
  33758. if (x === null || x === undefined) {
  33759. var textSize = this._context.measureText(text);
  33760. x = (size.width - textSize.width) / 2;
  33761. }
  33762. if (y === null || y === undefined) {
  33763. var fontSize = parseInt((font.replace(/\D/g, '')));
  33764. ;
  33765. y = (size.height / 2) + (fontSize / 3.65);
  33766. }
  33767. this._context.fillStyle = color;
  33768. this._context.fillText(text, x, y);
  33769. if (update) {
  33770. this.update(invertY);
  33771. }
  33772. };
  33773. DynamicTexture.prototype.clone = function () {
  33774. var textureSize = this.getSize();
  33775. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  33776. // Base texture
  33777. newTexture.hasAlpha = this.hasAlpha;
  33778. newTexture.level = this.level;
  33779. // Dynamic Texture
  33780. newTexture.wrapU = this.wrapU;
  33781. newTexture.wrapV = this.wrapV;
  33782. return newTexture;
  33783. };
  33784. DynamicTexture.prototype._rebuild = function () {
  33785. this.update();
  33786. };
  33787. return DynamicTexture;
  33788. }(BABYLON.Texture));
  33789. BABYLON.DynamicTexture = DynamicTexture;
  33790. })(BABYLON || (BABYLON = {}));
  33791. //# sourceMappingURL=babylon.dynamicTexture.js.map
  33792. var BABYLON;
  33793. (function (BABYLON) {
  33794. var VideoTexture = (function (_super) {
  33795. __extends(VideoTexture, _super);
  33796. /**
  33797. * Creates a video texture.
  33798. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  33799. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  33800. * @param {BABYLON.Scene} scene is obviously the current scene.
  33801. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  33802. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  33803. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  33804. */
  33805. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  33806. if (generateMipMaps === void 0) { generateMipMaps = false; }
  33807. if (invertY === void 0) { invertY = false; }
  33808. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33809. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33810. _this._autoLaunch = true;
  33811. var urls;
  33812. _this.name = name;
  33813. if (urlsOrVideo instanceof HTMLVideoElement) {
  33814. _this.video = urlsOrVideo;
  33815. }
  33816. else {
  33817. urls = urlsOrVideo;
  33818. _this.video = document.createElement("video");
  33819. _this.video.autoplay = false;
  33820. _this.video.loop = true;
  33821. }
  33822. _this._generateMipMaps = generateMipMaps;
  33823. _this._samplingMode = samplingMode;
  33824. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  33825. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33826. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33827. }
  33828. else {
  33829. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33830. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33831. _this._generateMipMaps = false;
  33832. }
  33833. if (urls) {
  33834. _this.video.addEventListener("canplay", function () {
  33835. _this._createTexture();
  33836. });
  33837. urls.forEach(function (url) {
  33838. var source = document.createElement("source");
  33839. source.src = url;
  33840. _this.video.appendChild(source);
  33841. });
  33842. }
  33843. else {
  33844. _this._createTexture();
  33845. }
  33846. _this._lastUpdate = BABYLON.Tools.Now;
  33847. return _this;
  33848. }
  33849. VideoTexture.prototype.__setTextureReady = function () {
  33850. this._texture.isReady = true;
  33851. };
  33852. VideoTexture.prototype._createTexture = function () {
  33853. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  33854. if (this._autoLaunch) {
  33855. this._autoLaunch = false;
  33856. this.video.play();
  33857. }
  33858. this._setTextureReady = this.__setTextureReady.bind(this);
  33859. this.video.addEventListener("playing", this._setTextureReady);
  33860. };
  33861. VideoTexture.prototype.update = function () {
  33862. var now = BABYLON.Tools.Now;
  33863. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  33864. return false;
  33865. }
  33866. this._lastUpdate = now;
  33867. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  33868. return true;
  33869. };
  33870. VideoTexture.prototype.dispose = function () {
  33871. _super.prototype.dispose.call(this);
  33872. this.video.removeEventListener("playing", this._setTextureReady);
  33873. };
  33874. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  33875. var video = document.createElement("video");
  33876. var constraintsDeviceId;
  33877. if (constraints && constraints.deviceId) {
  33878. constraintsDeviceId = {
  33879. exact: constraints.deviceId
  33880. };
  33881. }
  33882. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  33883. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  33884. if (navigator.getUserMedia) {
  33885. navigator.getUserMedia({
  33886. video: {
  33887. deviceId: constraintsDeviceId,
  33888. width: {
  33889. min: (constraints && constraints.minWidth) || 256,
  33890. max: (constraints && constraints.maxWidth) || 640
  33891. },
  33892. height: {
  33893. min: (constraints && constraints.minHeight) || 256,
  33894. max: (constraints && constraints.maxHeight) || 480
  33895. }
  33896. }
  33897. }, function (stream) {
  33898. if (video.mozSrcObject !== undefined) {
  33899. video.mozSrcObject = stream;
  33900. }
  33901. else {
  33902. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  33903. }
  33904. video.play();
  33905. if (onReady) {
  33906. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  33907. }
  33908. }, function (e) {
  33909. BABYLON.Tools.Error(e.name);
  33910. });
  33911. }
  33912. };
  33913. return VideoTexture;
  33914. }(BABYLON.Texture));
  33915. BABYLON.VideoTexture = VideoTexture;
  33916. })(BABYLON || (BABYLON = {}));
  33917. //# sourceMappingURL=babylon.videoTexture.js.map
  33918. var BABYLON;
  33919. (function (BABYLON) {
  33920. var RawTexture = (function (_super) {
  33921. __extends(RawTexture, _super);
  33922. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  33923. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33924. if (invertY === void 0) { invertY = false; }
  33925. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33926. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33927. _this.format = format;
  33928. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  33929. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33930. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33931. return _this;
  33932. }
  33933. RawTexture.prototype.update = function (data) {
  33934. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  33935. };
  33936. // Statics
  33937. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33938. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33939. if (invertY === void 0) { invertY = false; }
  33940. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33941. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  33942. };
  33943. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33944. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33945. if (invertY === void 0) { invertY = false; }
  33946. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33947. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33948. };
  33949. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33950. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33951. if (invertY === void 0) { invertY = false; }
  33952. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33953. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33954. };
  33955. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33956. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33957. if (invertY === void 0) { invertY = false; }
  33958. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33959. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  33960. };
  33961. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33962. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33963. if (invertY === void 0) { invertY = false; }
  33964. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33965. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  33966. };
  33967. return RawTexture;
  33968. }(BABYLON.Texture));
  33969. BABYLON.RawTexture = RawTexture;
  33970. })(BABYLON || (BABYLON = {}));
  33971. //# sourceMappingURL=babylon.rawTexture.js.map
  33972. var BABYLON;
  33973. (function (BABYLON) {
  33974. var Internals;
  33975. (function (Internals) {
  33976. /*
  33977. * Based on jsTGALoader - Javascript loader for TGA file
  33978. * By Vincent Thibault
  33979. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  33980. */
  33981. var TGATools = (function () {
  33982. function TGATools() {
  33983. }
  33984. TGATools.GetTGAHeader = function (data) {
  33985. var offset = 0;
  33986. var header = {
  33987. id_length: data[offset++],
  33988. colormap_type: data[offset++],
  33989. image_type: data[offset++],
  33990. colormap_index: data[offset++] | data[offset++] << 8,
  33991. colormap_length: data[offset++] | data[offset++] << 8,
  33992. colormap_size: data[offset++],
  33993. origin: [
  33994. data[offset++] | data[offset++] << 8,
  33995. data[offset++] | data[offset++] << 8
  33996. ],
  33997. width: data[offset++] | data[offset++] << 8,
  33998. height: data[offset++] | data[offset++] << 8,
  33999. pixel_size: data[offset++],
  34000. flags: data[offset++]
  34001. };
  34002. return header;
  34003. };
  34004. TGATools.UploadContent = function (gl, data) {
  34005. // Not enough data to contain header ?
  34006. if (data.length < 19) {
  34007. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  34008. return;
  34009. }
  34010. // Read Header
  34011. var offset = 18;
  34012. var header = TGATools.GetTGAHeader(data);
  34013. // Assume it's a valid Targa file.
  34014. if (header.id_length + offset > data.length) {
  34015. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  34016. return;
  34017. }
  34018. // Skip not needed data
  34019. offset += header.id_length;
  34020. var use_rle = false;
  34021. var use_pal = false;
  34022. var use_rgb = false;
  34023. var use_grey = false;
  34024. // Get some informations.
  34025. switch (header.image_type) {
  34026. case TGATools._TYPE_RLE_INDEXED:
  34027. use_rle = true;
  34028. case TGATools._TYPE_INDEXED:
  34029. use_pal = true;
  34030. break;
  34031. case TGATools._TYPE_RLE_RGB:
  34032. use_rle = true;
  34033. case TGATools._TYPE_RGB:
  34034. use_rgb = true;
  34035. break;
  34036. case TGATools._TYPE_RLE_GREY:
  34037. use_rle = true;
  34038. case TGATools._TYPE_GREY:
  34039. use_grey = true;
  34040. break;
  34041. }
  34042. var pixel_data;
  34043. var numAlphaBits = header.flags & 0xf;
  34044. var pixel_size = header.pixel_size >> 3;
  34045. var pixel_total = header.width * header.height * pixel_size;
  34046. // Read palettes
  34047. var palettes;
  34048. if (use_pal) {
  34049. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  34050. }
  34051. // Read LRE
  34052. if (use_rle) {
  34053. pixel_data = new Uint8Array(pixel_total);
  34054. var c, count, i;
  34055. var localOffset = 0;
  34056. var pixels = new Uint8Array(pixel_size);
  34057. while (offset < pixel_total && localOffset < pixel_total) {
  34058. c = data[offset++];
  34059. count = (c & 0x7f) + 1;
  34060. // RLE pixels
  34061. if (c & 0x80) {
  34062. // Bind pixel tmp array
  34063. for (i = 0; i < pixel_size; ++i) {
  34064. pixels[i] = data[offset++];
  34065. }
  34066. // Copy pixel array
  34067. for (i = 0; i < count; ++i) {
  34068. pixel_data.set(pixels, localOffset + i * pixel_size);
  34069. }
  34070. localOffset += pixel_size * count;
  34071. }
  34072. else {
  34073. count *= pixel_size;
  34074. for (i = 0; i < count; ++i) {
  34075. pixel_data[localOffset + i] = data[offset++];
  34076. }
  34077. localOffset += count;
  34078. }
  34079. }
  34080. }
  34081. else {
  34082. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  34083. }
  34084. // Load to texture
  34085. var x_start, y_start, x_step, y_step, y_end, x_end;
  34086. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  34087. default:
  34088. case TGATools._ORIGIN_UL:
  34089. x_start = 0;
  34090. x_step = 1;
  34091. x_end = header.width;
  34092. y_start = 0;
  34093. y_step = 1;
  34094. y_end = header.height;
  34095. break;
  34096. case TGATools._ORIGIN_BL:
  34097. x_start = 0;
  34098. x_step = 1;
  34099. x_end = header.width;
  34100. y_start = header.height - 1;
  34101. y_step = -1;
  34102. y_end = -1;
  34103. break;
  34104. case TGATools._ORIGIN_UR:
  34105. x_start = header.width - 1;
  34106. x_step = -1;
  34107. x_end = -1;
  34108. y_start = 0;
  34109. y_step = 1;
  34110. y_end = header.height;
  34111. break;
  34112. case TGATools._ORIGIN_BR:
  34113. x_start = header.width - 1;
  34114. x_step = -1;
  34115. x_end = -1;
  34116. y_start = header.height - 1;
  34117. y_step = -1;
  34118. y_end = -1;
  34119. break;
  34120. }
  34121. // Load the specify method
  34122. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  34123. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  34124. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  34125. };
  34126. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34127. var image = pixel_data, colormap = palettes;
  34128. var width = header.width, height = header.height;
  34129. var color, i = 0, x, y;
  34130. var imageData = new Uint8Array(width * height * 4);
  34131. for (y = y_start; y !== y_end; y += y_step) {
  34132. for (x = x_start; x !== x_end; x += x_step, i++) {
  34133. color = image[i];
  34134. imageData[(x + width * y) * 4 + 3] = 255;
  34135. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  34136. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  34137. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  34138. }
  34139. }
  34140. return imageData;
  34141. };
  34142. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34143. var image = pixel_data;
  34144. var width = header.width, height = header.height;
  34145. var color, i = 0, x, y;
  34146. var imageData = new Uint8Array(width * height * 4);
  34147. for (y = y_start; y !== y_end; y += y_step) {
  34148. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  34149. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  34150. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  34151. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  34152. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  34153. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  34154. }
  34155. }
  34156. return imageData;
  34157. };
  34158. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34159. var image = pixel_data;
  34160. var width = header.width, height = header.height;
  34161. var i = 0, x, y;
  34162. var imageData = new Uint8Array(width * height * 4);
  34163. for (y = y_start; y !== y_end; y += y_step) {
  34164. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  34165. imageData[(x + width * y) * 4 + 3] = 255;
  34166. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34167. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  34168. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  34169. }
  34170. }
  34171. return imageData;
  34172. };
  34173. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34174. var image = pixel_data;
  34175. var width = header.width, height = header.height;
  34176. var i = 0, x, y;
  34177. var imageData = new Uint8Array(width * height * 4);
  34178. for (y = y_start; y !== y_end; y += y_step) {
  34179. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  34180. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34181. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  34182. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  34183. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  34184. }
  34185. }
  34186. return imageData;
  34187. };
  34188. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34189. var image = pixel_data;
  34190. var width = header.width, height = header.height;
  34191. var color, i = 0, x, y;
  34192. var imageData = new Uint8Array(width * height * 4);
  34193. for (y = y_start; y !== y_end; y += y_step) {
  34194. for (x = x_start; x !== x_end; x += x_step, i++) {
  34195. color = image[i];
  34196. imageData[(x + width * y) * 4 + 0] = color;
  34197. imageData[(x + width * y) * 4 + 1] = color;
  34198. imageData[(x + width * y) * 4 + 2] = color;
  34199. imageData[(x + width * y) * 4 + 3] = 255;
  34200. }
  34201. }
  34202. return imageData;
  34203. };
  34204. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34205. var image = pixel_data;
  34206. var width = header.width, height = header.height;
  34207. var i = 0, x, y;
  34208. var imageData = new Uint8Array(width * height * 4);
  34209. for (y = y_start; y !== y_end; y += y_step) {
  34210. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  34211. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  34212. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  34213. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34214. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  34215. }
  34216. }
  34217. return imageData;
  34218. };
  34219. TGATools._TYPE_NO_DATA = 0;
  34220. TGATools._TYPE_INDEXED = 1;
  34221. TGATools._TYPE_RGB = 2;
  34222. TGATools._TYPE_GREY = 3;
  34223. TGATools._TYPE_RLE_INDEXED = 9;
  34224. TGATools._TYPE_RLE_RGB = 10;
  34225. TGATools._TYPE_RLE_GREY = 11;
  34226. TGATools._ORIGIN_MASK = 0x30;
  34227. TGATools._ORIGIN_SHIFT = 0x04;
  34228. TGATools._ORIGIN_BL = 0x00;
  34229. TGATools._ORIGIN_BR = 0x01;
  34230. TGATools._ORIGIN_UL = 0x02;
  34231. TGATools._ORIGIN_UR = 0x03;
  34232. return TGATools;
  34233. }());
  34234. Internals.TGATools = TGATools;
  34235. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34236. })(BABYLON || (BABYLON = {}));
  34237. //# sourceMappingURL=babylon.tga.js.map
  34238. var BABYLON;
  34239. (function (BABYLON) {
  34240. var Internals;
  34241. (function (Internals) {
  34242. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  34243. // All values and structures referenced from:
  34244. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  34245. var DDS_MAGIC = 0x20534444;
  34246. 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;
  34247. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  34248. 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;
  34249. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  34250. function FourCCToInt32(value) {
  34251. return value.charCodeAt(0) +
  34252. (value.charCodeAt(1) << 8) +
  34253. (value.charCodeAt(2) << 16) +
  34254. (value.charCodeAt(3) << 24);
  34255. }
  34256. function Int32ToFourCC(value) {
  34257. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  34258. }
  34259. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  34260. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  34261. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  34262. var FOURCC_DX10 = FourCCToInt32("DX10");
  34263. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  34264. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  34265. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  34266. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  34267. var headerLengthInt = 31; // The header length in 32 bit ints
  34268. // Offsets into the header array
  34269. var off_magic = 0;
  34270. var off_size = 1;
  34271. var off_flags = 2;
  34272. var off_height = 3;
  34273. var off_width = 4;
  34274. var off_mipmapCount = 7;
  34275. var off_pfFlags = 20;
  34276. var off_pfFourCC = 21;
  34277. var off_RGBbpp = 22;
  34278. var off_RMask = 23;
  34279. var off_GMask = 24;
  34280. var off_BMask = 25;
  34281. var off_AMask = 26;
  34282. var off_caps1 = 27;
  34283. var off_caps2 = 28;
  34284. var off_caps3 = 29;
  34285. var off_caps4 = 30;
  34286. var off_dxgiFormat = 32;
  34287. ;
  34288. var DDSTools = (function () {
  34289. function DDSTools() {
  34290. }
  34291. DDSTools.GetDDSInfo = function (arrayBuffer) {
  34292. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  34293. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  34294. var mipmapCount = 1;
  34295. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  34296. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34297. }
  34298. var fourCC = header[off_pfFourCC];
  34299. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  34300. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34301. switch (fourCC) {
  34302. case FOURCC_D3DFMT_R16G16B16A16F:
  34303. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34304. break;
  34305. case FOURCC_D3DFMT_R32G32B32A32F:
  34306. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34307. break;
  34308. case FOURCC_DX10:
  34309. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  34310. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34311. break;
  34312. }
  34313. }
  34314. return {
  34315. width: header[off_width],
  34316. height: header[off_height],
  34317. mipmapCount: mipmapCount,
  34318. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  34319. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  34320. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  34321. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  34322. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  34323. dxgiFormat: dxgiFormat,
  34324. textureType: textureType
  34325. };
  34326. };
  34327. DDSTools._ToHalfFloat = function (value) {
  34328. if (!DDSTools._FloatView) {
  34329. DDSTools._FloatView = new Float32Array(1);
  34330. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  34331. }
  34332. DDSTools._FloatView[0] = value;
  34333. var x = DDSTools._Int32View[0];
  34334. var bits = (x >> 16) & 0x8000; /* Get the sign */
  34335. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  34336. var e = (x >> 23) & 0xff; /* Using int is faster here */
  34337. /* If zero, or denormal, or exponent underflows too much for a denormal
  34338. * half, return signed zero. */
  34339. if (e < 103) {
  34340. return bits;
  34341. }
  34342. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  34343. if (e > 142) {
  34344. bits |= 0x7c00;
  34345. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  34346. * not Inf, so make sure we set one mantissa bit too. */
  34347. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  34348. return bits;
  34349. }
  34350. /* If exponent underflows but not too much, return a denormal */
  34351. if (e < 113) {
  34352. m |= 0x0800;
  34353. /* Extra rounding may overflow and set mantissa to 0 and exponent
  34354. * to 1, which is OK. */
  34355. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  34356. return bits;
  34357. }
  34358. bits |= ((e - 112) << 10) | (m >> 1);
  34359. bits += m & 1;
  34360. return bits;
  34361. };
  34362. DDSTools._FromHalfFloat = function (value) {
  34363. var s = (value & 0x8000) >> 15;
  34364. var e = (value & 0x7C00) >> 10;
  34365. var f = value & 0x03FF;
  34366. if (e === 0) {
  34367. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  34368. }
  34369. else if (e == 0x1F) {
  34370. return f ? NaN : ((s ? -1 : 1) * Infinity);
  34371. }
  34372. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  34373. };
  34374. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34375. var destArray = new Float32Array(dataLength);
  34376. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34377. var index = 0;
  34378. for (var y = 0; y < height; y++) {
  34379. for (var x = 0; x < width; x++) {
  34380. var srcPos = (x + y * width) * 4;
  34381. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  34382. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  34383. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  34384. if (DDSTools.StoreLODInAlphaChannel) {
  34385. destArray[index + 3] = lod;
  34386. }
  34387. else {
  34388. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  34389. }
  34390. index += 4;
  34391. }
  34392. }
  34393. return destArray;
  34394. };
  34395. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34396. if (DDSTools.StoreLODInAlphaChannel) {
  34397. var destArray = new Uint16Array(dataLength);
  34398. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34399. var index = 0;
  34400. for (var y = 0; y < height; y++) {
  34401. for (var x = 0; x < width; x++) {
  34402. var srcPos = (x + y * width) * 4;
  34403. destArray[index] = srcData[srcPos];
  34404. destArray[index + 1] = srcData[srcPos + 1];
  34405. destArray[index + 2] = srcData[srcPos + 2];
  34406. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  34407. index += 4;
  34408. }
  34409. }
  34410. return destArray;
  34411. }
  34412. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  34413. };
  34414. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34415. if (DDSTools.StoreLODInAlphaChannel) {
  34416. var destArray = new Float32Array(dataLength);
  34417. var srcData = new Float32Array(arrayBuffer, dataOffset);
  34418. var index = 0;
  34419. for (var y = 0; y < height; y++) {
  34420. for (var x = 0; x < width; x++) {
  34421. var srcPos = (x + y * width) * 4;
  34422. destArray[index] = srcData[srcPos];
  34423. destArray[index + 1] = srcData[srcPos + 1];
  34424. destArray[index + 2] = srcData[srcPos + 2];
  34425. destArray[index + 3] = lod;
  34426. index += 4;
  34427. }
  34428. }
  34429. return destArray;
  34430. }
  34431. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  34432. };
  34433. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34434. var destArray = new Uint8Array(dataLength);
  34435. var srcData = new Float32Array(arrayBuffer, dataOffset);
  34436. var index = 0;
  34437. for (var y = 0; y < height; y++) {
  34438. for (var x = 0; x < width; x++) {
  34439. var srcPos = (x + y * width) * 4;
  34440. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  34441. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  34442. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  34443. if (DDSTools.StoreLODInAlphaChannel) {
  34444. destArray[index + 3] = lod;
  34445. }
  34446. else {
  34447. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  34448. }
  34449. index += 4;
  34450. }
  34451. }
  34452. return destArray;
  34453. };
  34454. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34455. var destArray = new Uint8Array(dataLength);
  34456. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34457. var index = 0;
  34458. for (var y = 0; y < height; y++) {
  34459. for (var x = 0; x < width; x++) {
  34460. var srcPos = (x + y * width) * 4;
  34461. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  34462. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  34463. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  34464. if (DDSTools.StoreLODInAlphaChannel) {
  34465. destArray[index + 3] = lod;
  34466. }
  34467. else {
  34468. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  34469. }
  34470. index += 4;
  34471. }
  34472. }
  34473. return destArray;
  34474. };
  34475. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34476. var byteArray = new Uint8Array(dataLength);
  34477. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34478. var index = 0;
  34479. for (var y = 0; y < height; y++) {
  34480. for (var x = 0; x < width; x++) {
  34481. var srcPos = (x + y * width) * 4;
  34482. byteArray[index] = srcData[srcPos + 2];
  34483. byteArray[index + 1] = srcData[srcPos + 1];
  34484. byteArray[index + 2] = srcData[srcPos];
  34485. byteArray[index + 3] = srcData[srcPos + 3];
  34486. index += 4;
  34487. }
  34488. }
  34489. return byteArray;
  34490. };
  34491. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34492. var byteArray = new Uint8Array(dataLength);
  34493. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34494. var index = 0;
  34495. for (var y = 0; y < height; y++) {
  34496. for (var x = 0; x < width; x++) {
  34497. var srcPos = (x + y * width) * 3;
  34498. byteArray[index] = srcData[srcPos + 2];
  34499. byteArray[index + 1] = srcData[srcPos + 1];
  34500. byteArray[index + 2] = srcData[srcPos];
  34501. index += 3;
  34502. }
  34503. }
  34504. return byteArray;
  34505. };
  34506. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34507. var byteArray = new Uint8Array(dataLength);
  34508. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34509. var index = 0;
  34510. for (var y = 0; y < height; y++) {
  34511. for (var x = 0; x < width; x++) {
  34512. var srcPos = (x + y * width);
  34513. byteArray[index] = srcData[srcPos];
  34514. index++;
  34515. }
  34516. }
  34517. return byteArray;
  34518. };
  34519. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  34520. if (lodIndex === void 0) { lodIndex = -1; }
  34521. var ext = engine.getCaps().s3tc;
  34522. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  34523. if (header[off_magic] != DDS_MAGIC) {
  34524. BABYLON.Tools.Error("Invalid magic number in DDS header");
  34525. return;
  34526. }
  34527. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  34528. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  34529. return;
  34530. }
  34531. if (info.isCompressed && !ext) {
  34532. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  34533. return;
  34534. }
  34535. var bpp = header[off_RGBbpp];
  34536. dataOffset = header[off_size] + 4;
  34537. var computeFormats = false;
  34538. if (info.isFourCC) {
  34539. fourCC = header[off_pfFourCC];
  34540. switch (fourCC) {
  34541. case FOURCC_DXT1:
  34542. blockBytes = 8;
  34543. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  34544. break;
  34545. case FOURCC_DXT3:
  34546. blockBytes = 16;
  34547. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  34548. break;
  34549. case FOURCC_DXT5:
  34550. blockBytes = 16;
  34551. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  34552. break;
  34553. case FOURCC_D3DFMT_R16G16B16A16F:
  34554. computeFormats = true;
  34555. break;
  34556. case FOURCC_D3DFMT_R32G32B32A32F:
  34557. computeFormats = true;
  34558. break;
  34559. case FOURCC_DX10:
  34560. // There is an additionnal header so dataOffset need to be changed
  34561. dataOffset += 5 * 4; // 5 uints
  34562. var supported = false;
  34563. switch (info.dxgiFormat) {
  34564. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  34565. computeFormats = true;
  34566. supported = true;
  34567. break;
  34568. case DXGI_FORMAT_B8G8R8X8_UNORM:
  34569. info.isRGB = true;
  34570. info.isFourCC = false;
  34571. bpp = 32;
  34572. supported = true;
  34573. break;
  34574. }
  34575. if (supported) {
  34576. break;
  34577. }
  34578. default:
  34579. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  34580. return;
  34581. }
  34582. }
  34583. if (computeFormats) {
  34584. format = engine._getWebGLTextureType(info.textureType);
  34585. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34586. }
  34587. mipmapCount = 1;
  34588. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  34589. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34590. }
  34591. for (var face = 0; face < faces; face++) {
  34592. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34593. width = header[off_width];
  34594. height = header[off_height];
  34595. for (mip = 0; mip < mipmapCount; ++mip) {
  34596. if (lodIndex === -1 || lodIndex === mip) {
  34597. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  34598. var i = (lodIndex === -1) ? mip : 0;
  34599. if (!info.isCompressed && info.isFourCC) {
  34600. dataLength = width * height * 4;
  34601. var floatArray;
  34602. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  34603. if (bpp === 128) {
  34604. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34605. }
  34606. else if (bpp === 64) {
  34607. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34608. }
  34609. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34610. format = engine._getWebGLTextureType(info.textureType);
  34611. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34612. }
  34613. else {
  34614. if (bpp === 128) {
  34615. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34616. }
  34617. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  34618. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34619. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34620. format = engine._getWebGLTextureType(info.textureType);
  34621. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34622. }
  34623. else {
  34624. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34625. }
  34626. }
  34627. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  34628. }
  34629. else if (info.isRGB) {
  34630. if (bpp === 24) {
  34631. dataLength = width * height * 3;
  34632. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34633. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  34634. }
  34635. else {
  34636. dataLength = width * height * 4;
  34637. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34638. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  34639. }
  34640. }
  34641. else if (info.isLuminance) {
  34642. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  34643. var unpaddedRowSize = width;
  34644. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  34645. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  34646. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34647. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  34648. }
  34649. else {
  34650. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  34651. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  34652. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  34653. }
  34654. }
  34655. dataOffset += width * height * (bpp / 8);
  34656. width *= 0.5;
  34657. height *= 0.5;
  34658. width = Math.max(1.0, width);
  34659. height = Math.max(1.0, height);
  34660. }
  34661. }
  34662. };
  34663. DDSTools.StoreLODInAlphaChannel = false;
  34664. return DDSTools;
  34665. }());
  34666. Internals.DDSTools = DDSTools;
  34667. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34668. })(BABYLON || (BABYLON = {}));
  34669. //# sourceMappingURL=babylon.dds.js.map
  34670. var BABYLON;
  34671. (function (BABYLON) {
  34672. var Internals;
  34673. (function (Internals) {
  34674. /**
  34675. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  34676. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  34677. */
  34678. var KhronosTextureContainer = (function () {
  34679. /**
  34680. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  34681. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  34682. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  34683. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  34684. */
  34685. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  34686. this.arrayBuffer = arrayBuffer;
  34687. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  34688. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  34689. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  34690. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  34691. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  34692. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  34693. BABYLON.Tools.Error("texture missing KTX identifier");
  34694. return;
  34695. }
  34696. // load the reset of the header in native 32 bit int
  34697. var header = new Int32Array(this.arrayBuffer, 12, 13);
  34698. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  34699. var oppositeEndianess = header[0] === 0x01020304;
  34700. // read all the header elements in order they exist in the file, without modification (sans endainness)
  34701. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  34702. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  34703. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  34704. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  34705. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  34706. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  34707. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  34708. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  34709. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  34710. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  34711. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  34712. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  34713. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  34714. if (this.glType !== 0) {
  34715. BABYLON.Tools.Error("only compressed formats currently supported");
  34716. return;
  34717. }
  34718. else {
  34719. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  34720. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  34721. }
  34722. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  34723. BABYLON.Tools.Error("only 2D textures currently supported");
  34724. return;
  34725. }
  34726. if (this.numberOfArrayElements !== 0) {
  34727. BABYLON.Tools.Error("texture arrays not currently supported");
  34728. return;
  34729. }
  34730. if (this.numberOfFaces !== facesExpected) {
  34731. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  34732. return;
  34733. }
  34734. // we now have a completely validated file, so could use existence of loadType as success
  34735. // would need to make this more elaborate & adjust checks above to support more than one load type
  34736. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  34737. }
  34738. // not as fast hardware based, but will probably never need to use
  34739. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  34740. return ((val & 0xFF) << 24)
  34741. | ((val & 0xFF00) << 8)
  34742. | ((val >> 8) & 0xFF00)
  34743. | ((val >> 24) & 0xFF);
  34744. };
  34745. /**
  34746. * It is assumed that the texture has already been created & is currently bound
  34747. */
  34748. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  34749. switch (this.loadType) {
  34750. case KhronosTextureContainer.COMPRESSED_2D:
  34751. this._upload2DCompressedLevels(gl, loadMipmaps);
  34752. break;
  34753. case KhronosTextureContainer.TEX_2D:
  34754. case KhronosTextureContainer.COMPRESSED_3D:
  34755. case KhronosTextureContainer.TEX_3D:
  34756. }
  34757. };
  34758. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  34759. // initialize width & height for level 1
  34760. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  34761. var width = this.pixelWidth;
  34762. var height = this.pixelHeight;
  34763. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  34764. for (var level = 0; level < mipmapCount; level++) {
  34765. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  34766. for (var face = 0; face < this.numberOfFaces; face++) {
  34767. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34768. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  34769. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  34770. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  34771. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  34772. }
  34773. width = Math.max(1.0, width * 0.5);
  34774. height = Math.max(1.0, height * 0.5);
  34775. }
  34776. };
  34777. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  34778. // load types
  34779. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  34780. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  34781. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  34782. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  34783. return KhronosTextureContainer;
  34784. }());
  34785. Internals.KhronosTextureContainer = KhronosTextureContainer;
  34786. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34787. })(BABYLON || (BABYLON = {}));
  34788. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  34789. var BABYLON;
  34790. (function (BABYLON) {
  34791. var PostProcess = (function () {
  34792. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  34793. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  34794. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34795. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  34796. if (blockCompilation === void 0) { blockCompilation = false; }
  34797. this.name = name;
  34798. this.width = -1;
  34799. this.height = -1;
  34800. this.autoClear = true;
  34801. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  34802. /*
  34803. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  34804. Can only be used on a single postprocess or on the last one of a chain.
  34805. */
  34806. this.enablePixelPerfectMode = false;
  34807. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  34808. this.alwaysForcePOT = false;
  34809. this.samples = 1;
  34810. this._reusable = false;
  34811. this._textures = new BABYLON.SmartArray(2);
  34812. this._currentRenderTextureInd = 0;
  34813. this._scaleRatio = new BABYLON.Vector2(1, 1);
  34814. this._texelSize = BABYLON.Vector2.Zero();
  34815. // Events
  34816. /**
  34817. * An event triggered when the postprocess is activated.
  34818. * @type {BABYLON.Observable}
  34819. */
  34820. this.onActivateObservable = new BABYLON.Observable();
  34821. /**
  34822. * An event triggered when the postprocess changes its size.
  34823. * @type {BABYLON.Observable}
  34824. */
  34825. this.onSizeChangedObservable = new BABYLON.Observable();
  34826. /**
  34827. * An event triggered when the postprocess applies its effect.
  34828. * @type {BABYLON.Observable}
  34829. */
  34830. this.onApplyObservable = new BABYLON.Observable();
  34831. /**
  34832. * An event triggered before rendering the postprocess
  34833. * @type {BABYLON.Observable}
  34834. */
  34835. this.onBeforeRenderObservable = new BABYLON.Observable();
  34836. /**
  34837. * An event triggered after rendering the postprocess
  34838. * @type {BABYLON.Observable}
  34839. */
  34840. this.onAfterRenderObservable = new BABYLON.Observable();
  34841. if (camera != null) {
  34842. this._camera = camera;
  34843. this._scene = camera.getScene();
  34844. camera.attachPostProcess(this);
  34845. this._engine = this._scene.getEngine();
  34846. this._scene.postProcesses.push(this);
  34847. }
  34848. else {
  34849. this._engine = engine;
  34850. this._engine.postProcesses.push(this);
  34851. }
  34852. this._options = options;
  34853. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  34854. this._reusable = reusable || false;
  34855. this._textureType = textureType;
  34856. this._samplers = samplers || [];
  34857. this._samplers.push("textureSampler");
  34858. this._fragmentUrl = fragmentUrl;
  34859. this._vertexUrl = vertexUrl;
  34860. this._parameters = parameters || [];
  34861. this._parameters.push("scale");
  34862. this._indexParameters = indexParameters;
  34863. if (!blockCompilation) {
  34864. this.updateEffect(defines);
  34865. }
  34866. }
  34867. Object.defineProperty(PostProcess.prototype, "onActivate", {
  34868. set: function (callback) {
  34869. if (this._onActivateObserver) {
  34870. this.onActivateObservable.remove(this._onActivateObserver);
  34871. }
  34872. this._onActivateObserver = this.onActivateObservable.add(callback);
  34873. },
  34874. enumerable: true,
  34875. configurable: true
  34876. });
  34877. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  34878. set: function (callback) {
  34879. if (this._onSizeChangedObserver) {
  34880. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  34881. }
  34882. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  34883. },
  34884. enumerable: true,
  34885. configurable: true
  34886. });
  34887. Object.defineProperty(PostProcess.prototype, "onApply", {
  34888. set: function (callback) {
  34889. if (this._onApplyObserver) {
  34890. this.onApplyObservable.remove(this._onApplyObserver);
  34891. }
  34892. this._onApplyObserver = this.onApplyObservable.add(callback);
  34893. },
  34894. enumerable: true,
  34895. configurable: true
  34896. });
  34897. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  34898. set: function (callback) {
  34899. if (this._onBeforeRenderObserver) {
  34900. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  34901. }
  34902. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  34903. },
  34904. enumerable: true,
  34905. configurable: true
  34906. });
  34907. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  34908. set: function (callback) {
  34909. if (this._onAfterRenderObserver) {
  34910. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  34911. }
  34912. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  34913. },
  34914. enumerable: true,
  34915. configurable: true
  34916. });
  34917. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  34918. get: function () {
  34919. return this._textures.data[this._currentRenderTextureInd];
  34920. },
  34921. set: function (value) {
  34922. this._forcedOutputTexture = value;
  34923. },
  34924. enumerable: true,
  34925. configurable: true
  34926. });
  34927. PostProcess.prototype.getCamera = function () {
  34928. return this._camera;
  34929. };
  34930. Object.defineProperty(PostProcess.prototype, "texelSize", {
  34931. get: function () {
  34932. if (this._shareOutputWithPostProcess) {
  34933. return this._shareOutputWithPostProcess.texelSize;
  34934. }
  34935. if (this._forcedOutputTexture) {
  34936. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  34937. }
  34938. return this._texelSize;
  34939. },
  34940. enumerable: true,
  34941. configurable: true
  34942. });
  34943. PostProcess.prototype.getEngine = function () {
  34944. return this._engine;
  34945. };
  34946. PostProcess.prototype.getEffect = function () {
  34947. return this._effect;
  34948. };
  34949. PostProcess.prototype.shareOutputWith = function (postProcess) {
  34950. this._disposeTextures();
  34951. this._shareOutputWithPostProcess = postProcess;
  34952. return this;
  34953. };
  34954. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  34955. 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);
  34956. };
  34957. PostProcess.prototype.isReusable = function () {
  34958. return this._reusable;
  34959. };
  34960. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  34961. PostProcess.prototype.markTextureDirty = function () {
  34962. this.width = -1;
  34963. };
  34964. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  34965. var _this = this;
  34966. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  34967. camera = camera || this._camera;
  34968. var scene = camera.getScene();
  34969. var engine = scene.getEngine();
  34970. var maxSize = engine.getCaps().maxTextureSize;
  34971. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  34972. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  34973. var desiredWidth = this._options.width || requiredWidth;
  34974. var desiredHeight = this._options.height || requiredHeight;
  34975. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  34976. if (!this._options.width) {
  34977. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  34978. }
  34979. if (!this._options.height) {
  34980. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  34981. }
  34982. }
  34983. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  34984. if (this._textures.length > 0) {
  34985. for (var i = 0; i < this._textures.length; i++) {
  34986. this._engine._releaseTexture(this._textures.data[i]);
  34987. }
  34988. this._textures.reset();
  34989. }
  34990. this.width = desiredWidth;
  34991. this.height = desiredHeight;
  34992. var textureSize = { width: this.width, height: this.height };
  34993. var textureOptions = {
  34994. generateMipMaps: false,
  34995. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  34996. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  34997. samplingMode: this.renderTargetSamplingMode,
  34998. type: this._textureType
  34999. };
  35000. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35001. if (this._reusable) {
  35002. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35003. }
  35004. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  35005. this.onSizeChangedObservable.notifyObservers(this);
  35006. }
  35007. this._textures.forEach(function (texture) {
  35008. if (texture.samples !== _this.samples) {
  35009. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  35010. }
  35011. });
  35012. }
  35013. var target;
  35014. if (this._shareOutputWithPostProcess) {
  35015. target = this._shareOutputWithPostProcess.outputTexture;
  35016. }
  35017. else if (this._forcedOutputTexture) {
  35018. target = this._forcedOutputTexture;
  35019. this.width = this._forcedOutputTexture.width;
  35020. this.height = this._forcedOutputTexture.height;
  35021. }
  35022. else {
  35023. target = this.outputTexture;
  35024. }
  35025. if (this.enablePixelPerfectMode) {
  35026. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  35027. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  35028. }
  35029. else {
  35030. this._scaleRatio.copyFromFloats(1, 1);
  35031. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  35032. }
  35033. this.onActivateObservable.notifyObservers(camera);
  35034. // Clear
  35035. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  35036. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  35037. }
  35038. if (this._reusable) {
  35039. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  35040. }
  35041. };
  35042. Object.defineProperty(PostProcess.prototype, "isSupported", {
  35043. get: function () {
  35044. return this._effect.isSupported;
  35045. },
  35046. enumerable: true,
  35047. configurable: true
  35048. });
  35049. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  35050. get: function () {
  35051. if (this._shareOutputWithPostProcess) {
  35052. return this._shareOutputWithPostProcess.aspectRatio;
  35053. }
  35054. if (this._forcedOutputTexture) {
  35055. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  35056. }
  35057. return this.width / this.height;
  35058. },
  35059. enumerable: true,
  35060. configurable: true
  35061. });
  35062. PostProcess.prototype.apply = function () {
  35063. // Check
  35064. if (!this._effect || !this._effect.isReady())
  35065. return null;
  35066. // States
  35067. this._engine.enableEffect(this._effect);
  35068. this._engine.setState(false);
  35069. this._engine.setDepthBuffer(false);
  35070. this._engine.setDepthWrite(false);
  35071. // Alpha
  35072. this._engine.setAlphaMode(this.alphaMode);
  35073. if (this.alphaConstants) {
  35074. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  35075. }
  35076. // Texture
  35077. var source;
  35078. if (this._shareOutputWithPostProcess) {
  35079. source = this._shareOutputWithPostProcess.outputTexture;
  35080. }
  35081. else if (this._forcedOutputTexture) {
  35082. source = this._forcedOutputTexture;
  35083. }
  35084. else {
  35085. source = this.outputTexture;
  35086. }
  35087. this._effect._bindTexture("textureSampler", source);
  35088. // Parameters
  35089. this._effect.setVector2("scale", this._scaleRatio);
  35090. this.onApplyObservable.notifyObservers(this._effect);
  35091. return this._effect;
  35092. };
  35093. PostProcess.prototype._disposeTextures = function () {
  35094. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  35095. return;
  35096. }
  35097. if (this._textures.length > 0) {
  35098. for (var i = 0; i < this._textures.length; i++) {
  35099. this._engine._releaseTexture(this._textures.data[i]);
  35100. }
  35101. }
  35102. this._textures.dispose();
  35103. };
  35104. PostProcess.prototype.dispose = function (camera) {
  35105. camera = camera || this._camera;
  35106. this._disposeTextures();
  35107. if (this._scene) {
  35108. var index_1 = this._scene.postProcesses.indexOf(this);
  35109. if (index_1 !== -1) {
  35110. this._scene.postProcesses.splice(index_1, 1);
  35111. }
  35112. }
  35113. else {
  35114. var index_2 = this._engine.postProcesses.indexOf(this);
  35115. if (index_2 !== -1) {
  35116. this._engine.postProcesses.splice(index_2, 1);
  35117. }
  35118. }
  35119. if (!camera) {
  35120. return;
  35121. }
  35122. camera.detachPostProcess(this);
  35123. var index = camera._postProcesses.indexOf(this);
  35124. if (index === 0 && camera._postProcesses.length > 0) {
  35125. this._camera._postProcesses[0].markTextureDirty();
  35126. }
  35127. this.onActivateObservable.clear();
  35128. this.onAfterRenderObservable.clear();
  35129. this.onApplyObservable.clear();
  35130. this.onBeforeRenderObservable.clear();
  35131. this.onSizeChangedObservable.clear();
  35132. };
  35133. return PostProcess;
  35134. }());
  35135. BABYLON.PostProcess = PostProcess;
  35136. })(BABYLON || (BABYLON = {}));
  35137. //# sourceMappingURL=babylon.postProcess.js.map
  35138. var BABYLON;
  35139. (function (BABYLON) {
  35140. var PassPostProcess = (function (_super) {
  35141. __extends(PassPostProcess, _super);
  35142. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  35143. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35144. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  35145. }
  35146. return PassPostProcess;
  35147. }(BABYLON.PostProcess));
  35148. BABYLON.PassPostProcess = PassPostProcess;
  35149. })(BABYLON || (BABYLON = {}));
  35150. //# sourceMappingURL=babylon.passPostProcess.js.map
  35151. var BABYLON;
  35152. (function (BABYLON) {
  35153. var ShadowGenerator = (function () {
  35154. /**
  35155. * Creates a ShadowGenerator object.
  35156. * A ShadowGenerator is the required tool to use the shadows.
  35157. * Each light casting shadows needs to use its own ShadowGenerator.
  35158. * Required parameters :
  35159. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  35160. * - `light`: the light object generating the shadows.
  35161. * - `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.
  35162. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  35163. */
  35164. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  35165. // Members
  35166. this._bias = 0.00005;
  35167. this._blurBoxOffset = 1;
  35168. this._blurScale = 2;
  35169. this._blurKernel = 1;
  35170. this._useKernelBlur = false;
  35171. this._filter = ShadowGenerator.FILTER_NONE;
  35172. this._darkness = 0;
  35173. this._transparencyShadow = false;
  35174. /**
  35175. * Controls the extent to which the shadows fade out at the edge of the frustum
  35176. * Used only by directionals and spots
  35177. */
  35178. this.frustumEdgeFalloff = 0;
  35179. this.forceBackFacesOnly = false;
  35180. this._lightDirection = BABYLON.Vector3.Zero();
  35181. this._viewMatrix = BABYLON.Matrix.Zero();
  35182. this._projectionMatrix = BABYLON.Matrix.Zero();
  35183. this._transformMatrix = BABYLON.Matrix.Zero();
  35184. this._worldViewProjection = BABYLON.Matrix.Zero();
  35185. this._currentFaceIndex = 0;
  35186. this._currentFaceIndexCache = 0;
  35187. this._isCube = false;
  35188. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  35189. this._mapSize = mapSize;
  35190. this._light = light;
  35191. this._scene = light.getScene();
  35192. light._shadowGenerator = this;
  35193. // Texture type fallback from float to int if not supported.
  35194. var caps = this._scene.getEngine().getCaps();
  35195. if (!useFullFloatFirst) {
  35196. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  35197. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  35198. }
  35199. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  35200. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  35201. }
  35202. else {
  35203. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  35204. }
  35205. }
  35206. else {
  35207. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  35208. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  35209. }
  35210. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  35211. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  35212. }
  35213. else {
  35214. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  35215. }
  35216. }
  35217. this._initializeGenerator();
  35218. }
  35219. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  35220. // Static
  35221. get: function () {
  35222. return ShadowGenerator._FILTER_NONE;
  35223. },
  35224. enumerable: true,
  35225. configurable: true
  35226. });
  35227. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  35228. get: function () {
  35229. return ShadowGenerator._FILTER_POISSONSAMPLING;
  35230. },
  35231. enumerable: true,
  35232. configurable: true
  35233. });
  35234. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  35235. get: function () {
  35236. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  35237. },
  35238. enumerable: true,
  35239. configurable: true
  35240. });
  35241. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  35242. get: function () {
  35243. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  35244. },
  35245. enumerable: true,
  35246. configurable: true
  35247. });
  35248. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  35249. get: function () {
  35250. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  35251. },
  35252. enumerable: true,
  35253. configurable: true
  35254. });
  35255. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  35256. get: function () {
  35257. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  35258. },
  35259. enumerable: true,
  35260. configurable: true
  35261. });
  35262. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  35263. get: function () {
  35264. return this._bias;
  35265. },
  35266. set: function (bias) {
  35267. this._bias = bias;
  35268. },
  35269. enumerable: true,
  35270. configurable: true
  35271. });
  35272. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  35273. get: function () {
  35274. return this._blurBoxOffset;
  35275. },
  35276. set: function (value) {
  35277. if (this._blurBoxOffset === value) {
  35278. return;
  35279. }
  35280. this._blurBoxOffset = value;
  35281. this._disposeBlurPostProcesses();
  35282. },
  35283. enumerable: true,
  35284. configurable: true
  35285. });
  35286. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  35287. get: function () {
  35288. return this._blurScale;
  35289. },
  35290. set: function (value) {
  35291. if (this._blurScale === value) {
  35292. return;
  35293. }
  35294. this._blurScale = value;
  35295. this._disposeBlurPostProcesses();
  35296. },
  35297. enumerable: true,
  35298. configurable: true
  35299. });
  35300. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  35301. get: function () {
  35302. return this._blurKernel;
  35303. },
  35304. set: function (value) {
  35305. if (this._blurKernel === value) {
  35306. return;
  35307. }
  35308. this._blurKernel = value;
  35309. this._disposeBlurPostProcesses();
  35310. },
  35311. enumerable: true,
  35312. configurable: true
  35313. });
  35314. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  35315. get: function () {
  35316. return this._useKernelBlur;
  35317. },
  35318. set: function (value) {
  35319. if (this._useKernelBlur === value) {
  35320. return;
  35321. }
  35322. this._useKernelBlur = value;
  35323. this._disposeBlurPostProcesses();
  35324. },
  35325. enumerable: true,
  35326. configurable: true
  35327. });
  35328. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  35329. get: function () {
  35330. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  35331. },
  35332. set: function (value) {
  35333. this._depthScale = value;
  35334. },
  35335. enumerable: true,
  35336. configurable: true
  35337. });
  35338. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  35339. get: function () {
  35340. return this._filter;
  35341. },
  35342. set: function (value) {
  35343. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  35344. if (this._light.needCube()) {
  35345. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  35346. this.useExponentialShadowMap = true;
  35347. return;
  35348. }
  35349. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  35350. this.useCloseExponentialShadowMap = true;
  35351. return;
  35352. }
  35353. }
  35354. if (this._filter === value) {
  35355. return;
  35356. }
  35357. this._filter = value;
  35358. this._disposeBlurPostProcesses();
  35359. this._applyFilterValues();
  35360. this._light._markMeshesAsLightDirty();
  35361. },
  35362. enumerable: true,
  35363. configurable: true
  35364. });
  35365. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  35366. get: function () {
  35367. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  35368. },
  35369. set: function (value) {
  35370. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  35371. return;
  35372. }
  35373. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  35374. },
  35375. enumerable: true,
  35376. configurable: true
  35377. });
  35378. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  35379. get: function () {
  35380. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  35381. return this.useExponentialShadowMap;
  35382. },
  35383. set: function (value) {
  35384. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  35385. this.useExponentialShadowMap = value;
  35386. },
  35387. enumerable: true,
  35388. configurable: true
  35389. });
  35390. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  35391. get: function () {
  35392. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  35393. return this.useBlurExponentialShadowMap;
  35394. },
  35395. set: function (value) {
  35396. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  35397. this.useBlurExponentialShadowMap = value;
  35398. },
  35399. enumerable: true,
  35400. configurable: true
  35401. });
  35402. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  35403. get: function () {
  35404. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  35405. },
  35406. set: function (value) {
  35407. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  35408. return;
  35409. }
  35410. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35411. },
  35412. enumerable: true,
  35413. configurable: true
  35414. });
  35415. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  35416. get: function () {
  35417. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  35418. },
  35419. set: function (value) {
  35420. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  35421. return;
  35422. }
  35423. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35424. },
  35425. enumerable: true,
  35426. configurable: true
  35427. });
  35428. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  35429. get: function () {
  35430. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  35431. },
  35432. set: function (value) {
  35433. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  35434. return;
  35435. }
  35436. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35437. },
  35438. enumerable: true,
  35439. configurable: true
  35440. });
  35441. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  35442. get: function () {
  35443. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  35444. },
  35445. set: function (value) {
  35446. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  35447. return;
  35448. }
  35449. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35450. },
  35451. enumerable: true,
  35452. configurable: true
  35453. });
  35454. /**
  35455. * Returns the darkness value (float).
  35456. */
  35457. ShadowGenerator.prototype.getDarkness = function () {
  35458. return this._darkness;
  35459. };
  35460. /**
  35461. * Sets the ShadowGenerator darkness value (float <= 1.0).
  35462. * Returns the ShadowGenerator.
  35463. */
  35464. ShadowGenerator.prototype.setDarkness = function (darkness) {
  35465. if (darkness >= 1.0)
  35466. this._darkness = 1.0;
  35467. else if (darkness <= 0.0)
  35468. this._darkness = 0.0;
  35469. else
  35470. this._darkness = darkness;
  35471. return this;
  35472. };
  35473. /**
  35474. * Sets the ability to have transparent shadow (boolean).
  35475. * Returns the ShadowGenerator.
  35476. */
  35477. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  35478. this._transparencyShadow = hasShadow;
  35479. return this;
  35480. };
  35481. /**
  35482. * Returns a RenderTargetTexture object : the shadow map texture.
  35483. */
  35484. ShadowGenerator.prototype.getShadowMap = function () {
  35485. return this._shadowMap;
  35486. };
  35487. /**
  35488. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  35489. */
  35490. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  35491. if (this._shadowMap2) {
  35492. return this._shadowMap2;
  35493. }
  35494. return this._shadowMap;
  35495. };
  35496. /**
  35497. * Returns the associated light object.
  35498. */
  35499. ShadowGenerator.prototype.getLight = function () {
  35500. return this._light;
  35501. };
  35502. ShadowGenerator.prototype._initializeGenerator = function () {
  35503. this._light._markMeshesAsLightDirty();
  35504. this._initializeShadowMap();
  35505. };
  35506. ShadowGenerator.prototype._initializeShadowMap = function () {
  35507. var _this = this;
  35508. // Render target
  35509. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  35510. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35511. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35512. this._shadowMap.anisotropicFilteringLevel = 1;
  35513. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35514. this._shadowMap.renderParticles = false;
  35515. // Record Face Index before render.
  35516. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  35517. _this._currentFaceIndex = faceIndex;
  35518. });
  35519. // Custom render function.
  35520. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  35521. // Blur if required afer render.
  35522. this._shadowMap.onAfterUnbindObservable.add(function () {
  35523. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  35524. return;
  35525. }
  35526. if (!_this._blurPostProcesses) {
  35527. _this._initializeBlurRTTAndPostProcesses();
  35528. }
  35529. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  35530. });
  35531. // Clear according to the chosen filter.
  35532. this._shadowMap.onClearObservable.add(function (engine) {
  35533. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  35534. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  35535. }
  35536. else {
  35537. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  35538. }
  35539. });
  35540. };
  35541. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  35542. var _this = this;
  35543. var engine = this._scene.getEngine();
  35544. var targetSize = this._mapSize / this.blurScale;
  35545. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  35546. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  35547. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35548. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35549. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35550. }
  35551. if (this.useKernelBlur) {
  35552. 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);
  35553. this._kernelBlurXPostprocess.width = targetSize;
  35554. this._kernelBlurXPostprocess.height = targetSize;
  35555. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  35556. effect.setTexture("textureSampler", _this._shadowMap);
  35557. });
  35558. 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);
  35559. this._kernelBlurXPostprocess.autoClear = false;
  35560. this._kernelBlurYPostprocess.autoClear = false;
  35561. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35562. this._kernelBlurXPostprocess.packedFloat = true;
  35563. this._kernelBlurYPostprocess.packedFloat = true;
  35564. }
  35565. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  35566. }
  35567. else {
  35568. 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);
  35569. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  35570. effect.setFloat2("screenSize", targetSize, targetSize);
  35571. effect.setTexture("textureSampler", _this._shadowMap);
  35572. });
  35573. this._boxBlurPostprocess.autoClear = false;
  35574. this._blurPostProcesses = [this._boxBlurPostprocess];
  35575. }
  35576. };
  35577. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35578. var index;
  35579. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35580. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  35581. }
  35582. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35583. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  35584. }
  35585. if (this._transparencyShadow) {
  35586. for (index = 0; index < transparentSubMeshes.length; index++) {
  35587. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  35588. }
  35589. }
  35590. };
  35591. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  35592. var _this = this;
  35593. var mesh = subMesh.getRenderingMesh();
  35594. var scene = this._scene;
  35595. var engine = scene.getEngine();
  35596. // Culling
  35597. engine.setState(subMesh.getMaterial().backFaceCulling);
  35598. // Managing instances
  35599. var batch = mesh._getInstancesRenderList(subMesh._id);
  35600. if (batch.mustReturn) {
  35601. return;
  35602. }
  35603. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  35604. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  35605. engine.enableEffect(this._effect);
  35606. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  35607. var material = subMesh.getMaterial();
  35608. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  35609. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  35610. this._effect.setVector3("lightPosition", this.getLight().position);
  35611. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  35612. // Alpha test
  35613. if (material && material.needAlphaTesting()) {
  35614. var alphaTexture = material.getAlphaTestTexture();
  35615. if (alphaTexture) {
  35616. this._effect.setTexture("diffuseSampler", alphaTexture);
  35617. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  35618. }
  35619. }
  35620. // Bones
  35621. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35622. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35623. }
  35624. if (this.forceBackFacesOnly) {
  35625. engine.setState(true, 0, false, true);
  35626. }
  35627. // Draw
  35628. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35629. if (this.forceBackFacesOnly) {
  35630. engine.setState(true, 0, false, false);
  35631. }
  35632. }
  35633. else {
  35634. // Need to reset refresh rate of the shadowMap
  35635. this._shadowMap.resetRefreshCounter();
  35636. }
  35637. };
  35638. ShadowGenerator.prototype._applyFilterValues = function () {
  35639. if (this.filter === ShadowGenerator.FILTER_NONE) {
  35640. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  35641. }
  35642. else {
  35643. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35644. }
  35645. };
  35646. /**
  35647. * Force shader compilation including textures ready check
  35648. */
  35649. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  35650. var _this = this;
  35651. var scene = this._scene;
  35652. var engine = scene.getEngine();
  35653. var subMeshes = new Array();
  35654. var currentIndex = 0;
  35655. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  35656. var mesh = _a[_i];
  35657. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  35658. }
  35659. var checkReady = function () {
  35660. if (!_this._scene || !_this._scene.getEngine()) {
  35661. return;
  35662. }
  35663. var subMesh = subMeshes[currentIndex];
  35664. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  35665. currentIndex++;
  35666. if (currentIndex >= subMeshes.length) {
  35667. if (onCompiled) {
  35668. onCompiled(_this);
  35669. }
  35670. return;
  35671. }
  35672. }
  35673. setTimeout(checkReady, 16);
  35674. };
  35675. if (subMeshes.length > 0) {
  35676. checkReady();
  35677. }
  35678. };
  35679. /**
  35680. * Boolean : true when the ShadowGenerator is finally computed.
  35681. */
  35682. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  35683. var defines = [];
  35684. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35685. defines.push("#define FLOAT");
  35686. }
  35687. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  35688. defines.push("#define ESM");
  35689. }
  35690. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35691. var mesh = subMesh.getMesh();
  35692. var material = subMesh.getMaterial();
  35693. // Alpha test
  35694. if (material && material.needAlphaTesting()) {
  35695. var alphaTexture = material.getAlphaTestTexture();
  35696. if (alphaTexture) {
  35697. defines.push("#define ALPHATEST");
  35698. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35699. attribs.push(BABYLON.VertexBuffer.UVKind);
  35700. defines.push("#define UV1");
  35701. }
  35702. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35703. if (alphaTexture.coordinatesIndex === 1) {
  35704. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35705. defines.push("#define UV2");
  35706. }
  35707. }
  35708. }
  35709. }
  35710. // Bones
  35711. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35712. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35713. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35714. if (mesh.numBoneInfluencers > 4) {
  35715. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35716. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35717. }
  35718. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35719. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35720. }
  35721. else {
  35722. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35723. }
  35724. // Instances
  35725. if (useInstances) {
  35726. defines.push("#define INSTANCES");
  35727. attribs.push("world0");
  35728. attribs.push("world1");
  35729. attribs.push("world2");
  35730. attribs.push("world3");
  35731. }
  35732. // Get correct effect
  35733. var join = defines.join("\n");
  35734. if (this._cachedDefines !== join) {
  35735. this._cachedDefines = join;
  35736. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  35737. }
  35738. return this._effect.isReady();
  35739. };
  35740. /**
  35741. * This creates the defines related to the standard BJS materials.
  35742. */
  35743. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  35744. var scene = this._scene;
  35745. var light = this._light;
  35746. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  35747. return;
  35748. }
  35749. defines["SHADOW" + lightIndex] = true;
  35750. if (this.usePoissonSampling) {
  35751. defines["SHADOWPCF" + lightIndex] = true;
  35752. }
  35753. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  35754. defines["SHADOWESM" + lightIndex] = true;
  35755. }
  35756. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  35757. defines["SHADOWCLOSEESM" + lightIndex] = true;
  35758. }
  35759. if (light.needCube()) {
  35760. defines["SHADOWCUBE" + lightIndex] = true;
  35761. }
  35762. };
  35763. /**
  35764. * This binds shadow lights related to the standard BJS materials.
  35765. * It implies the unifroms available on the materials are the standard BJS ones.
  35766. */
  35767. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  35768. var light = this._light;
  35769. var scene = this._scene;
  35770. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  35771. return;
  35772. }
  35773. if (!light.needCube()) {
  35774. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  35775. }
  35776. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  35777. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  35778. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  35779. };
  35780. // Methods
  35781. /**
  35782. * Returns a Matrix object : the updated transformation matrix.
  35783. */
  35784. ShadowGenerator.prototype.getTransformMatrix = function () {
  35785. var scene = this._scene;
  35786. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  35787. return this._transformMatrix;
  35788. }
  35789. this._currentRenderID = scene.getRenderId();
  35790. this._currentFaceIndexCache = this._currentFaceIndex;
  35791. var lightPosition = this._light.position;
  35792. if (this._light.computeTransformedInformation()) {
  35793. lightPosition = this._light.transformedPosition;
  35794. }
  35795. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  35796. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  35797. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  35798. }
  35799. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  35800. this._cachedPosition = lightPosition.clone();
  35801. this._cachedDirection = this._lightDirection.clone();
  35802. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  35803. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  35804. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  35805. }
  35806. return this._transformMatrix;
  35807. };
  35808. ShadowGenerator.prototype.recreateShadowMap = function () {
  35809. // Track render list.
  35810. var renderList = this._shadowMap.renderList;
  35811. // Clean up existing data.
  35812. this._disposeRTTandPostProcesses();
  35813. // Reinitializes.
  35814. this._initializeGenerator();
  35815. // Reaffect the filter to ensure a correct fallback if necessary.
  35816. this.filter = this.filter;
  35817. // Reaffect the filter.
  35818. this._applyFilterValues();
  35819. // Reaffect Render List.
  35820. this._shadowMap.renderList = renderList;
  35821. };
  35822. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  35823. if (this._shadowMap2) {
  35824. this._shadowMap2.dispose();
  35825. this._shadowMap2 = null;
  35826. }
  35827. if (this._downSamplePostprocess) {
  35828. this._downSamplePostprocess.dispose();
  35829. this._downSamplePostprocess = null;
  35830. }
  35831. if (this._boxBlurPostprocess) {
  35832. this._boxBlurPostprocess.dispose();
  35833. this._boxBlurPostprocess = null;
  35834. }
  35835. if (this._kernelBlurXPostprocess) {
  35836. this._kernelBlurXPostprocess.dispose();
  35837. this._kernelBlurXPostprocess = null;
  35838. }
  35839. if (this._kernelBlurYPostprocess) {
  35840. this._kernelBlurYPostprocess.dispose();
  35841. this._kernelBlurYPostprocess = null;
  35842. }
  35843. this._blurPostProcesses = null;
  35844. };
  35845. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  35846. if (this._shadowMap) {
  35847. this._shadowMap.dispose();
  35848. this._shadowMap = null;
  35849. }
  35850. this._disposeBlurPostProcesses();
  35851. };
  35852. /**
  35853. * Disposes the ShadowGenerator.
  35854. * Returns nothing.
  35855. */
  35856. ShadowGenerator.prototype.dispose = function () {
  35857. this._disposeRTTandPostProcesses();
  35858. this._light._shadowGenerator = null;
  35859. this._light._markMeshesAsLightDirty();
  35860. };
  35861. /**
  35862. * Serializes the ShadowGenerator and returns a serializationObject.
  35863. */
  35864. ShadowGenerator.prototype.serialize = function () {
  35865. var serializationObject = {};
  35866. var shadowMap = this.getShadowMap();
  35867. serializationObject.lightId = this._light.id;
  35868. serializationObject.mapSize = shadowMap.getRenderSize();
  35869. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  35870. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  35871. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  35872. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  35873. serializationObject.usePoissonSampling = this.usePoissonSampling;
  35874. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  35875. serializationObject.depthScale = this.depthScale;
  35876. serializationObject.darkness = this.getDarkness();
  35877. serializationObject.blurBoxOffset = this.blurBoxOffset;
  35878. serializationObject.blurKernel = this.blurKernel;
  35879. serializationObject.blurScale = this.blurScale;
  35880. serializationObject.useKernelBlur = this.useKernelBlur;
  35881. serializationObject.transparencyShadow = this._transparencyShadow;
  35882. serializationObject.renderList = [];
  35883. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  35884. var mesh = shadowMap.renderList[meshIndex];
  35885. serializationObject.renderList.push(mesh.id);
  35886. }
  35887. return serializationObject;
  35888. };
  35889. /**
  35890. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  35891. */
  35892. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  35893. //casting to point light, as light is missing the position attr and typescript complains.
  35894. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  35895. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  35896. var shadowMap = shadowGenerator.getShadowMap();
  35897. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  35898. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  35899. meshes.forEach(function (mesh) {
  35900. shadowMap.renderList.push(mesh);
  35901. });
  35902. }
  35903. if (parsedShadowGenerator.usePoissonSampling) {
  35904. shadowGenerator.usePoissonSampling = true;
  35905. }
  35906. else if (parsedShadowGenerator.useExponentialShadowMap) {
  35907. shadowGenerator.useExponentialShadowMap = true;
  35908. }
  35909. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  35910. shadowGenerator.useBlurExponentialShadowMap = true;
  35911. }
  35912. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  35913. shadowGenerator.useCloseExponentialShadowMap = true;
  35914. }
  35915. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  35916. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  35917. }
  35918. else if (parsedShadowGenerator.useVarianceShadowMap) {
  35919. shadowGenerator.useExponentialShadowMap = true;
  35920. }
  35921. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  35922. shadowGenerator.useBlurExponentialShadowMap = true;
  35923. }
  35924. if (parsedShadowGenerator.depthScale) {
  35925. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  35926. }
  35927. if (parsedShadowGenerator.blurScale) {
  35928. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  35929. }
  35930. if (parsedShadowGenerator.blurBoxOffset) {
  35931. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  35932. }
  35933. if (parsedShadowGenerator.useKernelBlur) {
  35934. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  35935. }
  35936. if (parsedShadowGenerator.blurKernel) {
  35937. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  35938. }
  35939. if (parsedShadowGenerator.bias !== undefined) {
  35940. shadowGenerator.bias = parsedShadowGenerator.bias;
  35941. }
  35942. if (parsedShadowGenerator.darkness) {
  35943. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  35944. }
  35945. if (parsedShadowGenerator.transparencyShadow) {
  35946. shadowGenerator.setTransparencyShadow(true);
  35947. }
  35948. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  35949. return shadowGenerator;
  35950. };
  35951. ShadowGenerator._FILTER_NONE = 0;
  35952. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  35953. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  35954. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  35955. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  35956. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  35957. return ShadowGenerator;
  35958. }());
  35959. BABYLON.ShadowGenerator = ShadowGenerator;
  35960. })(BABYLON || (BABYLON = {}));
  35961. //# sourceMappingURL=babylon.shadowGenerator.js.map
  35962. var BABYLON;
  35963. (function (BABYLON) {
  35964. var ShadowLight = (function (_super) {
  35965. __extends(ShadowLight, _super);
  35966. function ShadowLight() {
  35967. var _this = _super !== null && _super.apply(this, arguments) || this;
  35968. _this._needProjectionMatrixCompute = true;
  35969. return _this;
  35970. }
  35971. Object.defineProperty(ShadowLight.prototype, "direction", {
  35972. get: function () {
  35973. return this._direction;
  35974. },
  35975. set: function (value) {
  35976. this._direction = value;
  35977. },
  35978. enumerable: true,
  35979. configurable: true
  35980. });
  35981. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  35982. get: function () {
  35983. return this._shadowMinZ;
  35984. },
  35985. set: function (value) {
  35986. this._shadowMinZ = value;
  35987. this.forceProjectionMatrixCompute();
  35988. },
  35989. enumerable: true,
  35990. configurable: true
  35991. });
  35992. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  35993. get: function () {
  35994. return this._shadowMaxZ;
  35995. },
  35996. set: function (value) {
  35997. this._shadowMaxZ = value;
  35998. this.forceProjectionMatrixCompute();
  35999. },
  36000. enumerable: true,
  36001. configurable: true
  36002. });
  36003. /**
  36004. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  36005. */
  36006. ShadowLight.prototype.computeTransformedInformation = function () {
  36007. if (this.parent && this.parent.getWorldMatrix) {
  36008. if (!this.transformedPosition) {
  36009. this.transformedPosition = BABYLON.Vector3.Zero();
  36010. }
  36011. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  36012. // In case the direction is present.
  36013. if (this.direction) {
  36014. if (!this.transformedDirection) {
  36015. this.transformedDirection = BABYLON.Vector3.Zero();
  36016. }
  36017. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  36018. }
  36019. return true;
  36020. }
  36021. return false;
  36022. };
  36023. /**
  36024. * Return the depth scale used for the shadow map.
  36025. */
  36026. ShadowLight.prototype.getDepthScale = function () {
  36027. return 50.0;
  36028. };
  36029. /**
  36030. * Returns the light direction (Vector3) for any passed face index.
  36031. */
  36032. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  36033. return this.transformedDirection ? this.transformedDirection : this.direction;
  36034. };
  36035. /**
  36036. * Returns the DirectionalLight absolute position in the World.
  36037. */
  36038. ShadowLight.prototype.getAbsolutePosition = function () {
  36039. return this.transformedPosition ? this.transformedPosition : this.position;
  36040. };
  36041. /**
  36042. * Sets the DirectionalLight direction toward the passed target (Vector3).
  36043. * Returns the updated DirectionalLight direction (Vector3).
  36044. */
  36045. ShadowLight.prototype.setDirectionToTarget = function (target) {
  36046. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  36047. return this.direction;
  36048. };
  36049. /**
  36050. * Returns the light rotation (Vector3).
  36051. */
  36052. ShadowLight.prototype.getRotation = function () {
  36053. this.direction.normalize();
  36054. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  36055. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  36056. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  36057. };
  36058. /**
  36059. * Boolean : false by default.
  36060. */
  36061. ShadowLight.prototype.needCube = function () {
  36062. return false;
  36063. };
  36064. /**
  36065. * Specifies wether or not the projection matrix should be recomputed this frame.
  36066. */
  36067. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  36068. return this._needProjectionMatrixCompute;
  36069. };
  36070. /**
  36071. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  36072. */
  36073. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  36074. this._needProjectionMatrixCompute = true;
  36075. };
  36076. /**
  36077. * Get the world matrix of the sahdow lights.
  36078. */
  36079. ShadowLight.prototype._getWorldMatrix = function () {
  36080. if (!this._worldMatrix) {
  36081. this._worldMatrix = BABYLON.Matrix.Identity();
  36082. }
  36083. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  36084. return this._worldMatrix;
  36085. };
  36086. /**
  36087. * Gets the minZ used for shadow according to both the scene and the light.
  36088. * @param activeCamera
  36089. */
  36090. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  36091. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  36092. };
  36093. /**
  36094. * Gets the maxZ used for shadow according to both the scene and the light.
  36095. * @param activeCamera
  36096. */
  36097. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  36098. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  36099. };
  36100. /**
  36101. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  36102. * Returns the light.
  36103. */
  36104. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36105. if (this.customProjectionMatrixBuilder) {
  36106. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  36107. }
  36108. else {
  36109. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36110. }
  36111. return this;
  36112. };
  36113. __decorate([
  36114. BABYLON.serializeAsVector3()
  36115. ], ShadowLight.prototype, "position", void 0);
  36116. __decorate([
  36117. BABYLON.serializeAsVector3()
  36118. ], ShadowLight.prototype, "direction", null);
  36119. __decorate([
  36120. BABYLON.serialize()
  36121. ], ShadowLight.prototype, "shadowMinZ", null);
  36122. __decorate([
  36123. BABYLON.serialize()
  36124. ], ShadowLight.prototype, "shadowMaxZ", null);
  36125. return ShadowLight;
  36126. }(BABYLON.Light));
  36127. BABYLON.ShadowLight = ShadowLight;
  36128. })(BABYLON || (BABYLON = {}));
  36129. //# sourceMappingURL=babylon.shadowLight.js.map
  36130. var BABYLON;
  36131. (function (BABYLON) {
  36132. var PointLight = (function (_super) {
  36133. __extends(PointLight, _super);
  36134. /**
  36135. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  36136. * A PointLight emits the light in every direction.
  36137. * It can cast shadows.
  36138. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  36139. * ```javascript
  36140. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  36141. * ```
  36142. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36143. */
  36144. function PointLight(name, position, scene) {
  36145. var _this = _super.call(this, name, scene) || this;
  36146. _this._shadowAngle = Math.PI / 2;
  36147. _this.position = position;
  36148. return _this;
  36149. }
  36150. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  36151. /**
  36152. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36153. * This specifies what angle the shadow will use to be created.
  36154. *
  36155. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36156. */
  36157. get: function () {
  36158. return this._shadowAngle;
  36159. },
  36160. /**
  36161. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36162. * This specifies what angle the shadow will use to be created.
  36163. *
  36164. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36165. */
  36166. set: function (value) {
  36167. this._shadowAngle = value;
  36168. this.forceProjectionMatrixCompute();
  36169. },
  36170. enumerable: true,
  36171. configurable: true
  36172. });
  36173. Object.defineProperty(PointLight.prototype, "direction", {
  36174. get: function () {
  36175. return this._direction;
  36176. },
  36177. /**
  36178. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36179. */
  36180. set: function (value) {
  36181. var previousNeedCube = this.needCube();
  36182. this._direction = value;
  36183. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  36184. this._shadowGenerator.recreateShadowMap();
  36185. }
  36186. },
  36187. enumerable: true,
  36188. configurable: true
  36189. });
  36190. /**
  36191. * Returns the string "PointLight"
  36192. */
  36193. PointLight.prototype.getClassName = function () {
  36194. return "PointLight";
  36195. };
  36196. /**
  36197. * Returns the integer 0.
  36198. */
  36199. PointLight.prototype.getTypeID = function () {
  36200. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  36201. };
  36202. /**
  36203. * Specifies wether or not the shadowmap should be a cube texture.
  36204. */
  36205. PointLight.prototype.needCube = function () {
  36206. return !this.direction;
  36207. };
  36208. /**
  36209. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  36210. */
  36211. PointLight.prototype.getShadowDirection = function (faceIndex) {
  36212. if (this.direction) {
  36213. return _super.prototype.getShadowDirection.call(this, faceIndex);
  36214. }
  36215. else {
  36216. switch (faceIndex) {
  36217. case 0:
  36218. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  36219. case 1:
  36220. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  36221. case 2:
  36222. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  36223. case 3:
  36224. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  36225. case 4:
  36226. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  36227. case 5:
  36228. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  36229. }
  36230. }
  36231. return BABYLON.Vector3.Zero();
  36232. };
  36233. /**
  36234. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  36235. * - fov = PI / 2
  36236. * - aspect ratio : 1.0
  36237. * - z-near and far equal to the active camera minZ and maxZ.
  36238. * Returns the PointLight.
  36239. */
  36240. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36241. var activeCamera = this.getScene().activeCamera;
  36242. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36243. };
  36244. PointLight.prototype._buildUniformLayout = function () {
  36245. this._uniformBuffer.addUniform("vLightData", 4);
  36246. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36247. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36248. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36249. this._uniformBuffer.addUniform("depthValues", 2);
  36250. this._uniformBuffer.create();
  36251. };
  36252. /**
  36253. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  36254. * Returns the PointLight.
  36255. */
  36256. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  36257. if (this.computeTransformedInformation()) {
  36258. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  36259. return this;
  36260. }
  36261. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36262. return this;
  36263. };
  36264. __decorate([
  36265. BABYLON.serialize()
  36266. ], PointLight.prototype, "shadowAngle", null);
  36267. return PointLight;
  36268. }(BABYLON.ShadowLight));
  36269. BABYLON.PointLight = PointLight;
  36270. })(BABYLON || (BABYLON = {}));
  36271. //# sourceMappingURL=babylon.pointLight.js.map
  36272. /// <reference path="babylon.light.ts" />
  36273. var BABYLON;
  36274. (function (BABYLON) {
  36275. var DirectionalLight = (function (_super) {
  36276. __extends(DirectionalLight, _super);
  36277. /**
  36278. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36279. * The directional light is emitted from everywhere in the given direction.
  36280. * It can cast shawdows.
  36281. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36282. */
  36283. function DirectionalLight(name, direction, scene) {
  36284. var _this = _super.call(this, name, scene) || this;
  36285. _this._shadowFrustumSize = 0;
  36286. _this._shadowOrthoScale = 0.5;
  36287. _this.autoUpdateExtends = true;
  36288. // Cache
  36289. _this._orthoLeft = Number.MAX_VALUE;
  36290. _this._orthoRight = Number.MIN_VALUE;
  36291. _this._orthoTop = Number.MIN_VALUE;
  36292. _this._orthoBottom = Number.MAX_VALUE;
  36293. _this.position = direction.scale(-1.0);
  36294. _this.direction = direction;
  36295. return _this;
  36296. }
  36297. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36298. /**
  36299. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36300. */
  36301. get: function () {
  36302. return this._shadowFrustumSize;
  36303. },
  36304. /**
  36305. * Specifies a fix frustum size for the shadow generation.
  36306. */
  36307. set: function (value) {
  36308. this._shadowFrustumSize = value;
  36309. this.forceProjectionMatrixCompute();
  36310. },
  36311. enumerable: true,
  36312. configurable: true
  36313. });
  36314. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36315. get: function () {
  36316. return this._shadowOrthoScale;
  36317. },
  36318. set: function (value) {
  36319. this._shadowOrthoScale = value;
  36320. this.forceProjectionMatrixCompute();
  36321. },
  36322. enumerable: true,
  36323. configurable: true
  36324. });
  36325. /**
  36326. * Returns the string "DirectionalLight".
  36327. */
  36328. DirectionalLight.prototype.getClassName = function () {
  36329. return "DirectionalLight";
  36330. };
  36331. /**
  36332. * Returns the integer 1.
  36333. */
  36334. DirectionalLight.prototype.getTypeID = function () {
  36335. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36336. };
  36337. /**
  36338. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36339. * Returns the DirectionalLight Shadow projection matrix.
  36340. */
  36341. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36342. if (this.shadowFrustumSize > 0) {
  36343. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36344. }
  36345. else {
  36346. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36347. }
  36348. };
  36349. /**
  36350. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36351. * Returns the DirectionalLight Shadow projection matrix.
  36352. */
  36353. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36354. var activeCamera = this.getScene().activeCamera;
  36355. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36356. };
  36357. /**
  36358. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36359. * Returns the DirectionalLight Shadow projection matrix.
  36360. */
  36361. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36362. var activeCamera = this.getScene().activeCamera;
  36363. // Check extends
  36364. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36365. var tempVector3 = BABYLON.Vector3.Zero();
  36366. this._orthoLeft = Number.MAX_VALUE;
  36367. this._orthoRight = Number.MIN_VALUE;
  36368. this._orthoTop = Number.MIN_VALUE;
  36369. this._orthoBottom = Number.MAX_VALUE;
  36370. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36371. var mesh = renderList[meshIndex];
  36372. if (!mesh) {
  36373. continue;
  36374. }
  36375. var boundingInfo = mesh.getBoundingInfo();
  36376. if (!boundingInfo) {
  36377. continue;
  36378. }
  36379. var boundingBox = boundingInfo.boundingBox;
  36380. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36381. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36382. if (tempVector3.x < this._orthoLeft)
  36383. this._orthoLeft = tempVector3.x;
  36384. if (tempVector3.y < this._orthoBottom)
  36385. this._orthoBottom = tempVector3.y;
  36386. if (tempVector3.x > this._orthoRight)
  36387. this._orthoRight = tempVector3.x;
  36388. if (tempVector3.y > this._orthoTop)
  36389. this._orthoTop = tempVector3.y;
  36390. }
  36391. }
  36392. }
  36393. var xOffset = this._orthoRight - this._orthoLeft;
  36394. var yOffset = this._orthoTop - this._orthoBottom;
  36395. 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);
  36396. };
  36397. DirectionalLight.prototype._buildUniformLayout = function () {
  36398. this._uniformBuffer.addUniform("vLightData", 4);
  36399. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36400. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36401. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36402. this._uniformBuffer.addUniform("depthValues", 2);
  36403. this._uniformBuffer.create();
  36404. };
  36405. /**
  36406. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36407. * Returns the DirectionalLight.
  36408. */
  36409. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36410. if (this.computeTransformedInformation()) {
  36411. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36412. return this;
  36413. }
  36414. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36415. return this;
  36416. };
  36417. /**
  36418. * Gets the minZ used for shadow according to both the scene and the light.
  36419. *
  36420. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36421. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36422. * @param activeCamera
  36423. */
  36424. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36425. return 1;
  36426. };
  36427. /**
  36428. * Gets the maxZ used for shadow according to both the scene and the light.
  36429. *
  36430. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36431. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36432. * @param activeCamera
  36433. */
  36434. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36435. return 1;
  36436. };
  36437. __decorate([
  36438. BABYLON.serialize()
  36439. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36440. __decorate([
  36441. BABYLON.serialize()
  36442. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36443. __decorate([
  36444. BABYLON.serialize()
  36445. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36446. return DirectionalLight;
  36447. }(BABYLON.ShadowLight));
  36448. BABYLON.DirectionalLight = DirectionalLight;
  36449. })(BABYLON || (BABYLON = {}));
  36450. //# sourceMappingURL=babylon.directionalLight.js.map
  36451. var BABYLON;
  36452. (function (BABYLON) {
  36453. var SpotLight = (function (_super) {
  36454. __extends(SpotLight, _super);
  36455. /**
  36456. * Creates a SpotLight object in the scene with the passed parameters :
  36457. * - `position` (Vector3) is the initial SpotLight position,
  36458. * - `direction` (Vector3) is the initial SpotLight direction,
  36459. * - `angle` (float, in radians) is the spot light cone angle,
  36460. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36461. * A spot light is a simply light oriented cone.
  36462. * It can cast shadows.
  36463. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36464. */
  36465. function SpotLight(name, position, direction, angle, exponent, scene) {
  36466. var _this = _super.call(this, name, scene) || this;
  36467. _this.position = position;
  36468. _this.direction = direction;
  36469. _this.angle = angle;
  36470. _this.exponent = exponent;
  36471. return _this;
  36472. }
  36473. Object.defineProperty(SpotLight.prototype, "angle", {
  36474. get: function () {
  36475. return this._angle;
  36476. },
  36477. set: function (value) {
  36478. this._angle = value;
  36479. this.forceProjectionMatrixCompute();
  36480. },
  36481. enumerable: true,
  36482. configurable: true
  36483. });
  36484. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  36485. get: function () {
  36486. return this._shadowAngleScale;
  36487. },
  36488. /**
  36489. * Allows scaling the angle of the light for shadow generation only.
  36490. */
  36491. set: function (value) {
  36492. this._shadowAngleScale = value;
  36493. this.forceProjectionMatrixCompute();
  36494. },
  36495. enumerable: true,
  36496. configurable: true
  36497. });
  36498. /**
  36499. * Returns the string "SpotLight".
  36500. */
  36501. SpotLight.prototype.getClassName = function () {
  36502. return "SpotLight";
  36503. };
  36504. /**
  36505. * Returns the integer 2.
  36506. */
  36507. SpotLight.prototype.getTypeID = function () {
  36508. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36509. };
  36510. /**
  36511. * 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.
  36512. * Returns the SpotLight.
  36513. */
  36514. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36515. var activeCamera = this.getScene().activeCamera;
  36516. this._shadowAngleScale = this._shadowAngleScale || 1;
  36517. var angle = this._shadowAngleScale * this._angle;
  36518. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36519. };
  36520. SpotLight.prototype._buildUniformLayout = function () {
  36521. this._uniformBuffer.addUniform("vLightData", 4);
  36522. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36523. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36524. this._uniformBuffer.addUniform("vLightDirection", 3);
  36525. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36526. this._uniformBuffer.addUniform("depthValues", 2);
  36527. this._uniformBuffer.create();
  36528. };
  36529. /**
  36530. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36531. * Return the SpotLight.
  36532. */
  36533. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36534. var normalizeDirection;
  36535. if (this.computeTransformedInformation()) {
  36536. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36537. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36538. }
  36539. else {
  36540. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36541. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36542. }
  36543. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36544. return this;
  36545. };
  36546. __decorate([
  36547. BABYLON.serialize()
  36548. ], SpotLight.prototype, "angle", null);
  36549. __decorate([
  36550. BABYLON.serialize()
  36551. /**
  36552. * Allows scaling the angle of the light for shadow generation only.
  36553. */
  36554. ], SpotLight.prototype, "shadowAngleScale", null);
  36555. __decorate([
  36556. BABYLON.serialize()
  36557. ], SpotLight.prototype, "exponent", void 0);
  36558. return SpotLight;
  36559. }(BABYLON.ShadowLight));
  36560. BABYLON.SpotLight = SpotLight;
  36561. })(BABYLON || (BABYLON = {}));
  36562. //# sourceMappingURL=babylon.spotLight.js.map
  36563. var BABYLON;
  36564. (function (BABYLON) {
  36565. var MultiMaterial = (function (_super) {
  36566. __extends(MultiMaterial, _super);
  36567. function MultiMaterial(name, scene) {
  36568. var _this = _super.call(this, name, scene, true) || this;
  36569. scene.multiMaterials.push(_this);
  36570. _this.subMaterials = new Array();
  36571. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  36572. return _this;
  36573. }
  36574. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  36575. get: function () {
  36576. return this._subMaterials;
  36577. },
  36578. set: function (value) {
  36579. this._subMaterials = value;
  36580. this._hookArray(value);
  36581. },
  36582. enumerable: true,
  36583. configurable: true
  36584. });
  36585. MultiMaterial.prototype._hookArray = function (array) {
  36586. var _this = this;
  36587. var oldPush = array.push;
  36588. array.push = function () {
  36589. var items = [];
  36590. for (var _i = 0; _i < arguments.length; _i++) {
  36591. items[_i] = arguments[_i];
  36592. }
  36593. var result = oldPush.apply(array, items);
  36594. _this._markAllSubMeshesAsTexturesDirty();
  36595. return result;
  36596. };
  36597. var oldSplice = array.splice;
  36598. array.splice = function (index, deleteCount) {
  36599. var deleted = oldSplice.apply(array, [index, deleteCount]);
  36600. _this._markAllSubMeshesAsTexturesDirty();
  36601. return deleted;
  36602. };
  36603. };
  36604. // Properties
  36605. MultiMaterial.prototype.getSubMaterial = function (index) {
  36606. if (index < 0 || index >= this.subMaterials.length) {
  36607. return this.getScene().defaultMaterial;
  36608. }
  36609. return this.subMaterials[index];
  36610. };
  36611. MultiMaterial.prototype.getActiveTextures = function () {
  36612. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  36613. var _a;
  36614. };
  36615. // Methods
  36616. MultiMaterial.prototype.getClassName = function () {
  36617. return "MultiMaterial";
  36618. };
  36619. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36620. for (var index = 0; index < this.subMaterials.length; index++) {
  36621. var subMaterial = this.subMaterials[index];
  36622. if (subMaterial) {
  36623. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  36624. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  36625. return false;
  36626. }
  36627. continue;
  36628. }
  36629. if (!this.subMaterials[index].isReady(mesh)) {
  36630. return false;
  36631. }
  36632. }
  36633. }
  36634. return true;
  36635. };
  36636. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  36637. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  36638. for (var index = 0; index < this.subMaterials.length; index++) {
  36639. var subMaterial = null;
  36640. if (cloneChildren) {
  36641. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  36642. }
  36643. else {
  36644. subMaterial = this.subMaterials[index];
  36645. }
  36646. newMultiMaterial.subMaterials.push(subMaterial);
  36647. }
  36648. return newMultiMaterial;
  36649. };
  36650. MultiMaterial.prototype.serialize = function () {
  36651. var serializationObject = {};
  36652. serializationObject.name = this.name;
  36653. serializationObject.id = this.id;
  36654. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36655. serializationObject.materials = [];
  36656. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  36657. var subMat = this.subMaterials[matIndex];
  36658. if (subMat) {
  36659. serializationObject.materials.push(subMat.id);
  36660. }
  36661. else {
  36662. serializationObject.materials.push(null);
  36663. }
  36664. }
  36665. return serializationObject;
  36666. };
  36667. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36668. var scene = this.getScene();
  36669. if (!scene) {
  36670. return;
  36671. }
  36672. var index = scene.multiMaterials.indexOf(this);
  36673. if (index >= 0) {
  36674. scene.multiMaterials.splice(index, 1);
  36675. }
  36676. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36677. };
  36678. return MultiMaterial;
  36679. }(BABYLON.Material));
  36680. BABYLON.MultiMaterial = MultiMaterial;
  36681. })(BABYLON || (BABYLON = {}));
  36682. //# sourceMappingURL=babylon.multiMaterial.js.map
  36683. var BABYLON;
  36684. (function (BABYLON) {
  36685. var PBRMaterialDefines = (function (_super) {
  36686. __extends(PBRMaterialDefines, _super);
  36687. function PBRMaterialDefines() {
  36688. var _this = _super.call(this) || this;
  36689. _this.PBR = true;
  36690. _this.MAINUV1 = false;
  36691. _this.MAINUV2 = false;
  36692. _this.UV1 = false;
  36693. _this.UV2 = false;
  36694. _this.ALBEDO = false;
  36695. _this.ALBEDODIRECTUV = 0;
  36696. _this.VERTEXCOLOR = false;
  36697. _this.AMBIENT = false;
  36698. _this.AMBIENTDIRECTUV = 0;
  36699. _this.AMBIENTINGRAYSCALE = false;
  36700. _this.OPACITY = false;
  36701. _this.VERTEXALPHA = false;
  36702. _this.OPACITYDIRECTUV = 0;
  36703. _this.OPACITYRGB = false;
  36704. _this.ALPHATEST = false;
  36705. _this.ALPHABLEND = false;
  36706. _this.ALPHAFROMALBEDO = false;
  36707. _this.ALPHATESTVALUE = 0.5;
  36708. _this.SPECULAROVERALPHA = false;
  36709. _this.RADIANCEOVERALPHA = false;
  36710. _this.ALPHAFRESNEL = false;
  36711. _this.PREMULTIPLYALPHA = false;
  36712. _this.EMISSIVE = false;
  36713. _this.EMISSIVEDIRECTUV = 0;
  36714. _this.REFLECTIVITY = false;
  36715. _this.REFLECTIVITYDIRECTUV = 0;
  36716. _this.SPECULARTERM = false;
  36717. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36718. _this.MICROSURFACEAUTOMATIC = false;
  36719. _this.LODBASEDMICROSFURACE = false;
  36720. _this.MICROSURFACEMAP = false;
  36721. _this.MICROSURFACEMAPDIRECTUV = 0;
  36722. _this.METALLICWORKFLOW = false;
  36723. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36724. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36725. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36726. _this.AOSTOREINMETALMAPRED = false;
  36727. _this.ENVIRONMENTBRDF = false;
  36728. _this.NORMAL = false;
  36729. _this.TANGENT = false;
  36730. _this.BUMP = false;
  36731. _this.BUMPDIRECTUV = 0;
  36732. _this.PARALLAX = false;
  36733. _this.PARALLAXOCCLUSION = false;
  36734. _this.NORMALXYSCALE = true;
  36735. _this.LIGHTMAP = false;
  36736. _this.LIGHTMAPDIRECTUV = 0;
  36737. _this.USELIGHTMAPASSHADOWMAP = false;
  36738. _this.REFLECTION = false;
  36739. _this.REFLECTIONMAP_3D = false;
  36740. _this.REFLECTIONMAP_SPHERICAL = false;
  36741. _this.REFLECTIONMAP_PLANAR = false;
  36742. _this.REFLECTIONMAP_CUBIC = false;
  36743. _this.REFLECTIONMAP_PROJECTION = false;
  36744. _this.REFLECTIONMAP_SKYBOX = false;
  36745. _this.REFLECTIONMAP_EXPLICIT = false;
  36746. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36747. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36748. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36749. _this.INVERTCUBICMAP = false;
  36750. _this.USESPHERICALFROMREFLECTIONMAP = false;
  36751. _this.USESPHERICALINFRAGMENT = false;
  36752. _this.REFLECTIONMAP_OPPOSITEZ = false;
  36753. _this.LODINREFLECTIONALPHA = false;
  36754. _this.GAMMAREFLECTION = false;
  36755. _this.REFRACTION = false;
  36756. _this.REFRACTIONMAP_3D = false;
  36757. _this.REFRACTIONMAP_OPPOSITEZ = false;
  36758. _this.LODINREFRACTIONALPHA = false;
  36759. _this.GAMMAREFRACTION = false;
  36760. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  36761. _this.INSTANCES = false;
  36762. _this.NUM_BONE_INFLUENCERS = 0;
  36763. _this.BonesPerMesh = 0;
  36764. _this.MORPHTARGETS = false;
  36765. _this.MORPHTARGETS_NORMAL = false;
  36766. _this.MORPHTARGETS_TANGENT = false;
  36767. _this.NUM_MORPH_INFLUENCERS = 0;
  36768. _this.IMAGEPROCESSING = false;
  36769. _this.VIGNETTE = false;
  36770. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36771. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36772. _this.TONEMAPPING = false;
  36773. _this.CONTRAST = false;
  36774. _this.COLORCURVES = false;
  36775. _this.COLORGRADING = false;
  36776. _this.SAMPLER3DGREENDEPTH = false;
  36777. _this.SAMPLER3DBGRMAP = false;
  36778. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36779. _this.EXPOSURE = false;
  36780. _this.USEPHYSICALLIGHTFALLOFF = false;
  36781. _this.TWOSIDEDLIGHTING = false;
  36782. _this.SHADOWFLOAT = false;
  36783. _this.USERIGHTHANDEDSYSTEM = false;
  36784. _this.CLIPPLANE = false;
  36785. _this.POINTSIZE = false;
  36786. _this.FOG = false;
  36787. _this.LOGARITHMICDEPTH = false;
  36788. _this.FORCENORMALFORWARD = false;
  36789. _this.rebuild();
  36790. return _this;
  36791. }
  36792. PBRMaterialDefines.prototype.reset = function () {
  36793. _super.prototype.reset.call(this);
  36794. this.ALPHATESTVALUE = 0.5;
  36795. this.PBR = true;
  36796. };
  36797. return PBRMaterialDefines;
  36798. }(BABYLON.MaterialDefines));
  36799. /**
  36800. * The Physically based material base class of BJS.
  36801. *
  36802. * This offers the main features of a standard PBR material.
  36803. * For more information, please refer to the documentation :
  36804. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36805. */
  36806. var PBRBaseMaterial = (function (_super) {
  36807. __extends(PBRBaseMaterial, _super);
  36808. /**
  36809. * Instantiates a new PBRMaterial instance.
  36810. *
  36811. * @param name The material name
  36812. * @param scene The scene the material will be use in.
  36813. */
  36814. function PBRBaseMaterial(name, scene) {
  36815. var _this = _super.call(this, name, scene) || this;
  36816. /**
  36817. * Intensity of the direct lights e.g. the four lights available in your scene.
  36818. * This impacts both the direct diffuse and specular highlights.
  36819. */
  36820. _this._directIntensity = 1.0;
  36821. /**
  36822. * Intensity of the emissive part of the material.
  36823. * This helps controlling the emissive effect without modifying the emissive color.
  36824. */
  36825. _this._emissiveIntensity = 1.0;
  36826. /**
  36827. * Intensity of the environment e.g. how much the environment will light the object
  36828. * either through harmonics for rough material or through the refelction for shiny ones.
  36829. */
  36830. _this._environmentIntensity = 1.0;
  36831. /**
  36832. * This is a special control allowing the reduction of the specular highlights coming from the
  36833. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36834. */
  36835. _this._specularIntensity = 1.0;
  36836. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  36837. /**
  36838. * Debug Control allowing disabling the bump map on this material.
  36839. */
  36840. _this._disableBumpMap = false;
  36841. /**
  36842. * AKA Occlusion Texture Intensity in other nomenclature.
  36843. */
  36844. _this._ambientTextureStrength = 1.0;
  36845. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  36846. /**
  36847. * AKA Diffuse Color in other nomenclature.
  36848. */
  36849. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  36850. /**
  36851. * AKA Specular Color in other nomenclature.
  36852. */
  36853. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36854. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  36855. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  36856. /**
  36857. * AKA Glossiness in other nomenclature.
  36858. */
  36859. _this._microSurface = 0.9;
  36860. /**
  36861. * source material index of refraction (IOR)' / 'destination material IOR.
  36862. */
  36863. _this._indexOfRefraction = 0.66;
  36864. /**
  36865. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36866. */
  36867. _this._invertRefractionY = false;
  36868. /**
  36869. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36870. * Materials half opaque for instance using refraction could benefit from this control.
  36871. */
  36872. _this._linkRefractionWithTransparency = false;
  36873. _this._useLightmapAsShadowmap = false;
  36874. /**
  36875. * Specifies that the alpha is coming form the albedo channel alpha channel.
  36876. */
  36877. _this._useAlphaFromAlbedoTexture = false;
  36878. /**
  36879. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36880. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36881. */
  36882. _this._useSpecularOverAlpha = true;
  36883. /**
  36884. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36885. */
  36886. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  36887. /**
  36888. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36889. */
  36890. _this._useRoughnessFromMetallicTextureAlpha = true;
  36891. /**
  36892. * Specifies if the metallic texture contains the roughness information in its green channel.
  36893. */
  36894. _this._useRoughnessFromMetallicTextureGreen = false;
  36895. /**
  36896. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36897. */
  36898. _this._useMetallnessFromMetallicTextureBlue = false;
  36899. /**
  36900. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36901. */
  36902. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  36903. /**
  36904. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36905. */
  36906. _this._useAmbientInGrayScale = false;
  36907. /**
  36908. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36909. * The material will try to infer what glossiness each pixel should be.
  36910. */
  36911. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  36912. /**
  36913. * BJS is using an harcoded light falloff based on a manually sets up range.
  36914. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36915. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36916. */
  36917. _this._usePhysicalLightFalloff = true;
  36918. /**
  36919. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36920. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36921. */
  36922. _this._useRadianceOverAlpha = true;
  36923. /**
  36924. * Allows using the bump map in parallax mode.
  36925. */
  36926. _this._useParallax = false;
  36927. /**
  36928. * Allows using the bump map in parallax occlusion mode.
  36929. */
  36930. _this._useParallaxOcclusion = false;
  36931. /**
  36932. * Controls the scale bias of the parallax mode.
  36933. */
  36934. _this._parallaxScaleBias = 0.05;
  36935. /**
  36936. * If sets to true, disables all the lights affecting the material.
  36937. */
  36938. _this._disableLighting = false;
  36939. /**
  36940. * Number of Simultaneous lights allowed on the material.
  36941. */
  36942. _this._maxSimultaneousLights = 4;
  36943. /**
  36944. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  36945. */
  36946. _this._invertNormalMapX = false;
  36947. /**
  36948. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  36949. */
  36950. _this._invertNormalMapY = false;
  36951. /**
  36952. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36953. */
  36954. _this._twoSidedLighting = false;
  36955. /**
  36956. * Defines the alpha limits in alpha test mode.
  36957. */
  36958. _this._alphaCutOff = 0.4;
  36959. /**
  36960. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36961. */
  36962. _this._forceAlphaTest = false;
  36963. /**
  36964. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  36965. * in your scene composition.
  36966. */
  36967. _this._preMultiplyAlpha = false;
  36968. /**
  36969. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36970. * And/Or occlude the blended part.
  36971. */
  36972. _this._useAlphaFresnel = false;
  36973. /**
  36974. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36975. * from cos thetav and roughness:
  36976. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36977. */
  36978. _this._environmentBRDFTexture = null;
  36979. /**
  36980. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36981. */
  36982. _this._forceIrradianceInFragment = false;
  36983. /**
  36984. * Force normal to face away from face.
  36985. * (Temporary internal fix to remove before 3.1)
  36986. */
  36987. _this._forceNormalForward = false;
  36988. _this._renderTargets = new BABYLON.SmartArray(16);
  36989. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  36990. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36991. _this._tempColor = new BABYLON.Color3();
  36992. // Setup the default processing configuration to the scene.
  36993. _this._attachImageProcessingConfiguration(null);
  36994. _this.getRenderTargetTextures = function () {
  36995. _this._renderTargets.reset();
  36996. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36997. _this._renderTargets.push(_this._reflectionTexture);
  36998. }
  36999. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  37000. _this._renderTargets.push(_this._refractionTexture);
  37001. }
  37002. return _this._renderTargets;
  37003. };
  37004. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37005. return _this;
  37006. }
  37007. /**
  37008. * Attaches a new image processing configuration to the PBR Material.
  37009. * @param configuration
  37010. */
  37011. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  37012. var _this = this;
  37013. if (configuration === this._imageProcessingConfiguration) {
  37014. return;
  37015. }
  37016. // Detaches observer.
  37017. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37018. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37019. }
  37020. // Pick the scene configuration if needed.
  37021. if (!configuration) {
  37022. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  37023. }
  37024. else {
  37025. this._imageProcessingConfiguration = configuration;
  37026. }
  37027. // Attaches observer.
  37028. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  37029. _this._markAllSubMeshesAsImageProcessingDirty();
  37030. });
  37031. };
  37032. PBRBaseMaterial.prototype.getClassName = function () {
  37033. return "PBRBaseMaterial";
  37034. };
  37035. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  37036. get: function () {
  37037. return this._useLogarithmicDepth;
  37038. },
  37039. set: function (value) {
  37040. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37041. },
  37042. enumerable: true,
  37043. configurable: true
  37044. });
  37045. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  37046. if (this._linkRefractionWithTransparency) {
  37047. return false;
  37048. }
  37049. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  37050. };
  37051. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  37052. if (this._forceAlphaTest) {
  37053. return true;
  37054. }
  37055. if (this._linkRefractionWithTransparency) {
  37056. return false;
  37057. }
  37058. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  37059. };
  37060. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  37061. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  37062. };
  37063. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  37064. return this._albedoTexture;
  37065. };
  37066. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37067. if (this.isFrozen) {
  37068. if (this._wasPreviouslyReady) {
  37069. return true;
  37070. }
  37071. }
  37072. if (!subMesh._materialDefines) {
  37073. subMesh._materialDefines = new PBRMaterialDefines();
  37074. }
  37075. var scene = this.getScene();
  37076. var defines = subMesh._materialDefines;
  37077. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37078. if (defines._renderId === scene.getRenderId()) {
  37079. return true;
  37080. }
  37081. }
  37082. var engine = scene.getEngine();
  37083. // Lights
  37084. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37085. defines._needNormals = true;
  37086. // Textures
  37087. if (defines._areTexturesDirty) {
  37088. defines._needUVs = false;
  37089. if (scene.texturesEnabled) {
  37090. if (scene.getEngine().getCaps().textureLOD) {
  37091. defines.LODBASEDMICROSFURACE = true;
  37092. }
  37093. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37094. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  37095. return false;
  37096. }
  37097. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  37098. }
  37099. else {
  37100. defines.ALBEDO = false;
  37101. }
  37102. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37103. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37104. return false;
  37105. }
  37106. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37107. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  37108. }
  37109. else {
  37110. defines.AMBIENT = false;
  37111. }
  37112. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37113. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37114. return false;
  37115. }
  37116. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37117. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37118. }
  37119. else {
  37120. defines.OPACITY = false;
  37121. }
  37122. var reflectionTexture = this._getReflectionTexture();
  37123. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37124. if (!reflectionTexture.isReadyOrNotBlocking()) {
  37125. return false;
  37126. }
  37127. defines.REFLECTION = true;
  37128. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  37129. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  37130. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37131. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  37132. defines.INVERTCUBICMAP = true;
  37133. }
  37134. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  37135. switch (reflectionTexture.coordinatesMode) {
  37136. case BABYLON.Texture.CUBIC_MODE:
  37137. case BABYLON.Texture.INVCUBIC_MODE:
  37138. defines.REFLECTIONMAP_CUBIC = true;
  37139. break;
  37140. case BABYLON.Texture.EXPLICIT_MODE:
  37141. defines.REFLECTIONMAP_EXPLICIT = true;
  37142. break;
  37143. case BABYLON.Texture.PLANAR_MODE:
  37144. defines.REFLECTIONMAP_PLANAR = true;
  37145. break;
  37146. case BABYLON.Texture.PROJECTION_MODE:
  37147. defines.REFLECTIONMAP_PROJECTION = true;
  37148. break;
  37149. case BABYLON.Texture.SKYBOX_MODE:
  37150. defines.REFLECTIONMAP_SKYBOX = true;
  37151. break;
  37152. case BABYLON.Texture.SPHERICAL_MODE:
  37153. defines.REFLECTIONMAP_SPHERICAL = true;
  37154. break;
  37155. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37156. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  37157. break;
  37158. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37159. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  37160. break;
  37161. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37162. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  37163. break;
  37164. }
  37165. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37166. if (reflectionTexture.sphericalPolynomial) {
  37167. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37168. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37169. defines.USESPHERICALINFRAGMENT = true;
  37170. }
  37171. }
  37172. }
  37173. }
  37174. else {
  37175. defines.REFLECTION = false;
  37176. defines.REFLECTIONMAP_3D = false;
  37177. defines.REFLECTIONMAP_SPHERICAL = false;
  37178. defines.REFLECTIONMAP_PLANAR = false;
  37179. defines.REFLECTIONMAP_CUBIC = false;
  37180. defines.REFLECTIONMAP_PROJECTION = false;
  37181. defines.REFLECTIONMAP_SKYBOX = false;
  37182. defines.REFLECTIONMAP_EXPLICIT = false;
  37183. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37184. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37185. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37186. defines.INVERTCUBICMAP = false;
  37187. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37188. defines.USESPHERICALINFRAGMENT = false;
  37189. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37190. defines.LODINREFLECTIONALPHA = false;
  37191. defines.GAMMAREFLECTION = false;
  37192. }
  37193. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37194. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37195. return false;
  37196. }
  37197. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37198. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37199. }
  37200. else {
  37201. defines.LIGHTMAP = false;
  37202. }
  37203. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37204. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37205. return false;
  37206. }
  37207. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37208. }
  37209. else {
  37210. defines.EMISSIVE = false;
  37211. }
  37212. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37213. if (this._metallicTexture) {
  37214. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37215. return false;
  37216. }
  37217. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37218. defines.METALLICWORKFLOW = true;
  37219. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37220. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37221. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37222. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37223. }
  37224. else if (this._reflectivityTexture) {
  37225. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37226. return false;
  37227. }
  37228. defines.METALLICWORKFLOW = false;
  37229. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37230. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37231. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37232. }
  37233. else {
  37234. defines.METALLICWORKFLOW = false;
  37235. defines.REFLECTIVITY = false;
  37236. }
  37237. if (this._microSurfaceTexture) {
  37238. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37239. return false;
  37240. }
  37241. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37242. }
  37243. else {
  37244. defines.MICROSURFACEMAP = false;
  37245. }
  37246. }
  37247. else {
  37248. defines.REFLECTIVITY = false;
  37249. defines.MICROSURFACEMAP = false;
  37250. }
  37251. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37252. // Bump texure can not be none blocking.
  37253. if (!this._bumpTexture.isReady()) {
  37254. return false;
  37255. }
  37256. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37257. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37258. defines.PARALLAX = true;
  37259. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  37260. }
  37261. else {
  37262. defines.PARALLAX = false;
  37263. }
  37264. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  37265. }
  37266. else {
  37267. defines.BUMP = false;
  37268. }
  37269. var refractionTexture = this._getRefractionTexture();
  37270. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37271. if (!refractionTexture.isReadyOrNotBlocking()) {
  37272. return false;
  37273. }
  37274. defines.REFRACTION = true;
  37275. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  37276. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  37277. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  37278. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37279. if (this._linkRefractionWithTransparency) {
  37280. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  37281. }
  37282. }
  37283. else {
  37284. defines.REFRACTION = false;
  37285. }
  37286. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37287. // This is blocking.
  37288. if (!this._environmentBRDFTexture.isReady()) {
  37289. return false;
  37290. }
  37291. defines.ENVIRONMENTBRDF = true;
  37292. }
  37293. if (this._shouldUseAlphaFromAlbedoTexture()) {
  37294. defines.ALPHAFROMALBEDO = true;
  37295. }
  37296. }
  37297. if (this._useSpecularOverAlpha) {
  37298. defines.SPECULAROVERALPHA = true;
  37299. }
  37300. if (this._usePhysicalLightFalloff) {
  37301. defines.USEPHYSICALLIGHTFALLOFF = true;
  37302. }
  37303. if (this._useRadianceOverAlpha) {
  37304. defines.RADIANCEOVERALPHA = true;
  37305. }
  37306. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  37307. defines.METALLICWORKFLOW = true;
  37308. }
  37309. if (!this.backFaceCulling && this._twoSidedLighting) {
  37310. defines.TWOSIDEDLIGHTING = true;
  37311. }
  37312. defines.ALPHATESTVALUE = this._alphaCutOff;
  37313. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  37314. defines.ALPHABLEND = this.needAlphaBlending();
  37315. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  37316. }
  37317. if (defines._areImageProcessingDirty) {
  37318. if (!this._imageProcessingConfiguration.isReady()) {
  37319. return false;
  37320. }
  37321. this._imageProcessingConfiguration.prepareDefines(defines);
  37322. }
  37323. defines.FORCENORMALFORWARD = this._forceNormalForward;
  37324. // Misc.
  37325. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  37326. // Values that need to be evaluated on every frame
  37327. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  37328. // Attribs
  37329. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  37330. if (mesh) {
  37331. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37332. mesh.createNormals(true);
  37333. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  37334. }
  37335. }
  37336. }
  37337. // Get correct effect
  37338. if (defines.isDirty) {
  37339. defines.markAsProcessed();
  37340. scene.resetCachedMaterial();
  37341. // Fallbacks
  37342. var fallbacks = new BABYLON.EffectFallbacks();
  37343. if (defines.ENVIRONMENTBRDF) {
  37344. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  37345. }
  37346. if (defines.REFLECTION) {
  37347. fallbacks.addFallback(0, "REFLECTION");
  37348. }
  37349. if (defines.REFRACTION) {
  37350. fallbacks.addFallback(0, "REFRACTION");
  37351. }
  37352. if (defines.REFLECTIVITY) {
  37353. fallbacks.addFallback(0, "REFLECTIVITY");
  37354. }
  37355. if (defines.BUMP) {
  37356. fallbacks.addFallback(0, "BUMP");
  37357. }
  37358. if (defines.PARALLAX) {
  37359. fallbacks.addFallback(1, "PARALLAX");
  37360. }
  37361. if (defines.PARALLAXOCCLUSION) {
  37362. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37363. }
  37364. if (defines.SPECULAROVERALPHA) {
  37365. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37366. }
  37367. if (defines.FOG) {
  37368. fallbacks.addFallback(1, "FOG");
  37369. }
  37370. if (defines.POINTSIZE) {
  37371. fallbacks.addFallback(0, "POINTSIZE");
  37372. }
  37373. if (defines.LOGARITHMICDEPTH) {
  37374. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37375. }
  37376. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37377. if (defines.SPECULARTERM) {
  37378. fallbacks.addFallback(0, "SPECULARTERM");
  37379. }
  37380. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37381. fallbacks.addCPUSkinningFallback(0, mesh);
  37382. }
  37383. //Attributes
  37384. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37385. if (defines.NORMAL) {
  37386. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37387. }
  37388. if (defines.TANGENT) {
  37389. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37390. }
  37391. if (defines.UV1) {
  37392. attribs.push(BABYLON.VertexBuffer.UVKind);
  37393. }
  37394. if (defines.UV2) {
  37395. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37396. }
  37397. if (defines.VERTEXCOLOR) {
  37398. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37399. }
  37400. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37401. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37402. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37403. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  37404. "vFogInfos", "vFogColor", "pointSize",
  37405. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37406. "mBones",
  37407. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37408. "vLightingIntensity",
  37409. "logarithmicDepthConstant",
  37410. "vSphericalX", "vSphericalY", "vSphericalZ",
  37411. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  37412. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  37413. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  37414. "vNormalReoderParams"
  37415. ];
  37416. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  37417. "bumpSampler", "lightmapSampler", "opacitySampler",
  37418. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  37419. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  37420. "microSurfaceSampler", "environmentBrdfSampler"];
  37421. var uniformBuffers = ["Material", "Scene"];
  37422. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37423. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37424. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37425. uniformsNames: uniforms,
  37426. uniformBuffersNames: uniformBuffers,
  37427. samplers: samplers,
  37428. defines: defines,
  37429. maxSimultaneousLights: this._maxSimultaneousLights
  37430. });
  37431. var onCompiled = function (effect) {
  37432. if (this.onCompiled) {
  37433. this.onCompiled(effect);
  37434. }
  37435. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  37436. }.bind(this);
  37437. var join = defines.toString();
  37438. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  37439. attributes: attribs,
  37440. uniformsNames: uniforms,
  37441. uniformBuffersNames: uniformBuffers,
  37442. samplers: samplers,
  37443. defines: join,
  37444. fallbacks: fallbacks,
  37445. onCompiled: onCompiled,
  37446. onError: this.onError,
  37447. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37448. }, engine), defines);
  37449. this.buildUniformLayout();
  37450. }
  37451. if (!subMesh.effect.isReady()) {
  37452. return false;
  37453. }
  37454. defines._renderId = scene.getRenderId();
  37455. this._wasPreviouslyReady = true;
  37456. return true;
  37457. };
  37458. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37459. // Order is important !
  37460. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37461. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37462. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37463. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37464. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37465. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37466. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37467. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37468. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37469. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37470. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37471. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37472. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37473. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37474. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37475. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37476. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37477. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37478. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  37479. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37480. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37481. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37482. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37483. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37484. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37485. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37486. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37487. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37488. this._uniformBuffer.addUniform("pointSize", 1);
  37489. this._uniformBuffer.create();
  37490. };
  37491. PBRBaseMaterial.prototype.unbind = function () {
  37492. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37493. this._uniformBuffer.setTexture("reflectionSampler", null);
  37494. }
  37495. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37496. this._uniformBuffer.setTexture("refractionSampler", null);
  37497. }
  37498. _super.prototype.unbind.call(this);
  37499. };
  37500. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37501. this._activeEffect.setMatrix("world", world);
  37502. };
  37503. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37504. var scene = this.getScene();
  37505. var defines = subMesh._materialDefines;
  37506. if (!defines) {
  37507. return;
  37508. }
  37509. var effect = subMesh.effect;
  37510. this._activeEffect = effect;
  37511. // Matrices
  37512. this.bindOnlyWorldMatrix(world);
  37513. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37514. // Bones
  37515. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37516. if (mustRebind) {
  37517. this._uniformBuffer.bindToEffect(effect, "Material");
  37518. this.bindViewProjection(effect);
  37519. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37520. // Texture uniforms
  37521. if (scene.texturesEnabled) {
  37522. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37523. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37524. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37525. }
  37526. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37527. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37528. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37529. }
  37530. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37531. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37532. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37533. }
  37534. var reflectionTexture = this._getReflectionTexture();
  37535. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37536. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37537. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37538. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37539. var polynomials = reflectionTexture.sphericalPolynomial;
  37540. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37541. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37542. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37543. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37544. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37545. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37546. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37547. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37548. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37549. }
  37550. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37551. }
  37552. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37553. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37554. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37555. }
  37556. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37557. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37558. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37559. }
  37560. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37561. if (this._metallicTexture) {
  37562. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37563. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37564. }
  37565. else if (this._reflectivityTexture) {
  37566. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37567. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37568. }
  37569. if (this._microSurfaceTexture) {
  37570. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37571. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37572. }
  37573. }
  37574. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37575. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37576. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37577. if (scene._mirroredCameraPosition) {
  37578. 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);
  37579. }
  37580. else {
  37581. 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);
  37582. }
  37583. }
  37584. var refractionTexture = this._getRefractionTexture();
  37585. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37586. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37587. var depth = 1.0;
  37588. if (!refractionTexture.isCube) {
  37589. if (refractionTexture.depth) {
  37590. depth = refractionTexture.depth;
  37591. }
  37592. }
  37593. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37594. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37595. }
  37596. }
  37597. // Point size
  37598. if (this.pointsCloud) {
  37599. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37600. }
  37601. // Colors
  37602. if (defines.METALLICWORKFLOW) {
  37603. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37604. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37605. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37606. }
  37607. else {
  37608. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37609. }
  37610. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37611. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37612. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37613. // Misc
  37614. this._lightingInfos.x = this._directIntensity;
  37615. this._lightingInfos.y = this._emissiveIntensity;
  37616. this._lightingInfos.z = this._environmentIntensity;
  37617. this._lightingInfos.w = this._specularIntensity;
  37618. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37619. }
  37620. // Textures
  37621. if (scene.texturesEnabled) {
  37622. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37623. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37624. }
  37625. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37626. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37627. }
  37628. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37629. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37630. }
  37631. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37632. if (defines.LODBASEDMICROSFURACE) {
  37633. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37634. }
  37635. else {
  37636. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37637. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37638. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37639. }
  37640. }
  37641. if (defines.ENVIRONMENTBRDF) {
  37642. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37643. }
  37644. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37645. if (defines.LODBASEDMICROSFURACE) {
  37646. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37647. }
  37648. else {
  37649. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37650. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37651. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37652. }
  37653. }
  37654. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37655. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37656. }
  37657. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37658. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37659. }
  37660. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37661. if (this._metallicTexture) {
  37662. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37663. }
  37664. else if (this._reflectivityTexture) {
  37665. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37666. }
  37667. if (this._microSurfaceTexture) {
  37668. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37669. }
  37670. }
  37671. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37672. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37673. }
  37674. }
  37675. // Clip plane
  37676. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37677. // Colors
  37678. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37679. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  37680. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  37681. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37682. }
  37683. if (mustRebind || !this.isFrozen) {
  37684. // Lights
  37685. if (scene.lightsEnabled && !this._disableLighting) {
  37686. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37687. }
  37688. // View
  37689. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37690. this.bindView(effect);
  37691. }
  37692. // Fog
  37693. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37694. // Morph targets
  37695. if (defines.NUM_MORPH_INFLUENCERS) {
  37696. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37697. }
  37698. // image processing
  37699. this._imageProcessingConfiguration.bind(this._activeEffect);
  37700. // Log. depth
  37701. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37702. }
  37703. this._uniformBuffer.update();
  37704. this._afterBind(mesh);
  37705. scene = null;
  37706. };
  37707. PBRBaseMaterial.prototype.getAnimatables = function () {
  37708. var results = [];
  37709. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37710. results.push(this._albedoTexture);
  37711. }
  37712. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37713. results.push(this._ambientTexture);
  37714. }
  37715. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37716. results.push(this._opacityTexture);
  37717. }
  37718. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37719. results.push(this._reflectionTexture);
  37720. }
  37721. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37722. results.push(this._emissiveTexture);
  37723. }
  37724. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37725. results.push(this._metallicTexture);
  37726. }
  37727. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37728. results.push(this._reflectivityTexture);
  37729. }
  37730. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37731. results.push(this._bumpTexture);
  37732. }
  37733. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37734. results.push(this._lightmapTexture);
  37735. }
  37736. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37737. results.push(this._refractionTexture);
  37738. }
  37739. return results;
  37740. };
  37741. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  37742. if (this._reflectionTexture) {
  37743. return this._reflectionTexture;
  37744. }
  37745. return this.getScene().environmentTexture;
  37746. };
  37747. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  37748. if (this._refractionTexture) {
  37749. return this._refractionTexture;
  37750. }
  37751. if (this._linkRefractionWithTransparency) {
  37752. return this.getScene().environmentTexture;
  37753. }
  37754. return null;
  37755. };
  37756. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37757. if (forceDisposeTextures) {
  37758. if (this._albedoTexture) {
  37759. this._albedoTexture.dispose();
  37760. }
  37761. if (this._ambientTexture) {
  37762. this._ambientTexture.dispose();
  37763. }
  37764. if (this._opacityTexture) {
  37765. this._opacityTexture.dispose();
  37766. }
  37767. if (this._reflectionTexture) {
  37768. this._reflectionTexture.dispose();
  37769. }
  37770. if (this._environmentBRDFTexture) {
  37771. this._environmentBRDFTexture.dispose();
  37772. }
  37773. if (this._emissiveTexture) {
  37774. this._emissiveTexture.dispose();
  37775. }
  37776. if (this._metallicTexture) {
  37777. this._metallicTexture.dispose();
  37778. }
  37779. if (this._reflectivityTexture) {
  37780. this._reflectivityTexture.dispose();
  37781. }
  37782. if (this._bumpTexture) {
  37783. this._bumpTexture.dispose();
  37784. }
  37785. if (this._lightmapTexture) {
  37786. this._lightmapTexture.dispose();
  37787. }
  37788. if (this._refractionTexture) {
  37789. this._refractionTexture.dispose();
  37790. }
  37791. }
  37792. this._renderTargets.dispose();
  37793. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37794. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37795. }
  37796. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37797. };
  37798. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37799. __decorate([
  37800. BABYLON.serializeAsImageProcessingConfiguration()
  37801. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37802. __decorate([
  37803. BABYLON.serialize()
  37804. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37805. return PBRBaseMaterial;
  37806. }(BABYLON.PushMaterial));
  37807. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37808. })(BABYLON || (BABYLON = {}));
  37809. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37810. var BABYLON;
  37811. (function (BABYLON) {
  37812. var Internals;
  37813. (function (Internals) {
  37814. /**
  37815. * The Physically based simple base material of BJS.
  37816. *
  37817. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37818. * It is used as the base class for both the specGloss and metalRough conventions.
  37819. */
  37820. var PBRBaseSimpleMaterial = (function (_super) {
  37821. __extends(PBRBaseSimpleMaterial, _super);
  37822. /**
  37823. * Instantiates a new PBRMaterial instance.
  37824. *
  37825. * @param name The material name
  37826. * @param scene The scene the material will be use in.
  37827. */
  37828. function PBRBaseSimpleMaterial(name, scene) {
  37829. var _this = _super.call(this, name, scene) || this;
  37830. /**
  37831. * Number of Simultaneous lights allowed on the material.
  37832. */
  37833. _this.maxSimultaneousLights = 4;
  37834. /**
  37835. * If sets to true, disables all the lights affecting the material.
  37836. */
  37837. _this.disableLighting = false;
  37838. /**
  37839. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37840. */
  37841. _this.invertNormalMapX = false;
  37842. /**
  37843. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37844. */
  37845. _this.invertNormalMapY = false;
  37846. /**
  37847. * Emissivie color used to self-illuminate the model.
  37848. */
  37849. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37850. /**
  37851. * Occlusion Channel Strenght.
  37852. */
  37853. _this.occlusionStrength = 1.0;
  37854. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  37855. _this._useAmbientInGrayScale = true;
  37856. return _this;
  37857. }
  37858. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  37859. /**
  37860. * Gets the current transparency mode.
  37861. */
  37862. get: function () {
  37863. return this._transparencyMode;
  37864. },
  37865. /**
  37866. * Sets the transparency mode of the material.
  37867. */
  37868. set: function (value) {
  37869. if (this._transparencyMode === value) {
  37870. return;
  37871. }
  37872. this._transparencyMode = value;
  37873. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  37874. this._forceAlphaTest = true;
  37875. }
  37876. else {
  37877. this._forceAlphaTest = false;
  37878. }
  37879. this._markAllSubMeshesAsTexturesDirty();
  37880. },
  37881. enumerable: true,
  37882. configurable: true
  37883. });
  37884. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37885. /**
  37886. * Gets the current double sided mode.
  37887. */
  37888. get: function () {
  37889. return this._twoSidedLighting;
  37890. },
  37891. /**
  37892. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37893. */
  37894. set: function (value) {
  37895. if (this._twoSidedLighting === value) {
  37896. return;
  37897. }
  37898. this._twoSidedLighting = value;
  37899. this.backFaceCulling = !value;
  37900. this._markAllSubMeshesAsTexturesDirty();
  37901. },
  37902. enumerable: true,
  37903. configurable: true
  37904. });
  37905. /**
  37906. * Specifies wether or not the alpha value of the albedo texture should be used.
  37907. */
  37908. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  37909. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  37910. };
  37911. /**
  37912. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  37913. */
  37914. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  37915. if (this._linkRefractionWithTransparency) {
  37916. return false;
  37917. }
  37918. return (this.alpha < 1.0) ||
  37919. (this._shouldUseAlphaFromAlbedoTexture() &&
  37920. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  37921. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  37922. };
  37923. /**
  37924. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  37925. */
  37926. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  37927. if (this._linkRefractionWithTransparency) {
  37928. return false;
  37929. }
  37930. return this._shouldUseAlphaFromAlbedoTexture() &&
  37931. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  37932. };
  37933. /**
  37934. * Return the active textures of the material.
  37935. */
  37936. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37937. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37938. if (this.environmentTexture) {
  37939. activeTextures.push(this.environmentTexture);
  37940. }
  37941. if (this.normalTexture) {
  37942. activeTextures.push(this.normalTexture);
  37943. }
  37944. if (this.emissiveTexture) {
  37945. activeTextures.push(this.emissiveTexture);
  37946. }
  37947. if (this.occlusionTexture) {
  37948. activeTextures.push(this.occlusionTexture);
  37949. }
  37950. return activeTextures;
  37951. };
  37952. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37953. return "PBRBaseSimpleMaterial";
  37954. };
  37955. __decorate([
  37956. BABYLON.serialize(),
  37957. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37958. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37959. __decorate([
  37960. BABYLON.serialize(),
  37961. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37962. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37963. __decorate([
  37964. BABYLON.serializeAsTexture(),
  37965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37966. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37967. __decorate([
  37968. BABYLON.serialize(),
  37969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37970. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37971. __decorate([
  37972. BABYLON.serialize(),
  37973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37974. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37975. __decorate([
  37976. BABYLON.serializeAsTexture(),
  37977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37978. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37979. __decorate([
  37980. BABYLON.serializeAsColor3("emissive"),
  37981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37982. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37983. __decorate([
  37984. BABYLON.serializeAsTexture(),
  37985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37986. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37987. __decorate([
  37988. BABYLON.serialize(),
  37989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37990. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37991. __decorate([
  37992. BABYLON.serializeAsTexture(),
  37993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37994. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37995. __decorate([
  37996. BABYLON.serialize(),
  37997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37998. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37999. __decorate([
  38000. BABYLON.serialize()
  38001. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  38002. __decorate([
  38003. BABYLON.serialize()
  38004. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  38005. return PBRBaseSimpleMaterial;
  38006. }(BABYLON.PBRBaseMaterial));
  38007. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  38008. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38009. })(BABYLON || (BABYLON = {}));
  38010. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  38011. var BABYLON;
  38012. (function (BABYLON) {
  38013. /**
  38014. * The Physically based material of BJS.
  38015. *
  38016. * This offers the main features of a standard PBR material.
  38017. * For more information, please refer to the documentation :
  38018. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38019. */
  38020. var PBRMaterial = (function (_super) {
  38021. __extends(PBRMaterial, _super);
  38022. /**
  38023. * Instantiates a new PBRMaterial instance.
  38024. *
  38025. * @param name The material name
  38026. * @param scene The scene the material will be use in.
  38027. */
  38028. function PBRMaterial(name, scene) {
  38029. var _this = _super.call(this, name, scene) || this;
  38030. /**
  38031. * Intensity of the direct lights e.g. the four lights available in your scene.
  38032. * This impacts both the direct diffuse and specular highlights.
  38033. */
  38034. _this.directIntensity = 1.0;
  38035. /**
  38036. * Intensity of the emissive part of the material.
  38037. * This helps controlling the emissive effect without modifying the emissive color.
  38038. */
  38039. _this.emissiveIntensity = 1.0;
  38040. /**
  38041. * Intensity of the environment e.g. how much the environment will light the object
  38042. * either through harmonics for rough material or through the refelction for shiny ones.
  38043. */
  38044. _this.environmentIntensity = 1.0;
  38045. /**
  38046. * This is a special control allowing the reduction of the specular highlights coming from the
  38047. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38048. */
  38049. _this.specularIntensity = 1.0;
  38050. /**
  38051. * Debug Control allowing disabling the bump map on this material.
  38052. */
  38053. _this.disableBumpMap = false;
  38054. /**
  38055. * AKA Occlusion Texture Intensity in other nomenclature.
  38056. */
  38057. _this.ambientTextureStrength = 1.0;
  38058. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38059. /**
  38060. * AKA Diffuse Color in other nomenclature.
  38061. */
  38062. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  38063. /**
  38064. * AKA Specular Color in other nomenclature.
  38065. */
  38066. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38067. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  38068. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38069. /**
  38070. * AKA Glossiness in other nomenclature.
  38071. */
  38072. _this.microSurface = 1.0;
  38073. /**
  38074. * source material index of refraction (IOR)' / 'destination material IOR.
  38075. */
  38076. _this.indexOfRefraction = 0.66;
  38077. /**
  38078. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38079. */
  38080. _this.invertRefractionY = false;
  38081. /**
  38082. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38083. * Materials half opaque for instance using refraction could benefit from this control.
  38084. */
  38085. _this.linkRefractionWithTransparency = false;
  38086. _this.useLightmapAsShadowmap = false;
  38087. /**
  38088. * Specifies that the alpha is coming form the albedo channel alpha channel.
  38089. */
  38090. _this.useAlphaFromAlbedoTexture = false;
  38091. /**
  38092. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38093. */
  38094. _this.forceAlphaTest = false;
  38095. /**
  38096. * Defines the alpha limits in alpha test mode.
  38097. */
  38098. _this.alphaCutOff = 0.4;
  38099. /**
  38100. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38101. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38102. */
  38103. _this.useSpecularOverAlpha = true;
  38104. /**
  38105. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38106. */
  38107. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  38108. /**
  38109. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38110. */
  38111. _this.useRoughnessFromMetallicTextureAlpha = true;
  38112. /**
  38113. * Specifies if the metallic texture contains the roughness information in its green channel.
  38114. */
  38115. _this.useRoughnessFromMetallicTextureGreen = false;
  38116. /**
  38117. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38118. */
  38119. _this.useMetallnessFromMetallicTextureBlue = false;
  38120. /**
  38121. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38122. */
  38123. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  38124. /**
  38125. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38126. */
  38127. _this.useAmbientInGrayScale = false;
  38128. /**
  38129. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38130. * The material will try to infer what glossiness each pixel should be.
  38131. */
  38132. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  38133. /**
  38134. * BJS is using an harcoded light falloff based on a manually sets up range.
  38135. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38136. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38137. */
  38138. _this.usePhysicalLightFalloff = true;
  38139. /**
  38140. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38141. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38142. */
  38143. _this.useRadianceOverAlpha = true;
  38144. /**
  38145. * Allows using the bump map in parallax mode.
  38146. */
  38147. _this.useParallax = false;
  38148. /**
  38149. * Allows using the bump map in parallax occlusion mode.
  38150. */
  38151. _this.useParallaxOcclusion = false;
  38152. /**
  38153. * Controls the scale bias of the parallax mode.
  38154. */
  38155. _this.parallaxScaleBias = 0.05;
  38156. /**
  38157. * If sets to true, disables all the lights affecting the material.
  38158. */
  38159. _this.disableLighting = false;
  38160. /**
  38161. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38162. */
  38163. _this.forceIrradianceInFragment = false;
  38164. /**
  38165. * Number of Simultaneous lights allowed on the material.
  38166. */
  38167. _this.maxSimultaneousLights = 4;
  38168. /**
  38169. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38170. */
  38171. _this.invertNormalMapX = false;
  38172. /**
  38173. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38174. */
  38175. _this.invertNormalMapY = false;
  38176. /**
  38177. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38178. */
  38179. _this.twoSidedLighting = false;
  38180. /**
  38181. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  38182. * in your scene composition.
  38183. */
  38184. _this.preMultiplyAlpha = false;
  38185. /**
  38186. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38187. * And/Or occlude the blended part.
  38188. */
  38189. _this.useAlphaFresnel = false;
  38190. /**
  38191. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38192. * And/Or occlude the blended part.
  38193. */
  38194. _this.environmentBRDFTexture = null;
  38195. /**
  38196. * Force normal to face away from face.
  38197. * (Temporary internal fix to remove before 3.1)
  38198. */
  38199. _this.forceNormalForward = false;
  38200. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38201. return _this;
  38202. }
  38203. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38204. /**
  38205. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38206. */
  38207. get: function () {
  38208. return this._PBRMATERIAL_OPAQUE;
  38209. },
  38210. enumerable: true,
  38211. configurable: true
  38212. });
  38213. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38214. /**
  38215. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  38216. */
  38217. get: function () {
  38218. return this._PBRMATERIAL_ALPHATEST;
  38219. },
  38220. enumerable: true,
  38221. configurable: true
  38222. });
  38223. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  38224. /**
  38225. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38226. */
  38227. get: function () {
  38228. return this._PBRMATERIAL_ALPHABLEND;
  38229. },
  38230. enumerable: true,
  38231. configurable: true
  38232. });
  38233. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  38234. /**
  38235. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38236. * They are also discarded below the alpha cutoff threshold to improve performances.
  38237. */
  38238. get: function () {
  38239. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  38240. },
  38241. enumerable: true,
  38242. configurable: true
  38243. });
  38244. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  38245. /**
  38246. * Gets the image processing configuration used either in this material.
  38247. */
  38248. get: function () {
  38249. return this._imageProcessingConfiguration;
  38250. },
  38251. /**
  38252. * Sets the Default image processing configuration used either in the this material.
  38253. *
  38254. * If sets to null, the scene one is in use.
  38255. */
  38256. set: function (value) {
  38257. this._attachImageProcessingConfiguration(value);
  38258. // Ensure the effect will be rebuilt.
  38259. this._markAllSubMeshesAsTexturesDirty();
  38260. },
  38261. enumerable: true,
  38262. configurable: true
  38263. });
  38264. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  38265. /**
  38266. * Gets wether the color curves effect is enabled.
  38267. */
  38268. get: function () {
  38269. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38270. },
  38271. /**
  38272. * Sets wether the color curves effect is enabled.
  38273. */
  38274. set: function (value) {
  38275. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38276. },
  38277. enumerable: true,
  38278. configurable: true
  38279. });
  38280. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  38281. /**
  38282. * Gets wether the color grading effect is enabled.
  38283. */
  38284. get: function () {
  38285. return this.imageProcessingConfiguration.colorGradingEnabled;
  38286. },
  38287. /**
  38288. * Gets wether the color grading effect is enabled.
  38289. */
  38290. set: function (value) {
  38291. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38292. },
  38293. enumerable: true,
  38294. configurable: true
  38295. });
  38296. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  38297. /**
  38298. * Gets wether tonemapping is enabled or not.
  38299. */
  38300. get: function () {
  38301. return this._imageProcessingConfiguration.toneMappingEnabled;
  38302. },
  38303. /**
  38304. * Sets wether tonemapping is enabled or not
  38305. */
  38306. set: function (value) {
  38307. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38308. },
  38309. enumerable: true,
  38310. configurable: true
  38311. });
  38312. ;
  38313. ;
  38314. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  38315. /**
  38316. * The camera exposure used on this material.
  38317. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38318. * This corresponds to a photographic exposure.
  38319. */
  38320. get: function () {
  38321. return this._imageProcessingConfiguration.exposure;
  38322. },
  38323. /**
  38324. * The camera exposure used on this material.
  38325. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38326. * This corresponds to a photographic exposure.
  38327. */
  38328. set: function (value) {
  38329. this._imageProcessingConfiguration.exposure = value;
  38330. },
  38331. enumerable: true,
  38332. configurable: true
  38333. });
  38334. ;
  38335. ;
  38336. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  38337. /**
  38338. * Gets The camera contrast used on this material.
  38339. */
  38340. get: function () {
  38341. return this._imageProcessingConfiguration.contrast;
  38342. },
  38343. /**
  38344. * Sets The camera contrast used on this material.
  38345. */
  38346. set: function (value) {
  38347. this._imageProcessingConfiguration.contrast = value;
  38348. },
  38349. enumerable: true,
  38350. configurable: true
  38351. });
  38352. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  38353. /**
  38354. * Gets the Color Grading 2D Lookup Texture.
  38355. */
  38356. get: function () {
  38357. return this._imageProcessingConfiguration.colorGradingTexture;
  38358. },
  38359. /**
  38360. * Sets the Color Grading 2D Lookup Texture.
  38361. */
  38362. set: function (value) {
  38363. this._imageProcessingConfiguration.colorGradingTexture = value;
  38364. },
  38365. enumerable: true,
  38366. configurable: true
  38367. });
  38368. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  38369. /**
  38370. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38371. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38372. * 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;
  38373. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38374. */
  38375. get: function () {
  38376. return this._imageProcessingConfiguration.colorCurves;
  38377. },
  38378. /**
  38379. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38380. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38381. * 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;
  38382. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38383. */
  38384. set: function (value) {
  38385. this._imageProcessingConfiguration.colorCurves = value;
  38386. },
  38387. enumerable: true,
  38388. configurable: true
  38389. });
  38390. PBRMaterial.prototype.getClassName = function () {
  38391. return "PBRMaterial";
  38392. };
  38393. PBRMaterial.prototype.getActiveTextures = function () {
  38394. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38395. if (this._albedoTexture) {
  38396. activeTextures.push(this._albedoTexture);
  38397. }
  38398. if (this._ambientTexture) {
  38399. activeTextures.push(this._ambientTexture);
  38400. }
  38401. if (this._opacityTexture) {
  38402. activeTextures.push(this._opacityTexture);
  38403. }
  38404. if (this._reflectionTexture) {
  38405. activeTextures.push(this._reflectionTexture);
  38406. }
  38407. if (this._emissiveTexture) {
  38408. activeTextures.push(this._emissiveTexture);
  38409. }
  38410. if (this._reflectivityTexture) {
  38411. activeTextures.push(this._reflectivityTexture);
  38412. }
  38413. if (this._metallicTexture) {
  38414. activeTextures.push(this._metallicTexture);
  38415. }
  38416. if (this._microSurfaceTexture) {
  38417. activeTextures.push(this._microSurfaceTexture);
  38418. }
  38419. if (this._bumpTexture) {
  38420. activeTextures.push(this._bumpTexture);
  38421. }
  38422. if (this._lightmapTexture) {
  38423. activeTextures.push(this._lightmapTexture);
  38424. }
  38425. if (this._refractionTexture) {
  38426. activeTextures.push(this._refractionTexture);
  38427. }
  38428. return activeTextures;
  38429. };
  38430. PBRMaterial.prototype.hasTexture = function (texture) {
  38431. if (_super.prototype.hasTexture.call(this, texture)) {
  38432. return true;
  38433. }
  38434. if (this._albedoTexture === texture) {
  38435. return true;
  38436. }
  38437. if (this._ambientTexture === texture) {
  38438. return true;
  38439. }
  38440. if (this._opacityTexture === texture) {
  38441. return true;
  38442. }
  38443. if (this._reflectionTexture === texture) {
  38444. return true;
  38445. }
  38446. if (this._reflectivityTexture === texture) {
  38447. return true;
  38448. }
  38449. if (this._metallicTexture === texture) {
  38450. return true;
  38451. }
  38452. if (this._microSurfaceTexture === texture) {
  38453. return true;
  38454. }
  38455. if (this._bumpTexture === texture) {
  38456. return true;
  38457. }
  38458. if (this._lightmapTexture === texture) {
  38459. return true;
  38460. }
  38461. if (this._refractionTexture === texture) {
  38462. return true;
  38463. }
  38464. return false;
  38465. };
  38466. PBRMaterial.prototype.clone = function (name) {
  38467. var _this = this;
  38468. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38469. };
  38470. PBRMaterial.prototype.serialize = function () {
  38471. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38472. serializationObject.customType = "BABYLON.PBRMaterial";
  38473. return serializationObject;
  38474. };
  38475. // Statics
  38476. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38477. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38478. };
  38479. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38480. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38481. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38482. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38483. __decorate([
  38484. BABYLON.serialize(),
  38485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38486. ], PBRMaterial.prototype, "directIntensity", void 0);
  38487. __decorate([
  38488. BABYLON.serialize(),
  38489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38490. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38491. __decorate([
  38492. BABYLON.serialize(),
  38493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38494. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38495. __decorate([
  38496. BABYLON.serialize(),
  38497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38498. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38499. __decorate([
  38500. BABYLON.serialize(),
  38501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38502. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38503. __decorate([
  38504. BABYLON.serializeAsTexture(),
  38505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38506. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38507. __decorate([
  38508. BABYLON.serializeAsTexture(),
  38509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38510. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38511. __decorate([
  38512. BABYLON.serialize(),
  38513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38514. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38515. __decorate([
  38516. BABYLON.serializeAsTexture(),
  38517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38518. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38519. __decorate([
  38520. BABYLON.serializeAsTexture(),
  38521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38522. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38523. __decorate([
  38524. BABYLON.serializeAsTexture(),
  38525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38526. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38527. __decorate([
  38528. BABYLON.serializeAsTexture(),
  38529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38530. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38531. __decorate([
  38532. BABYLON.serializeAsTexture(),
  38533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38534. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38535. __decorate([
  38536. BABYLON.serialize(),
  38537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38538. ], PBRMaterial.prototype, "metallic", void 0);
  38539. __decorate([
  38540. BABYLON.serialize(),
  38541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38542. ], PBRMaterial.prototype, "roughness", void 0);
  38543. __decorate([
  38544. BABYLON.serializeAsTexture(),
  38545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38546. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38547. __decorate([
  38548. BABYLON.serializeAsTexture(),
  38549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38550. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38551. __decorate([
  38552. BABYLON.serializeAsTexture(),
  38553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38554. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38555. __decorate([
  38556. BABYLON.serializeAsTexture(),
  38557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38558. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38559. __decorate([
  38560. BABYLON.serializeAsColor3("ambient"),
  38561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38562. ], PBRMaterial.prototype, "ambientColor", void 0);
  38563. __decorate([
  38564. BABYLON.serializeAsColor3("albedo"),
  38565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38566. ], PBRMaterial.prototype, "albedoColor", void 0);
  38567. __decorate([
  38568. BABYLON.serializeAsColor3("reflectivity"),
  38569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38570. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38571. __decorate([
  38572. BABYLON.serializeAsColor3("reflection"),
  38573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38574. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38575. __decorate([
  38576. BABYLON.serializeAsColor3("emissive"),
  38577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38578. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38579. __decorate([
  38580. BABYLON.serialize(),
  38581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38582. ], PBRMaterial.prototype, "microSurface", void 0);
  38583. __decorate([
  38584. BABYLON.serialize(),
  38585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38586. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38587. __decorate([
  38588. BABYLON.serialize(),
  38589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38590. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38591. __decorate([
  38592. BABYLON.serialize(),
  38593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38594. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38595. __decorate([
  38596. BABYLON.serialize(),
  38597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38598. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38599. __decorate([
  38600. BABYLON.serialize(),
  38601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38602. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38603. __decorate([
  38604. BABYLON.serialize(),
  38605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38606. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38607. __decorate([
  38608. BABYLON.serialize(),
  38609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38610. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38611. __decorate([
  38612. BABYLON.serialize(),
  38613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38614. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38615. __decorate([
  38616. BABYLON.serialize(),
  38617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38618. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38619. __decorate([
  38620. BABYLON.serialize(),
  38621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38622. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38623. __decorate([
  38624. BABYLON.serialize(),
  38625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38626. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38627. __decorate([
  38628. BABYLON.serialize(),
  38629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38630. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38631. __decorate([
  38632. BABYLON.serialize(),
  38633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38634. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38635. __decorate([
  38636. BABYLON.serialize(),
  38637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38638. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38639. __decorate([
  38640. BABYLON.serialize(),
  38641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38642. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38643. __decorate([
  38644. BABYLON.serialize(),
  38645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38646. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38647. __decorate([
  38648. BABYLON.serialize(),
  38649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38650. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38651. __decorate([
  38652. BABYLON.serialize(),
  38653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38654. ], PBRMaterial.prototype, "useParallax", void 0);
  38655. __decorate([
  38656. BABYLON.serialize(),
  38657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38658. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38659. __decorate([
  38660. BABYLON.serialize(),
  38661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38662. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38663. __decorate([
  38664. BABYLON.serialize(),
  38665. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38666. ], PBRMaterial.prototype, "disableLighting", void 0);
  38667. __decorate([
  38668. BABYLON.serialize(),
  38669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38670. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38671. __decorate([
  38672. BABYLON.serialize(),
  38673. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38674. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38675. __decorate([
  38676. BABYLON.serialize(),
  38677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38678. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38679. __decorate([
  38680. BABYLON.serialize(),
  38681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38682. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38683. __decorate([
  38684. BABYLON.serialize(),
  38685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38686. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38687. __decorate([
  38688. BABYLON.serialize(),
  38689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38690. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  38691. __decorate([
  38692. BABYLON.serialize(),
  38693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38694. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38695. __decorate([
  38696. BABYLON.serializeAsTexture(),
  38697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38698. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38699. __decorate([
  38700. BABYLON.serialize(),
  38701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38702. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38703. return PBRMaterial;
  38704. }(BABYLON.PBRBaseMaterial));
  38705. BABYLON.PBRMaterial = PBRMaterial;
  38706. })(BABYLON || (BABYLON = {}));
  38707. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38708. var BABYLON;
  38709. (function (BABYLON) {
  38710. /**
  38711. * The PBR material of BJS following the metal roughness convention.
  38712. *
  38713. * This fits to the PBR convention in the GLTF definition:
  38714. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38715. */
  38716. var PBRMetallicRoughnessMaterial = (function (_super) {
  38717. __extends(PBRMetallicRoughnessMaterial, _super);
  38718. /**
  38719. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38720. *
  38721. * @param name The material name
  38722. * @param scene The scene the material will be use in.
  38723. */
  38724. function PBRMetallicRoughnessMaterial(name, scene) {
  38725. var _this = _super.call(this, name, scene) || this;
  38726. _this._useRoughnessFromMetallicTextureAlpha = false;
  38727. _this._useRoughnessFromMetallicTextureGreen = true;
  38728. _this._useMetallnessFromMetallicTextureBlue = true;
  38729. return _this;
  38730. }
  38731. /**
  38732. * Return the currrent class name of the material.
  38733. */
  38734. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38735. return "PBRMetallicRoughnessMaterial";
  38736. };
  38737. /**
  38738. * Return the active textures of the material.
  38739. */
  38740. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  38741. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38742. if (this.baseTexture) {
  38743. activeTextures.push(this.baseTexture);
  38744. }
  38745. if (this.metallicRoughnessTexture) {
  38746. activeTextures.push(this.metallicRoughnessTexture);
  38747. }
  38748. return activeTextures;
  38749. };
  38750. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  38751. if (_super.prototype.hasTexture.call(this, texture)) {
  38752. return true;
  38753. }
  38754. if (this.baseTexture === texture) {
  38755. return true;
  38756. }
  38757. if (this.metallicRoughnessTexture === texture) {
  38758. return true;
  38759. }
  38760. return false;
  38761. };
  38762. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  38763. var _this = this;
  38764. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  38765. };
  38766. /**
  38767. * Serialize the material to a parsable JSON object.
  38768. */
  38769. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  38770. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38771. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  38772. return serializationObject;
  38773. };
  38774. /**
  38775. * Parses a JSON object correponding to the serialize function.
  38776. */
  38777. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38778. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38779. };
  38780. __decorate([
  38781. BABYLON.serializeAsColor3(),
  38782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38783. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38784. __decorate([
  38785. BABYLON.serializeAsTexture(),
  38786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38787. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38788. __decorate([
  38789. BABYLON.serialize(),
  38790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38791. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38792. __decorate([
  38793. BABYLON.serialize(),
  38794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38795. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38796. __decorate([
  38797. BABYLON.serializeAsTexture(),
  38798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38799. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38800. return PBRMetallicRoughnessMaterial;
  38801. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38802. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38803. })(BABYLON || (BABYLON = {}));
  38804. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38805. var BABYLON;
  38806. (function (BABYLON) {
  38807. /**
  38808. * The PBR material of BJS following the specular glossiness convention.
  38809. *
  38810. * This fits to the PBR convention in the GLTF definition:
  38811. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38812. */
  38813. var PBRSpecularGlossinessMaterial = (function (_super) {
  38814. __extends(PBRSpecularGlossinessMaterial, _super);
  38815. /**
  38816. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38817. *
  38818. * @param name The material name
  38819. * @param scene The scene the material will be use in.
  38820. */
  38821. function PBRSpecularGlossinessMaterial(name, scene) {
  38822. var _this = _super.call(this, name, scene) || this;
  38823. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38824. return _this;
  38825. }
  38826. /**
  38827. * Return the currrent class name of the material.
  38828. */
  38829. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38830. return "PBRSpecularGlossinessMaterial";
  38831. };
  38832. /**
  38833. * Return the active textures of the material.
  38834. */
  38835. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38836. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38837. if (this.diffuseTexture) {
  38838. activeTextures.push(this.diffuseTexture);
  38839. }
  38840. if (this.specularGlossinessTexture) {
  38841. activeTextures.push(this.specularGlossinessTexture);
  38842. }
  38843. return activeTextures;
  38844. };
  38845. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38846. if (_super.prototype.hasTexture.call(this, texture)) {
  38847. return true;
  38848. }
  38849. if (this.diffuseTexture === texture) {
  38850. return true;
  38851. }
  38852. if (this.specularGlossinessTexture === texture) {
  38853. return true;
  38854. }
  38855. return false;
  38856. };
  38857. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  38858. var _this = this;
  38859. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  38860. };
  38861. /**
  38862. * Serialize the material to a parsable JSON object.
  38863. */
  38864. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  38865. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38866. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  38867. return serializationObject;
  38868. };
  38869. /**
  38870. * Parses a JSON object correponding to the serialize function.
  38871. */
  38872. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38873. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38874. };
  38875. __decorate([
  38876. BABYLON.serializeAsColor3("diffuse"),
  38877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38878. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38879. __decorate([
  38880. BABYLON.serializeAsTexture(),
  38881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38882. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38883. __decorate([
  38884. BABYLON.serializeAsColor3("specular"),
  38885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38886. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38887. __decorate([
  38888. BABYLON.serialize(),
  38889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38890. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38891. __decorate([
  38892. BABYLON.serializeAsTexture(),
  38893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38894. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38895. return PBRSpecularGlossinessMaterial;
  38896. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38897. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38898. })(BABYLON || (BABYLON = {}));
  38899. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38900. var BABYLON;
  38901. (function (BABYLON) {
  38902. var ShaderMaterial = (function (_super) {
  38903. __extends(ShaderMaterial, _super);
  38904. function ShaderMaterial(name, scene, shaderPath, options) {
  38905. var _this = _super.call(this, name, scene) || this;
  38906. _this._textures = {};
  38907. _this._textureArrays = {};
  38908. _this._floats = {};
  38909. _this._floatsArrays = {};
  38910. _this._colors3 = {};
  38911. _this._colors3Arrays = {};
  38912. _this._colors4 = {};
  38913. _this._vectors2 = {};
  38914. _this._vectors3 = {};
  38915. _this._vectors4 = {};
  38916. _this._matrices = {};
  38917. _this._matrices3x3 = {};
  38918. _this._matrices2x2 = {};
  38919. _this._vectors3Arrays = {};
  38920. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  38921. _this._shaderPath = shaderPath;
  38922. options.needAlphaBlending = options.needAlphaBlending || false;
  38923. options.needAlphaTesting = options.needAlphaTesting || false;
  38924. options.attributes = options.attributes || ["position", "normal", "uv"];
  38925. options.uniforms = options.uniforms || ["worldViewProjection"];
  38926. options.uniformBuffers = options.uniformBuffers || [];
  38927. options.samplers = options.samplers || [];
  38928. options.defines = options.defines || [];
  38929. _this._options = options;
  38930. return _this;
  38931. }
  38932. ShaderMaterial.prototype.getClassName = function () {
  38933. return "ShaderMaterial";
  38934. };
  38935. ShaderMaterial.prototype.needAlphaBlending = function () {
  38936. return this._options.needAlphaBlending;
  38937. };
  38938. ShaderMaterial.prototype.needAlphaTesting = function () {
  38939. return this._options.needAlphaTesting;
  38940. };
  38941. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  38942. if (this._options.uniforms.indexOf(uniformName) === -1) {
  38943. this._options.uniforms.push(uniformName);
  38944. }
  38945. };
  38946. ShaderMaterial.prototype.setTexture = function (name, texture) {
  38947. if (this._options.samplers.indexOf(name) === -1) {
  38948. this._options.samplers.push(name);
  38949. }
  38950. this._textures[name] = texture;
  38951. return this;
  38952. };
  38953. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  38954. if (this._options.samplers.indexOf(name) === -1) {
  38955. this._options.samplers.push(name);
  38956. }
  38957. this._checkUniform(name);
  38958. this._textureArrays[name] = textures;
  38959. return this;
  38960. };
  38961. ShaderMaterial.prototype.setFloat = function (name, value) {
  38962. this._checkUniform(name);
  38963. this._floats[name] = value;
  38964. return this;
  38965. };
  38966. ShaderMaterial.prototype.setFloats = function (name, value) {
  38967. this._checkUniform(name);
  38968. this._floatsArrays[name] = value;
  38969. return this;
  38970. };
  38971. ShaderMaterial.prototype.setColor3 = function (name, value) {
  38972. this._checkUniform(name);
  38973. this._colors3[name] = value;
  38974. return this;
  38975. };
  38976. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  38977. this._checkUniform(name);
  38978. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  38979. color.toArray(arr, arr.length);
  38980. return arr;
  38981. }, []);
  38982. return this;
  38983. };
  38984. ShaderMaterial.prototype.setColor4 = function (name, value) {
  38985. this._checkUniform(name);
  38986. this._colors4[name] = value;
  38987. return this;
  38988. };
  38989. ShaderMaterial.prototype.setVector2 = function (name, value) {
  38990. this._checkUniform(name);
  38991. this._vectors2[name] = value;
  38992. return this;
  38993. };
  38994. ShaderMaterial.prototype.setVector3 = function (name, value) {
  38995. this._checkUniform(name);
  38996. this._vectors3[name] = value;
  38997. return this;
  38998. };
  38999. ShaderMaterial.prototype.setVector4 = function (name, value) {
  39000. this._checkUniform(name);
  39001. this._vectors4[name] = value;
  39002. return this;
  39003. };
  39004. ShaderMaterial.prototype.setMatrix = function (name, value) {
  39005. this._checkUniform(name);
  39006. this._matrices[name] = value;
  39007. return this;
  39008. };
  39009. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  39010. this._checkUniform(name);
  39011. this._matrices3x3[name] = value;
  39012. return this;
  39013. };
  39014. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  39015. this._checkUniform(name);
  39016. this._matrices2x2[name] = value;
  39017. return this;
  39018. };
  39019. ShaderMaterial.prototype.setArray3 = function (name, value) {
  39020. this._checkUniform(name);
  39021. this._vectors3Arrays[name] = value;
  39022. return this;
  39023. };
  39024. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  39025. if (!mesh) {
  39026. return true;
  39027. }
  39028. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  39029. return false;
  39030. }
  39031. return false;
  39032. };
  39033. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  39034. var scene = this.getScene();
  39035. var engine = scene.getEngine();
  39036. if (!this.checkReadyOnEveryCall) {
  39037. if (this._renderId === scene.getRenderId()) {
  39038. if (this._checkCache(scene, mesh, useInstances)) {
  39039. return true;
  39040. }
  39041. }
  39042. }
  39043. // Instances
  39044. var defines = [];
  39045. var attribs = [];
  39046. var fallbacks = new BABYLON.EffectFallbacks();
  39047. if (useInstances) {
  39048. defines.push("#define INSTANCES");
  39049. }
  39050. for (var index = 0; index < this._options.defines.length; index++) {
  39051. defines.push(this._options.defines[index]);
  39052. }
  39053. for (var index = 0; index < this._options.attributes.length; index++) {
  39054. attribs.push(this._options.attributes[index]);
  39055. }
  39056. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39057. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39058. defines.push("#define VERTEXCOLOR");
  39059. }
  39060. // Bones
  39061. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  39062. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39063. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39064. if (mesh.numBoneInfluencers > 4) {
  39065. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39066. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39067. }
  39068. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39069. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39070. fallbacks.addCPUSkinningFallback(0, mesh);
  39071. if (this._options.uniforms.indexOf("mBones") === -1) {
  39072. this._options.uniforms.push("mBones");
  39073. }
  39074. }
  39075. else {
  39076. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39077. }
  39078. // Textures
  39079. for (var name in this._textures) {
  39080. if (!this._textures[name].isReady()) {
  39081. return false;
  39082. }
  39083. }
  39084. // Alpha test
  39085. if (engine.getAlphaTesting()) {
  39086. defines.push("#define ALPHATEST");
  39087. }
  39088. var previousEffect = this._effect;
  39089. var join = defines.join("\n");
  39090. this._effect = engine.createEffect(this._shaderPath, {
  39091. attributes: attribs,
  39092. uniformsNames: this._options.uniforms,
  39093. uniformBuffersNames: this._options.uniformBuffers,
  39094. samplers: this._options.samplers,
  39095. defines: join,
  39096. fallbacks: fallbacks,
  39097. onCompiled: this.onCompiled,
  39098. onError: this.onError
  39099. }, engine);
  39100. if (!this._effect.isReady()) {
  39101. return false;
  39102. }
  39103. if (previousEffect !== this._effect) {
  39104. scene.resetCachedMaterial();
  39105. }
  39106. this._renderId = scene.getRenderId();
  39107. return true;
  39108. };
  39109. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39110. var scene = this.getScene();
  39111. if (this._options.uniforms.indexOf("world") !== -1) {
  39112. this._effect.setMatrix("world", world);
  39113. }
  39114. if (this._options.uniforms.indexOf("worldView") !== -1) {
  39115. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  39116. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  39117. }
  39118. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  39119. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  39120. }
  39121. };
  39122. ShaderMaterial.prototype.bind = function (world, mesh) {
  39123. // Std values
  39124. this.bindOnlyWorldMatrix(world);
  39125. if (this.getScene().getCachedMaterial() !== this) {
  39126. if (this._options.uniforms.indexOf("view") !== -1) {
  39127. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  39128. }
  39129. if (this._options.uniforms.indexOf("projection") !== -1) {
  39130. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  39131. }
  39132. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  39133. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  39134. }
  39135. // Bones
  39136. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  39137. var name;
  39138. // Texture
  39139. for (name in this._textures) {
  39140. this._effect.setTexture(name, this._textures[name]);
  39141. }
  39142. // Texture arrays
  39143. for (name in this._textureArrays) {
  39144. this._effect.setTextureArray(name, this._textureArrays[name]);
  39145. }
  39146. // Float
  39147. for (name in this._floats) {
  39148. this._effect.setFloat(name, this._floats[name]);
  39149. }
  39150. // Float s
  39151. for (name in this._floatsArrays) {
  39152. this._effect.setArray(name, this._floatsArrays[name]);
  39153. }
  39154. // Color3
  39155. for (name in this._colors3) {
  39156. this._effect.setColor3(name, this._colors3[name]);
  39157. }
  39158. for (name in this._colors3Arrays) {
  39159. this._effect.setArray3(name, this._colors3Arrays[name]);
  39160. }
  39161. // Color4
  39162. for (name in this._colors4) {
  39163. var color = this._colors4[name];
  39164. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  39165. }
  39166. // Vector2
  39167. for (name in this._vectors2) {
  39168. this._effect.setVector2(name, this._vectors2[name]);
  39169. }
  39170. // Vector3
  39171. for (name in this._vectors3) {
  39172. this._effect.setVector3(name, this._vectors3[name]);
  39173. }
  39174. // Vector4
  39175. for (name in this._vectors4) {
  39176. this._effect.setVector4(name, this._vectors4[name]);
  39177. }
  39178. // Matrix
  39179. for (name in this._matrices) {
  39180. this._effect.setMatrix(name, this._matrices[name]);
  39181. }
  39182. // Matrix 3x3
  39183. for (name in this._matrices3x3) {
  39184. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  39185. }
  39186. // Matrix 2x2
  39187. for (name in this._matrices2x2) {
  39188. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  39189. }
  39190. // Vector3Array
  39191. for (name in this._vectors3Arrays) {
  39192. this._effect.setArray3(name, this._vectors3Arrays[name]);
  39193. }
  39194. }
  39195. this._afterBind(mesh);
  39196. };
  39197. ShaderMaterial.prototype.getActiveTextures = function () {
  39198. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39199. for (var name in this._textures) {
  39200. activeTextures.push(this._textures[name]);
  39201. }
  39202. for (var name in this._textureArrays) {
  39203. var array = this._textureArrays[name];
  39204. for (var index = 0; index < array.length; index++) {
  39205. activeTextures.push(array[index]);
  39206. }
  39207. }
  39208. return activeTextures;
  39209. };
  39210. ShaderMaterial.prototype.hasTexture = function (texture) {
  39211. if (_super.prototype.hasTexture.call(this, texture)) {
  39212. return true;
  39213. }
  39214. for (var name in this._textures) {
  39215. if (this._textures[name] === texture) {
  39216. return true;
  39217. }
  39218. }
  39219. for (var name in this._textureArrays) {
  39220. var array = this._textureArrays[name];
  39221. for (var index = 0; index < array.length; index++) {
  39222. if (array[index] === texture) {
  39223. return true;
  39224. }
  39225. }
  39226. }
  39227. return false;
  39228. };
  39229. ShaderMaterial.prototype.clone = function (name) {
  39230. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  39231. return newShaderMaterial;
  39232. };
  39233. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39234. if (forceDisposeTextures) {
  39235. var name;
  39236. for (name in this._textures) {
  39237. this._textures[name].dispose();
  39238. }
  39239. for (name in this._textureArrays) {
  39240. var array = this._textureArrays[name];
  39241. for (var index = 0; index < array.length; index++) {
  39242. array[index].dispose();
  39243. }
  39244. }
  39245. }
  39246. this._textures = {};
  39247. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39248. };
  39249. ShaderMaterial.prototype.serialize = function () {
  39250. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39251. serializationObject.customType = "BABYLON.ShaderMaterial";
  39252. serializationObject.options = this._options;
  39253. serializationObject.shaderPath = this._shaderPath;
  39254. var name;
  39255. // Texture
  39256. serializationObject.textures = {};
  39257. for (name in this._textures) {
  39258. serializationObject.textures[name] = this._textures[name].serialize();
  39259. }
  39260. // Texture arrays
  39261. serializationObject.textureArrays = {};
  39262. for (name in this._textureArrays) {
  39263. serializationObject.textureArrays[name] = [];
  39264. var array = this._textureArrays[name];
  39265. for (var index = 0; index < array.length; index++) {
  39266. serializationObject.textureArrays[name].push(array[index].serialize());
  39267. }
  39268. }
  39269. // Float
  39270. serializationObject.floats = {};
  39271. for (name in this._floats) {
  39272. serializationObject.floats[name] = this._floats[name];
  39273. }
  39274. // Float s
  39275. serializationObject.floatArrays = {};
  39276. for (name in this._floatsArrays) {
  39277. serializationObject.floatArrays[name] = this._floatsArrays[name];
  39278. }
  39279. // Color3
  39280. serializationObject.colors3 = {};
  39281. for (name in this._colors3) {
  39282. serializationObject.colors3[name] = this._colors3[name].asArray();
  39283. }
  39284. // Color3 array
  39285. serializationObject.colors3Arrays = {};
  39286. for (name in this._colors3Arrays) {
  39287. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  39288. }
  39289. // Color4
  39290. serializationObject.colors4 = {};
  39291. for (name in this._colors4) {
  39292. serializationObject.colors4[name] = this._colors4[name].asArray();
  39293. }
  39294. // Vector2
  39295. serializationObject.vectors2 = {};
  39296. for (name in this._vectors2) {
  39297. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  39298. }
  39299. // Vector3
  39300. serializationObject.vectors3 = {};
  39301. for (name in this._vectors3) {
  39302. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  39303. }
  39304. // Vector4
  39305. serializationObject.vectors4 = {};
  39306. for (name in this._vectors4) {
  39307. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  39308. }
  39309. // Matrix
  39310. serializationObject.matrices = {};
  39311. for (name in this._matrices) {
  39312. serializationObject.matrices[name] = this._matrices[name].asArray();
  39313. }
  39314. // Matrix 3x3
  39315. serializationObject.matrices3x3 = {};
  39316. for (name in this._matrices3x3) {
  39317. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  39318. }
  39319. // Matrix 2x2
  39320. serializationObject.matrices2x2 = {};
  39321. for (name in this._matrices2x2) {
  39322. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  39323. }
  39324. // Vector3Array
  39325. serializationObject.vectors3Arrays = {};
  39326. for (name in this._vectors3Arrays) {
  39327. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  39328. }
  39329. return serializationObject;
  39330. };
  39331. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  39332. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  39333. var name;
  39334. // Texture
  39335. for (name in source.textures) {
  39336. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  39337. }
  39338. // Texture arrays
  39339. for (name in source.textureArrays) {
  39340. var array = source.textureArrays[name];
  39341. var textureArray = new Array();
  39342. for (var index = 0; index < array.length; index++) {
  39343. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  39344. }
  39345. material.setTextureArray(name, textureArray);
  39346. }
  39347. // Float
  39348. for (name in source.floats) {
  39349. material.setFloat(name, source.floats[name]);
  39350. }
  39351. // Float s
  39352. for (name in source.floatsArrays) {
  39353. material.setFloats(name, source.floatsArrays[name]);
  39354. }
  39355. // Color3
  39356. for (name in source.colors3) {
  39357. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  39358. }
  39359. // Color3 arrays
  39360. for (name in source.colors3Arrays) {
  39361. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  39362. if (i % 3 === 0) {
  39363. arr.push([num]);
  39364. }
  39365. else {
  39366. arr[arr.length - 1].push(num);
  39367. }
  39368. return arr;
  39369. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  39370. material.setColor3Array(name, colors);
  39371. }
  39372. // Color4
  39373. for (name in source.colors4) {
  39374. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  39375. }
  39376. // Vector2
  39377. for (name in source.vectors2) {
  39378. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  39379. }
  39380. // Vector3
  39381. for (name in source.vectors3) {
  39382. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  39383. }
  39384. // Vector4
  39385. for (name in source.vectors4) {
  39386. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  39387. }
  39388. // Matrix
  39389. for (name in source.matrices) {
  39390. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  39391. }
  39392. // Matrix 3x3
  39393. for (name in source.matrices3x3) {
  39394. material.setMatrix3x3(name, source.matrices3x3[name]);
  39395. }
  39396. // Matrix 2x2
  39397. for (name in source.matrices2x2) {
  39398. material.setMatrix2x2(name, source.matrices2x2[name]);
  39399. }
  39400. // Vector3Array
  39401. for (name in source.vectors3Arrays) {
  39402. material.setArray3(name, source.vectors3Arrays[name]);
  39403. }
  39404. return material;
  39405. };
  39406. return ShaderMaterial;
  39407. }(BABYLON.Material));
  39408. BABYLON.ShaderMaterial = ShaderMaterial;
  39409. })(BABYLON || (BABYLON = {}));
  39410. //# sourceMappingURL=babylon.shaderMaterial.js.map
  39411. var BABYLON;
  39412. (function (BABYLON) {
  39413. var MeshBuilder = (function () {
  39414. function MeshBuilder() {
  39415. }
  39416. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  39417. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  39418. return BABYLON.Mesh.DOUBLESIDE;
  39419. }
  39420. if (orientation === undefined || orientation === null) {
  39421. return BABYLON.Mesh.FRONTSIDE;
  39422. }
  39423. return orientation;
  39424. };
  39425. /**
  39426. * Creates a box mesh.
  39427. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  39428. * The parameter `size` sets the size (float) of each box side (default 1).
  39429. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  39430. * 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).
  39431. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  39432. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39433. * 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).
  39434. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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.CreateBox = function (name, options, scene) {
  39438. var box = new BABYLON.Mesh(name, scene);
  39439. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39440. box.sideOrientation = options.sideOrientation;
  39441. var vertexData = BABYLON.VertexData.CreateBox(options);
  39442. vertexData.applyToMesh(box, options.updatable);
  39443. return box;
  39444. };
  39445. /**
  39446. * Creates a sphere mesh.
  39447. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  39448. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  39449. * 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`).
  39450. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  39451. * 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
  39452. * 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).
  39453. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39454. * 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).
  39455. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39456. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39457. */
  39458. MeshBuilder.CreateSphere = function (name, options, scene) {
  39459. var sphere = new BABYLON.Mesh(name, scene);
  39460. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39461. sphere.sideOrientation = options.sideOrientation;
  39462. var vertexData = BABYLON.VertexData.CreateSphere(options);
  39463. vertexData.applyToMesh(sphere, options.updatable);
  39464. return sphere;
  39465. };
  39466. /**
  39467. * Creates a plane polygonal mesh. By default, this is a disc.
  39468. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  39469. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  39470. * 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.
  39471. * 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
  39472. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39473. * 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).
  39474. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39475. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39476. */
  39477. MeshBuilder.CreateDisc = function (name, options, scene) {
  39478. var disc = new BABYLON.Mesh(name, scene);
  39479. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39480. disc.sideOrientation = options.sideOrientation;
  39481. var vertexData = BABYLON.VertexData.CreateDisc(options);
  39482. vertexData.applyToMesh(disc, options.updatable);
  39483. return disc;
  39484. };
  39485. /**
  39486. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  39487. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  39488. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  39489. * 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`).
  39490. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  39491. * 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.
  39492. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39493. * 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).
  39494. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39496. */
  39497. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  39498. var sphere = new BABYLON.Mesh(name, scene);
  39499. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39500. sphere.sideOrientation = options.sideOrientation;
  39501. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  39502. vertexData.applyToMesh(sphere, options.updatable);
  39503. return sphere;
  39504. };
  39505. ;
  39506. /**
  39507. * Creates a ribbon mesh.
  39508. * 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.
  39509. *
  39510. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  39511. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  39512. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  39513. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  39514. * 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.
  39515. * 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.
  39516. * 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
  39517. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39518. * 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).
  39519. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39520. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39521. * 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.
  39522. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  39523. * 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
  39524. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  39525. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  39526. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39527. */
  39528. MeshBuilder.CreateRibbon = function (name, options, scene) {
  39529. var pathArray = options.pathArray;
  39530. var closeArray = options.closeArray;
  39531. var closePath = options.closePath;
  39532. var offset = options.offset;
  39533. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39534. var instance = options.instance;
  39535. var updatable = options.updatable;
  39536. if (instance) {
  39537. // positionFunction : ribbon case
  39538. // only pathArray and sideOrientation parameters are taken into account for positions update
  39539. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  39540. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  39541. var positionFunction = function (positions) {
  39542. var minlg = pathArray[0].length;
  39543. var i = 0;
  39544. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  39545. for (var si = 1; si <= ns; si++) {
  39546. for (var p = 0; p < pathArray.length; p++) {
  39547. var path = pathArray[p];
  39548. var l = path.length;
  39549. minlg = (minlg < l) ? minlg : l;
  39550. var j = 0;
  39551. while (j < minlg) {
  39552. positions[i] = path[j].x;
  39553. positions[i + 1] = path[j].y;
  39554. positions[i + 2] = path[j].z;
  39555. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  39556. BABYLON.Tmp.Vector3[0].x = path[j].x;
  39557. }
  39558. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  39559. BABYLON.Tmp.Vector3[1].x = path[j].x;
  39560. }
  39561. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  39562. BABYLON.Tmp.Vector3[0].y = path[j].y;
  39563. }
  39564. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  39565. BABYLON.Tmp.Vector3[1].y = path[j].y;
  39566. }
  39567. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  39568. BABYLON.Tmp.Vector3[0].z = path[j].z;
  39569. }
  39570. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  39571. BABYLON.Tmp.Vector3[1].z = path[j].z;
  39572. }
  39573. j++;
  39574. i += 3;
  39575. }
  39576. if (instance._closePath) {
  39577. positions[i] = path[0].x;
  39578. positions[i + 1] = path[0].y;
  39579. positions[i + 2] = path[0].z;
  39580. i += 3;
  39581. }
  39582. }
  39583. }
  39584. };
  39585. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39586. positionFunction(positions);
  39587. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  39588. instance._boundingInfo.update(instance._worldMatrix);
  39589. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  39590. if (options.colors) {
  39591. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39592. for (var c = 0; c < options.colors.length; c++) {
  39593. colors[c * 4] = options.colors[c].r;
  39594. colors[c * 4 + 1] = options.colors[c].g;
  39595. colors[c * 4 + 2] = options.colors[c].b;
  39596. colors[c * 4 + 3] = options.colors[c].a;
  39597. }
  39598. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  39599. }
  39600. if (options.uvs) {
  39601. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39602. for (var i = 0; i < options.uvs.length; i++) {
  39603. uvs[i * 2] = options.uvs[i].x;
  39604. uvs[i * 2 + 1] = options.uvs[i].y;
  39605. }
  39606. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  39607. }
  39608. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  39609. var indices = instance.getIndices();
  39610. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39611. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  39612. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  39613. if (instance._closePath) {
  39614. var indexFirst = 0;
  39615. var indexLast = 0;
  39616. for (var p = 0; p < pathArray.length; p++) {
  39617. indexFirst = instance._idx[p] * 3;
  39618. if (p + 1 < pathArray.length) {
  39619. indexLast = (instance._idx[p + 1] - 1) * 3;
  39620. }
  39621. else {
  39622. indexLast = normals.length - 3;
  39623. }
  39624. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  39625. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  39626. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  39627. normals[indexLast] = normals[indexFirst];
  39628. normals[indexLast + 1] = normals[indexFirst + 1];
  39629. normals[indexLast + 2] = normals[indexFirst + 2];
  39630. }
  39631. }
  39632. if (!(instance.areNormalsFrozen)) {
  39633. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  39634. }
  39635. }
  39636. return instance;
  39637. }
  39638. else {
  39639. var ribbon = new BABYLON.Mesh(name, scene);
  39640. ribbon.sideOrientation = sideOrientation;
  39641. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  39642. if (closePath) {
  39643. ribbon._idx = vertexData._idx;
  39644. }
  39645. ribbon._closePath = closePath;
  39646. ribbon._closeArray = closeArray;
  39647. vertexData.applyToMesh(ribbon, updatable);
  39648. return ribbon;
  39649. }
  39650. };
  39651. /**
  39652. * Creates a cylinder or a cone mesh.
  39653. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  39654. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  39655. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  39656. * 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.
  39657. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  39658. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  39659. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  39660. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  39661. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  39662. * 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).
  39663. * 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
  39664. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  39665. * 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
  39666. * 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.
  39667. * If `enclose` is false, a ring surface is one element.
  39668. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  39669. * 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
  39670. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39671. * 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).
  39672. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39674. */
  39675. MeshBuilder.CreateCylinder = function (name, options, scene) {
  39676. var cylinder = new BABYLON.Mesh(name, scene);
  39677. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39678. cylinder.sideOrientation = options.sideOrientation;
  39679. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  39680. vertexData.applyToMesh(cylinder, options.updatable);
  39681. return cylinder;
  39682. };
  39683. /**
  39684. * Creates a torus mesh.
  39685. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  39686. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  39687. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  39688. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  39689. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39690. * 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).
  39691. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39693. */
  39694. MeshBuilder.CreateTorus = function (name, options, scene) {
  39695. var torus = new BABYLON.Mesh(name, scene);
  39696. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39697. torus.sideOrientation = options.sideOrientation;
  39698. var vertexData = BABYLON.VertexData.CreateTorus(options);
  39699. vertexData.applyToMesh(torus, options.updatable);
  39700. return torus;
  39701. };
  39702. /**
  39703. * Creates a torus knot mesh.
  39704. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  39705. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  39706. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  39707. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  39708. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  39709. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39710. * 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).
  39711. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39713. */
  39714. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  39715. var torusKnot = new BABYLON.Mesh(name, scene);
  39716. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39717. torusKnot.sideOrientation = options.sideOrientation;
  39718. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  39719. vertexData.applyToMesh(torusKnot, options.updatable);
  39720. return torusKnot;
  39721. };
  39722. /**
  39723. * Creates a line system mesh.
  39724. * A line system is a pool of many lines gathered in a single mesh.
  39725. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  39726. * 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.
  39727. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  39728. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  39729. * 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
  39730. * 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
  39731. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  39732. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39733. */
  39734. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  39735. var instance = options.instance;
  39736. var lines = options.lines;
  39737. if (instance) {
  39738. var positionFunction = function (positions) {
  39739. var i = 0;
  39740. for (var l = 0; l < lines.length; l++) {
  39741. var points = lines[l];
  39742. for (var p = 0; p < points.length; p++) {
  39743. positions[i] = points[p].x;
  39744. positions[i + 1] = points[p].y;
  39745. positions[i + 2] = points[p].z;
  39746. i += 3;
  39747. }
  39748. }
  39749. };
  39750. instance.updateMeshPositions(positionFunction, false);
  39751. return instance;
  39752. }
  39753. // line system creation
  39754. var lineSystem = new BABYLON.LinesMesh(name, scene);
  39755. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  39756. vertexData.applyToMesh(lineSystem, options.updatable);
  39757. return lineSystem;
  39758. };
  39759. /**
  39760. * Creates a line mesh.
  39761. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  39762. * 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.
  39763. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39764. * The parameter `points` is an array successive Vector3.
  39765. * 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
  39766. * When updating an instance, remember that only point positions can change, not the number of points.
  39767. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39768. */
  39769. MeshBuilder.CreateLines = function (name, options, scene) {
  39770. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  39771. return lines;
  39772. };
  39773. /**
  39774. * Creates a dashed line mesh.
  39775. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  39776. * 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.
  39777. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39778. * The parameter `points` is an array successive Vector3.
  39779. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  39780. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  39781. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  39782. * 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
  39783. * When updating an instance, remember that only point positions can change, not the number of points.
  39784. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39785. */
  39786. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  39787. var points = options.points;
  39788. var instance = options.instance;
  39789. var gapSize = options.gapSize;
  39790. var dashNb = options.dashNb;
  39791. var dashSize = options.dashSize;
  39792. if (instance) {
  39793. var positionFunction = function (positions) {
  39794. var curvect = BABYLON.Vector3.Zero();
  39795. var nbSeg = positions.length / 6;
  39796. var lg = 0;
  39797. var nb = 0;
  39798. var shft = 0;
  39799. var dashshft = 0;
  39800. var curshft = 0;
  39801. var p = 0;
  39802. var i = 0;
  39803. var j = 0;
  39804. for (i = 0; i < points.length - 1; i++) {
  39805. points[i + 1].subtractToRef(points[i], curvect);
  39806. lg += curvect.length();
  39807. }
  39808. shft = lg / nbSeg;
  39809. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  39810. for (i = 0; i < points.length - 1; i++) {
  39811. points[i + 1].subtractToRef(points[i], curvect);
  39812. nb = Math.floor(curvect.length() / shft);
  39813. curvect.normalize();
  39814. j = 0;
  39815. while (j < nb && p < positions.length) {
  39816. curshft = shft * j;
  39817. positions[p] = points[i].x + curshft * curvect.x;
  39818. positions[p + 1] = points[i].y + curshft * curvect.y;
  39819. positions[p + 2] = points[i].z + curshft * curvect.z;
  39820. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  39821. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  39822. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  39823. p += 6;
  39824. j++;
  39825. }
  39826. }
  39827. while (p < positions.length) {
  39828. positions[p] = points[i].x;
  39829. positions[p + 1] = points[i].y;
  39830. positions[p + 2] = points[i].z;
  39831. p += 3;
  39832. }
  39833. };
  39834. instance.updateMeshPositions(positionFunction, false);
  39835. return instance;
  39836. }
  39837. // dashed lines creation
  39838. var dashedLines = new BABYLON.LinesMesh(name, scene);
  39839. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  39840. vertexData.applyToMesh(dashedLines, options.updatable);
  39841. dashedLines.dashSize = dashSize;
  39842. dashedLines.gapSize = gapSize;
  39843. return dashedLines;
  39844. };
  39845. /**
  39846. * Creates an extruded shape mesh.
  39847. * 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.
  39848. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  39849. *
  39850. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39851. * 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
  39852. * extruded along the Z axis.
  39853. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39854. * 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.
  39855. * The parameter `scale` (float, default 1) is the value to scale the shape.
  39856. * 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
  39857. * 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
  39858. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  39859. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39860. * 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).
  39861. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39862. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39863. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39864. */
  39865. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  39866. var path = options.path;
  39867. var shape = options.shape;
  39868. var scale = options.scale || 1;
  39869. var rotation = options.rotation || 0;
  39870. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39871. var updatable = options.updatable;
  39872. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39873. var instance = options.instance;
  39874. var invertUV = options.invertUV || false;
  39875. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  39876. };
  39877. /**
  39878. * Creates an custom extruded shape mesh.
  39879. * 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.
  39880. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  39881. *
  39882. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39883. * 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
  39884. * extruded along the Z axis.
  39885. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39886. * 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
  39887. * and the distance of this point from the begining of the path :
  39888. * ```javascript
  39889. * var rotationFunction = function(i, distance) {
  39890. * // do things
  39891. * return rotationValue; }
  39892. * ```
  39893. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  39894. * 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
  39895. * and the distance of this point from the begining of the path :
  39896. * ```javascript
  39897. * var scaleFunction = function(i, distance) {
  39898. * // do things
  39899. * return scaleValue;}
  39900. * ```
  39901. * It must returns a float value that will be the scale value applied to the shape on each path point.
  39902. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  39903. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  39904. * 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
  39905. * 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
  39906. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  39907. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39908. * 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).
  39909. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39910. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39911. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39912. */
  39913. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  39914. var path = options.path;
  39915. var shape = options.shape;
  39916. var scaleFunction = options.scaleFunction || (function () { return 1; });
  39917. var rotationFunction = options.rotationFunction || (function () { return 0; });
  39918. var ribbonCloseArray = options.ribbonCloseArray || false;
  39919. var ribbonClosePath = options.ribbonClosePath || false;
  39920. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39921. var updatable = options.updatable;
  39922. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39923. var instance = options.instance;
  39924. var invertUV = options.invertUV || false;
  39925. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  39926. };
  39927. /**
  39928. * Creates lathe mesh.
  39929. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  39930. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  39931. *
  39932. * 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
  39933. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  39934. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  39935. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  39936. * 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.
  39937. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  39938. * 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
  39939. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39940. * 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).
  39941. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39942. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39944. */
  39945. MeshBuilder.CreateLathe = function (name, options, scene) {
  39946. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  39947. var closed = (options.closed === undefined) ? true : options.closed;
  39948. var shape = options.shape;
  39949. var radius = options.radius || 1;
  39950. var tessellation = options.tessellation || 64;
  39951. var updatable = options.updatable;
  39952. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39953. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  39954. var pi2 = Math.PI * 2;
  39955. var paths = new Array();
  39956. var invertUV = options.invertUV || false;
  39957. var i = 0;
  39958. var p = 0;
  39959. var step = pi2 / tessellation * arc;
  39960. var rotated;
  39961. var path = new Array();
  39962. ;
  39963. for (i = 0; i <= tessellation; i++) {
  39964. var path = [];
  39965. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  39966. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  39967. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  39968. }
  39969. for (p = 0; p < shape.length; p++) {
  39970. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  39971. path.push(rotated);
  39972. }
  39973. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  39974. 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));
  39975. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  39976. }
  39977. paths.push(path);
  39978. }
  39979. // lathe ribbon
  39980. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  39981. return lathe;
  39982. };
  39983. /**
  39984. * Creates a plane mesh.
  39985. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  39986. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  39987. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  39988. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  39989. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39990. * 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).
  39991. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39992. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39993. */
  39994. MeshBuilder.CreatePlane = function (name, options, scene) {
  39995. var plane = new BABYLON.Mesh(name, scene);
  39996. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39997. plane.sideOrientation = options.sideOrientation;
  39998. var vertexData = BABYLON.VertexData.CreatePlane(options);
  39999. vertexData.applyToMesh(plane, options.updatable);
  40000. if (options.sourcePlane) {
  40001. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  40002. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  40003. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  40004. plane.rotate(vectorProduct, product);
  40005. }
  40006. return plane;
  40007. };
  40008. /**
  40009. * Creates a ground mesh.
  40010. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40011. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  40012. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  40013. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40014. */
  40015. MeshBuilder.CreateGround = function (name, options, scene) {
  40016. var ground = new BABYLON.GroundMesh(name, scene);
  40017. ground._setReady(false);
  40018. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  40019. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  40020. ground._width = options.width || 1;
  40021. ground._height = options.height || 1;
  40022. ground._maxX = ground._width / 2;
  40023. ground._maxZ = ground._height / 2;
  40024. ground._minX = -ground._maxX;
  40025. ground._minZ = -ground._maxZ;
  40026. var vertexData = BABYLON.VertexData.CreateGround(options);
  40027. vertexData.applyToMesh(ground, options.updatable);
  40028. ground._setReady(true);
  40029. return ground;
  40030. };
  40031. /**
  40032. * Creates a tiled ground mesh.
  40033. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  40034. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  40035. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  40036. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  40037. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  40038. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  40039. * numbers of subdivisions on the ground width and height of each tile.
  40040. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40041. */
  40042. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  40043. var tiledGround = new BABYLON.Mesh(name, scene);
  40044. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  40045. vertexData.applyToMesh(tiledGround, options.updatable);
  40046. return tiledGround;
  40047. };
  40048. /**
  40049. * Creates a ground mesh from a height map.
  40050. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  40051. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  40052. * The parameter `url` sets the URL of the height map image resource.
  40053. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  40054. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  40055. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  40056. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  40057. * 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.
  40058. * 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).
  40059. * This function is passed the newly built mesh :
  40060. * ```javascript
  40061. * function(mesh) { // do things
  40062. * return; }
  40063. * ```
  40064. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40065. */
  40066. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  40067. var width = options.width || 10.0;
  40068. var height = options.height || 10.0;
  40069. var subdivisions = options.subdivisions || 1 | 0;
  40070. var minHeight = options.minHeight || 0.0;
  40071. var maxHeight = options.maxHeight || 10.0;
  40072. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  40073. var updatable = options.updatable;
  40074. var onReady = options.onReady;
  40075. var ground = new BABYLON.GroundMesh(name, scene);
  40076. ground._subdivisionsX = subdivisions;
  40077. ground._subdivisionsY = subdivisions;
  40078. ground._width = width;
  40079. ground._height = height;
  40080. ground._maxX = ground._width / 2.0;
  40081. ground._maxZ = ground._height / 2.0;
  40082. ground._minX = -ground._maxX;
  40083. ground._minZ = -ground._maxZ;
  40084. ground._setReady(false);
  40085. var onload = function (img) {
  40086. // Getting height map data
  40087. var canvas = document.createElement("canvas");
  40088. var context = canvas.getContext("2d");
  40089. var bufferWidth = img.width;
  40090. var bufferHeight = img.height;
  40091. canvas.width = bufferWidth;
  40092. canvas.height = bufferHeight;
  40093. context.drawImage(img, 0, 0);
  40094. // Create VertexData from map data
  40095. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  40096. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  40097. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  40098. width: width, height: height,
  40099. subdivisions: subdivisions,
  40100. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  40101. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  40102. });
  40103. vertexData.applyToMesh(ground, updatable);
  40104. ground._setReady(true);
  40105. //execute ready callback, if set
  40106. if (onReady) {
  40107. onReady(ground);
  40108. }
  40109. };
  40110. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  40111. return ground;
  40112. };
  40113. /**
  40114. * Creates a polygon mesh.
  40115. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  40116. * 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.
  40117. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40118. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40119. * 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).
  40120. * Remember you can only change the shape positions, not their number when updating a polygon.
  40121. */
  40122. MeshBuilder.CreatePolygon = function (name, options, scene) {
  40123. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40124. var shape = options.shape;
  40125. var holes = options.holes || [];
  40126. var depth = options.depth || 0;
  40127. var contours = [];
  40128. var hole = [];
  40129. for (var i = 0; i < shape.length; i++) {
  40130. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  40131. }
  40132. var epsilon = 0.00000001;
  40133. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  40134. contours.pop();
  40135. }
  40136. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  40137. for (var hNb = 0; hNb < holes.length; hNb++) {
  40138. hole = [];
  40139. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  40140. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  40141. }
  40142. polygonTriangulation.addHole(hole);
  40143. }
  40144. var polygon = polygonTriangulation.build(options.updatable, depth);
  40145. polygon.sideOrientation = options.sideOrientation;
  40146. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  40147. vertexData.applyToMesh(polygon, options.updatable);
  40148. return polygon;
  40149. };
  40150. ;
  40151. /**
  40152. * Creates an extruded polygon mesh, with depth in the Y direction.
  40153. * 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).
  40154. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40155. */
  40156. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  40157. return MeshBuilder.CreatePolygon(name, options, scene);
  40158. };
  40159. ;
  40160. /**
  40161. * Creates a tube mesh.
  40162. * 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.
  40163. *
  40164. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  40165. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  40166. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  40167. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  40168. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  40169. * 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.
  40170. * It must return a radius value (positive float) :
  40171. * ```javascript
  40172. * var radiusFunction = function(i, distance) {
  40173. * // do things
  40174. * return radius; }
  40175. * ```
  40176. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  40177. * 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
  40178. * 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
  40179. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40180. * 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).
  40181. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40182. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40183. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40184. */
  40185. MeshBuilder.CreateTube = function (name, options, scene) {
  40186. var path = options.path;
  40187. var radius = options.radius || 1.0;
  40188. var tessellation = options.tessellation || 64 | 0;
  40189. var radiusFunction = options.radiusFunction;
  40190. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40191. var invertUV = options.invertUV || false;
  40192. var updatable = options.updatable;
  40193. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40194. var instance = options.instance;
  40195. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  40196. // tube geometry
  40197. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  40198. var tangents = path3D.getTangents();
  40199. var normals = path3D.getNormals();
  40200. var distances = path3D.getDistances();
  40201. var pi2 = Math.PI * 2;
  40202. var step = pi2 / tessellation * arc;
  40203. var returnRadius = function () { return radius; };
  40204. var radiusFunctionFinal = radiusFunction || returnRadius;
  40205. var circlePath;
  40206. var rad;
  40207. var normal;
  40208. var rotated;
  40209. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  40210. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  40211. for (var i = 0; i < path.length; i++) {
  40212. rad = radiusFunctionFinal(i, distances[i]); // current radius
  40213. circlePath = Array(); // current circle array
  40214. normal = normals[i]; // current normal
  40215. for (var t = 0; t < tessellation; t++) {
  40216. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  40217. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  40218. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  40219. rotated.scaleInPlace(rad).addInPlace(path[i]);
  40220. circlePath[t] = rotated;
  40221. }
  40222. circlePaths[index] = circlePath;
  40223. index++;
  40224. }
  40225. // cap
  40226. var capPath = function (nbPoints, pathIndex) {
  40227. var pointCap = Array();
  40228. for (var i = 0; i < nbPoints; i++) {
  40229. pointCap.push(path[pathIndex]);
  40230. }
  40231. return pointCap;
  40232. };
  40233. switch (cap) {
  40234. case BABYLON.Mesh.NO_CAP:
  40235. break;
  40236. case BABYLON.Mesh.CAP_START:
  40237. circlePaths[0] = capPath(tessellation, 0);
  40238. circlePaths[1] = circlePaths[2].slice(0);
  40239. break;
  40240. case BABYLON.Mesh.CAP_END:
  40241. circlePaths[index] = circlePaths[index - 1].slice(0);
  40242. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40243. break;
  40244. case BABYLON.Mesh.CAP_ALL:
  40245. circlePaths[0] = capPath(tessellation, 0);
  40246. circlePaths[1] = circlePaths[2].slice(0);
  40247. circlePaths[index] = circlePaths[index - 1].slice(0);
  40248. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40249. break;
  40250. default:
  40251. break;
  40252. }
  40253. return circlePaths;
  40254. };
  40255. var path3D;
  40256. var pathArray;
  40257. if (instance) {
  40258. var arc = options.arc || instance.arc;
  40259. path3D = (instance.path3D).update(path);
  40260. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  40261. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  40262. instance.path3D = path3D;
  40263. instance.pathArray = pathArray;
  40264. instance.arc = arc;
  40265. return instance;
  40266. }
  40267. // tube creation
  40268. path3D = new BABYLON.Path3D(path);
  40269. var newPathArray = new Array();
  40270. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40271. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  40272. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40273. tube.pathArray = pathArray;
  40274. tube.path3D = path3D;
  40275. tube.tessellation = tessellation;
  40276. tube.cap = cap;
  40277. tube.arc = options.arc;
  40278. return tube;
  40279. };
  40280. /**
  40281. * Creates a polyhedron mesh.
  40282. *
  40283. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  40284. * 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
  40285. * to choose the wanted type.
  40286. * The parameter `size` (positive float, default 1) sets the polygon size.
  40287. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  40288. * 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`.
  40289. * 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
  40290. * 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)`).
  40291. * 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
  40292. * 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.
  40293. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40294. * 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).
  40295. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40296. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40297. */
  40298. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  40299. var polyhedron = new BABYLON.Mesh(name, scene);
  40300. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40301. polyhedron.sideOrientation = options.sideOrientation;
  40302. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  40303. vertexData.applyToMesh(polyhedron, options.updatable);
  40304. return polyhedron;
  40305. };
  40306. /**
  40307. * Creates a decal mesh.
  40308. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  40309. * 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.
  40310. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  40311. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  40312. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  40313. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  40314. */
  40315. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  40316. var indices = sourceMesh.getIndices();
  40317. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40318. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40319. var position = options.position || BABYLON.Vector3.Zero();
  40320. var normal = options.normal || BABYLON.Vector3.Up();
  40321. var size = options.size || BABYLON.Vector3.One();
  40322. var angle = options.angle || 0;
  40323. // Getting correct rotation
  40324. if (!normal) {
  40325. var target = new BABYLON.Vector3(0, 0, 1);
  40326. var camera = sourceMesh.getScene().activeCamera;
  40327. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  40328. normal = camera.globalPosition.subtract(cameraWorldTarget);
  40329. }
  40330. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  40331. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  40332. var pitch = Math.atan2(normal.y, len);
  40333. // Matrix
  40334. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  40335. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  40336. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  40337. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  40338. var vertexData = new BABYLON.VertexData();
  40339. vertexData.indices = [];
  40340. vertexData.positions = [];
  40341. vertexData.normals = [];
  40342. vertexData.uvs = [];
  40343. var currentVertexDataIndex = 0;
  40344. var extractDecalVector3 = function (indexId) {
  40345. var vertexId = indices[indexId];
  40346. var result = new BABYLON.PositionNormalVertex();
  40347. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  40348. // Send vector to decal local world
  40349. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  40350. // Get normal
  40351. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  40352. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  40353. return result;
  40354. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  40355. var clip = function (vertices, axis) {
  40356. if (vertices.length === 0) {
  40357. return vertices;
  40358. }
  40359. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  40360. var clipVertices = function (v0, v1) {
  40361. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  40362. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  40363. };
  40364. var result = new Array();
  40365. for (var index = 0; index < vertices.length; index += 3) {
  40366. var v1Out;
  40367. var v2Out;
  40368. var v3Out;
  40369. var total = 0;
  40370. var nV1, nV2, nV3, nV4;
  40371. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  40372. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  40373. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  40374. v1Out = d1 > 0;
  40375. v2Out = d2 > 0;
  40376. v3Out = d3 > 0;
  40377. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  40378. switch (total) {
  40379. case 0:
  40380. result.push(vertices[index]);
  40381. result.push(vertices[index + 1]);
  40382. result.push(vertices[index + 2]);
  40383. break;
  40384. case 1:
  40385. if (v1Out) {
  40386. nV1 = vertices[index + 1];
  40387. nV2 = vertices[index + 2];
  40388. nV3 = clipVertices(vertices[index], nV1);
  40389. nV4 = clipVertices(vertices[index], nV2);
  40390. }
  40391. if (v2Out) {
  40392. nV1 = vertices[index];
  40393. nV2 = vertices[index + 2];
  40394. nV3 = clipVertices(vertices[index + 1], nV1);
  40395. nV4 = clipVertices(vertices[index + 1], nV2);
  40396. result.push(nV3);
  40397. result.push(nV2.clone());
  40398. result.push(nV1.clone());
  40399. result.push(nV2.clone());
  40400. result.push(nV3.clone());
  40401. result.push(nV4);
  40402. break;
  40403. }
  40404. if (v3Out) {
  40405. nV1 = vertices[index];
  40406. nV2 = vertices[index + 1];
  40407. nV3 = clipVertices(vertices[index + 2], nV1);
  40408. nV4 = clipVertices(vertices[index + 2], nV2);
  40409. }
  40410. result.push(nV1.clone());
  40411. result.push(nV2.clone());
  40412. result.push(nV3);
  40413. result.push(nV4);
  40414. result.push(nV3.clone());
  40415. result.push(nV2.clone());
  40416. break;
  40417. case 2:
  40418. if (!v1Out) {
  40419. nV1 = vertices[index].clone();
  40420. nV2 = clipVertices(nV1, vertices[index + 1]);
  40421. nV3 = clipVertices(nV1, vertices[index + 2]);
  40422. result.push(nV1);
  40423. result.push(nV2);
  40424. result.push(nV3);
  40425. }
  40426. if (!v2Out) {
  40427. nV1 = vertices[index + 1].clone();
  40428. nV2 = clipVertices(nV1, vertices[index + 2]);
  40429. nV3 = clipVertices(nV1, vertices[index]);
  40430. result.push(nV1);
  40431. result.push(nV2);
  40432. result.push(nV3);
  40433. }
  40434. if (!v3Out) {
  40435. nV1 = vertices[index + 2].clone();
  40436. nV2 = clipVertices(nV1, vertices[index]);
  40437. nV3 = clipVertices(nV1, vertices[index + 1]);
  40438. result.push(nV1);
  40439. result.push(nV2);
  40440. result.push(nV3);
  40441. }
  40442. break;
  40443. case 3:
  40444. break;
  40445. }
  40446. }
  40447. return result;
  40448. };
  40449. for (var index = 0; index < indices.length; index += 3) {
  40450. var faceVertices = new Array();
  40451. faceVertices.push(extractDecalVector3(index));
  40452. faceVertices.push(extractDecalVector3(index + 1));
  40453. faceVertices.push(extractDecalVector3(index + 2));
  40454. // Clip
  40455. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  40456. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  40457. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  40458. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  40459. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  40460. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  40461. if (faceVertices.length === 0) {
  40462. continue;
  40463. }
  40464. // Add UVs and get back to world
  40465. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  40466. var vertex = faceVertices[vIndex];
  40467. //TODO check for Int32Array | Uint32Array | Uint16Array
  40468. vertexData.indices.push(currentVertexDataIndex);
  40469. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  40470. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  40471. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  40472. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  40473. currentVertexDataIndex++;
  40474. }
  40475. }
  40476. // Return mesh
  40477. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  40478. vertexData.applyToMesh(decal);
  40479. decal.position = position.clone();
  40480. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  40481. return decal;
  40482. };
  40483. // Privates
  40484. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  40485. // extrusion geometry
  40486. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  40487. var tangents = path3D.getTangents();
  40488. var normals = path3D.getNormals();
  40489. var binormals = path3D.getBinormals();
  40490. var distances = path3D.getDistances();
  40491. var angle = 0;
  40492. var returnScale = function () { return scale; };
  40493. var returnRotation = function () { return rotation; };
  40494. var rotate = custom ? rotateFunction : returnRotation;
  40495. var scl = custom ? scaleFunction : returnScale;
  40496. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  40497. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  40498. for (var i = 0; i < curve.length; i++) {
  40499. var shapePath = new Array();
  40500. var angleStep = rotate(i, distances[i]);
  40501. var scaleRatio = scl(i, distances[i]);
  40502. for (var p = 0; p < shape.length; p++) {
  40503. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  40504. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  40505. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  40506. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  40507. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  40508. shapePath[p] = rotated;
  40509. }
  40510. shapePaths[index] = shapePath;
  40511. angle += angleStep;
  40512. index++;
  40513. }
  40514. // cap
  40515. var capPath = function (shapePath) {
  40516. var pointCap = Array();
  40517. var barycenter = BABYLON.Vector3.Zero();
  40518. var i;
  40519. for (i = 0; i < shapePath.length; i++) {
  40520. barycenter.addInPlace(shapePath[i]);
  40521. }
  40522. barycenter.scaleInPlace(1.0 / shapePath.length);
  40523. for (i = 0; i < shapePath.length; i++) {
  40524. pointCap.push(barycenter);
  40525. }
  40526. return pointCap;
  40527. };
  40528. switch (cap) {
  40529. case BABYLON.Mesh.NO_CAP:
  40530. break;
  40531. case BABYLON.Mesh.CAP_START:
  40532. shapePaths[0] = capPath(shapePaths[2]);
  40533. shapePaths[1] = shapePaths[2];
  40534. break;
  40535. case BABYLON.Mesh.CAP_END:
  40536. shapePaths[index] = shapePaths[index - 1];
  40537. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40538. break;
  40539. case BABYLON.Mesh.CAP_ALL:
  40540. shapePaths[0] = capPath(shapePaths[2]);
  40541. shapePaths[1] = shapePaths[2];
  40542. shapePaths[index] = shapePaths[index - 1];
  40543. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40544. break;
  40545. default:
  40546. break;
  40547. }
  40548. return shapePaths;
  40549. };
  40550. var path3D;
  40551. var pathArray;
  40552. if (instance) {
  40553. path3D = (instance.path3D).update(curve);
  40554. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  40555. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  40556. return instance;
  40557. }
  40558. // extruded shape creation
  40559. path3D = new BABYLON.Path3D(curve);
  40560. var newShapePaths = new Array();
  40561. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40562. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  40563. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  40564. extrudedGeneric.pathArray = pathArray;
  40565. extrudedGeneric.path3D = path3D;
  40566. extrudedGeneric.cap = cap;
  40567. return extrudedGeneric;
  40568. };
  40569. return MeshBuilder;
  40570. }());
  40571. BABYLON.MeshBuilder = MeshBuilder;
  40572. })(BABYLON || (BABYLON = {}));
  40573. //# sourceMappingURL=babylon.meshBuilder.js.map
  40574. var BABYLON;
  40575. (function (BABYLON) {
  40576. var Layer = (function () {
  40577. function Layer(name, imgUrl, scene, isBackground, color) {
  40578. this.name = name;
  40579. this.scale = new BABYLON.Vector2(1, 1);
  40580. this.offset = new BABYLON.Vector2(0, 0);
  40581. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  40582. this.layerMask = 0x0FFFFFFF;
  40583. this._vertexBuffers = {};
  40584. // Events
  40585. /**
  40586. * An event triggered when the layer is disposed.
  40587. * @type {BABYLON.Observable}
  40588. */
  40589. this.onDisposeObservable = new BABYLON.Observable();
  40590. /**
  40591. * An event triggered before rendering the scene
  40592. * @type {BABYLON.Observable}
  40593. */
  40594. this.onBeforeRenderObservable = new BABYLON.Observable();
  40595. /**
  40596. * An event triggered after rendering the scene
  40597. * @type {BABYLON.Observable}
  40598. */
  40599. this.onAfterRenderObservable = new BABYLON.Observable();
  40600. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  40601. this.isBackground = isBackground === undefined ? true : isBackground;
  40602. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  40603. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40604. this._scene.layers.push(this);
  40605. var engine = this._scene.getEngine();
  40606. // VBO
  40607. var vertices = [];
  40608. vertices.push(1, 1);
  40609. vertices.push(-1, 1);
  40610. vertices.push(-1, -1);
  40611. vertices.push(1, -1);
  40612. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40613. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  40614. this._createIndexBuffer();
  40615. // Effects
  40616. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  40617. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  40618. }
  40619. Object.defineProperty(Layer.prototype, "onDispose", {
  40620. set: function (callback) {
  40621. if (this._onDisposeObserver) {
  40622. this.onDisposeObservable.remove(this._onDisposeObserver);
  40623. }
  40624. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  40625. },
  40626. enumerable: true,
  40627. configurable: true
  40628. });
  40629. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  40630. set: function (callback) {
  40631. if (this._onBeforeRenderObserver) {
  40632. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40633. }
  40634. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40635. },
  40636. enumerable: true,
  40637. configurable: true
  40638. });
  40639. Object.defineProperty(Layer.prototype, "onAfterRender", {
  40640. set: function (callback) {
  40641. if (this._onAfterRenderObserver) {
  40642. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40643. }
  40644. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40645. },
  40646. enumerable: true,
  40647. configurable: true
  40648. });
  40649. Layer.prototype._createIndexBuffer = function () {
  40650. var engine = this._scene.getEngine();
  40651. // Indices
  40652. var indices = [];
  40653. indices.push(0);
  40654. indices.push(1);
  40655. indices.push(2);
  40656. indices.push(0);
  40657. indices.push(2);
  40658. indices.push(3);
  40659. this._indexBuffer = engine.createIndexBuffer(indices);
  40660. };
  40661. Layer.prototype._rebuild = function () {
  40662. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  40663. this._createIndexBuffer();
  40664. };
  40665. Layer.prototype.render = function () {
  40666. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  40667. // Check
  40668. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  40669. return;
  40670. var engine = this._scene.getEngine();
  40671. this.onBeforeRenderObservable.notifyObservers(this);
  40672. // Render
  40673. engine.enableEffect(currentEffect);
  40674. engine.setState(false);
  40675. // Texture
  40676. currentEffect.setTexture("textureSampler", this.texture);
  40677. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  40678. // Color
  40679. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  40680. // Scale / offset
  40681. currentEffect.setVector2("offset", this.offset);
  40682. currentEffect.setVector2("scale", this.scale);
  40683. // VBOs
  40684. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  40685. // Draw order
  40686. if (!this.alphaTest) {
  40687. engine.setAlphaMode(this.alphaBlendingMode);
  40688. engine.draw(true, 0, 6);
  40689. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40690. }
  40691. else {
  40692. engine.draw(true, 0, 6);
  40693. }
  40694. this.onAfterRenderObservable.notifyObservers(this);
  40695. };
  40696. Layer.prototype.dispose = function () {
  40697. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40698. if (vertexBuffer) {
  40699. vertexBuffer.dispose();
  40700. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40701. }
  40702. if (this._indexBuffer) {
  40703. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40704. this._indexBuffer = null;
  40705. }
  40706. if (this.texture) {
  40707. this.texture.dispose();
  40708. this.texture = null;
  40709. }
  40710. // Remove from scene
  40711. var index = this._scene.layers.indexOf(this);
  40712. this._scene.layers.splice(index, 1);
  40713. // Callback
  40714. this.onDisposeObservable.notifyObservers(this);
  40715. this.onDisposeObservable.clear();
  40716. this.onAfterRenderObservable.clear();
  40717. this.onBeforeRenderObservable.clear();
  40718. };
  40719. return Layer;
  40720. }());
  40721. BABYLON.Layer = Layer;
  40722. })(BABYLON || (BABYLON = {}));
  40723. //# sourceMappingURL=babylon.layer.js.map
  40724. var BABYLON;
  40725. (function (BABYLON) {
  40726. var BlurPostProcess = (function (_super) {
  40727. __extends(BlurPostProcess, _super);
  40728. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  40729. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40730. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40731. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  40732. _this.direction = direction;
  40733. _this._packedFloat = false;
  40734. _this.onApplyObservable.add(function (effect) {
  40735. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  40736. });
  40737. _this.kernel = kernel;
  40738. return _this;
  40739. }
  40740. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  40741. /**
  40742. * Gets the length in pixels of the blur sample region
  40743. */
  40744. get: function () {
  40745. return this._idealKernel;
  40746. },
  40747. /**
  40748. * Sets the length in pixels of the blur sample region
  40749. */
  40750. set: function (v) {
  40751. if (this._idealKernel === v) {
  40752. return;
  40753. }
  40754. v = Math.max(v, 1);
  40755. this._idealKernel = v;
  40756. this._kernel = this._nearestBestKernel(v);
  40757. this._updateParameters();
  40758. },
  40759. enumerable: true,
  40760. configurable: true
  40761. });
  40762. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  40763. /**
  40764. * Gets wether or not the blur is unpacking/repacking floats
  40765. */
  40766. get: function () {
  40767. return this._packedFloat;
  40768. },
  40769. /**
  40770. * Sets wether or not the blur needs to unpack/repack floats
  40771. */
  40772. set: function (v) {
  40773. if (this._packedFloat === v) {
  40774. return;
  40775. }
  40776. this._packedFloat = v;
  40777. this._updateParameters();
  40778. },
  40779. enumerable: true,
  40780. configurable: true
  40781. });
  40782. BlurPostProcess.prototype._updateParameters = function () {
  40783. // Generate sampling offsets and weights
  40784. var N = this._kernel;
  40785. var centerIndex = (N - 1) / 2;
  40786. // Generate Gaussian sampling weights over kernel
  40787. var offsets = [];
  40788. var weights = [];
  40789. var totalWeight = 0;
  40790. for (var i = 0; i < N; i++) {
  40791. var u = i / (N - 1);
  40792. var w = this._gaussianWeight(u * 2.0 - 1);
  40793. offsets[i] = (i - centerIndex);
  40794. weights[i] = w;
  40795. totalWeight += w;
  40796. }
  40797. // Normalize weights
  40798. for (var i = 0; i < weights.length; i++) {
  40799. weights[i] /= totalWeight;
  40800. }
  40801. // Optimize: combine samples to take advantage of hardware linear sampling
  40802. // Walk from left to center, combining pairs (symmetrically)
  40803. var linearSamplingWeights = [];
  40804. var linearSamplingOffsets = [];
  40805. var linearSamplingMap = [];
  40806. for (var i = 0; i <= centerIndex; i += 2) {
  40807. var j = Math.min(i + 1, Math.floor(centerIndex));
  40808. var singleCenterSample = i === j;
  40809. if (singleCenterSample) {
  40810. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  40811. }
  40812. else {
  40813. var sharedCell = j === centerIndex;
  40814. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  40815. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  40816. if (offsetLinear === 0) {
  40817. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  40818. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  40819. }
  40820. else {
  40821. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  40822. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  40823. }
  40824. }
  40825. }
  40826. for (var i = 0; i < linearSamplingMap.length; i++) {
  40827. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  40828. linearSamplingWeights[i] = linearSamplingMap[i].w;
  40829. }
  40830. // Replace with optimized
  40831. offsets = linearSamplingOffsets;
  40832. weights = linearSamplingWeights;
  40833. // Generate shaders
  40834. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  40835. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  40836. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  40837. var defines = "";
  40838. for (var i = 0; i < varyingCount; i++) {
  40839. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  40840. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  40841. }
  40842. var depCount = 0;
  40843. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  40844. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  40845. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  40846. depCount++;
  40847. }
  40848. if (this.packedFloat) {
  40849. defines += "#define PACKEDFLOAT 1";
  40850. }
  40851. this.updateEffect(defines, null, null, {
  40852. varyingCount: varyingCount,
  40853. depCount: depCount
  40854. });
  40855. };
  40856. /**
  40857. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  40858. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  40859. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  40860. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  40861. * The gaps between physical kernels are compensated for in the weighting of the samples
  40862. * @param idealKernel Ideal blur kernel.
  40863. * @return Nearest best kernel.
  40864. */
  40865. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  40866. var v = Math.round(idealKernel);
  40867. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  40868. var k = _a[_i];
  40869. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  40870. return Math.max(k, 3);
  40871. }
  40872. }
  40873. return Math.max(v, 3);
  40874. };
  40875. /**
  40876. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  40877. * @param x The point on the Gaussian distribution to sample.
  40878. * @return the value of the Gaussian function at x.
  40879. */
  40880. BlurPostProcess.prototype._gaussianWeight = function (x) {
  40881. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  40882. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  40883. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  40884. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  40885. // truncated at around 1.3% of peak strength.
  40886. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  40887. var sigma = (1 / 3);
  40888. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  40889. var exponent = -((x * x) / (2.0 * sigma * sigma));
  40890. var weight = (1.0 / denominator) * Math.exp(exponent);
  40891. return weight;
  40892. };
  40893. /**
  40894. * Generates a string that can be used as a floating point number in GLSL.
  40895. * @param x Value to print.
  40896. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  40897. * @return GLSL float string.
  40898. */
  40899. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  40900. if (decimalFigures === void 0) { decimalFigures = 8; }
  40901. return x.toFixed(decimalFigures).replace(/0+$/, '');
  40902. };
  40903. return BlurPostProcess;
  40904. }(BABYLON.PostProcess));
  40905. BABYLON.BlurPostProcess = BlurPostProcess;
  40906. })(BABYLON || (BABYLON = {}));
  40907. //# sourceMappingURL=babylon.blurPostProcess.js.map
  40908. var BABYLON;
  40909. (function (BABYLON) {
  40910. var FxaaPostProcess = (function (_super) {
  40911. __extends(FxaaPostProcess, _super);
  40912. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  40913. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40914. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  40915. _this.onApplyObservable.add(function (effect) {
  40916. var texelSize = _this.texelSize;
  40917. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  40918. });
  40919. return _this;
  40920. }
  40921. return FxaaPostProcess;
  40922. }(BABYLON.PostProcess));
  40923. BABYLON.FxaaPostProcess = FxaaPostProcess;
  40924. })(BABYLON || (BABYLON = {}));
  40925. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  40926. var BABYLON;
  40927. (function (BABYLON) {
  40928. var HighlightsPostProcess = (function (_super) {
  40929. __extends(HighlightsPostProcess, _super);
  40930. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  40931. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40932. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  40933. }
  40934. return HighlightsPostProcess;
  40935. }(BABYLON.PostProcess));
  40936. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  40937. })(BABYLON || (BABYLON = {}));
  40938. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  40939. var BABYLON;
  40940. (function (BABYLON) {
  40941. var ImageProcessingPostProcess = (function (_super) {
  40942. __extends(ImageProcessingPostProcess, _super);
  40943. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  40944. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40945. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  40946. _this._fromLinearSpace = true;
  40947. /**
  40948. * Defines cache preventing GC.
  40949. */
  40950. _this._defines = {
  40951. IMAGEPROCESSING: false,
  40952. VIGNETTE: false,
  40953. VIGNETTEBLENDMODEMULTIPLY: false,
  40954. VIGNETTEBLENDMODEOPAQUE: false,
  40955. TONEMAPPING: false,
  40956. CONTRAST: false,
  40957. COLORCURVES: false,
  40958. COLORGRADING: false,
  40959. FROMLINEARSPACE: false,
  40960. SAMPLER3DGREENDEPTH: false,
  40961. SAMPLER3DBGRMAP: false,
  40962. IMAGEPROCESSINGPOSTPROCESS: false,
  40963. EXPOSURE: false,
  40964. };
  40965. // Setup the default processing configuration to the scene.
  40966. _this._attachImageProcessingConfiguration(null, true);
  40967. _this.imageProcessingConfiguration.applyByPostProcess = true;
  40968. _this.onApply = function (effect) {
  40969. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  40970. };
  40971. return _this;
  40972. }
  40973. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  40974. /**
  40975. * Gets the image processing configuration used either in this material.
  40976. */
  40977. get: function () {
  40978. return this._imageProcessingConfiguration;
  40979. },
  40980. /**
  40981. * Sets the Default image processing configuration used either in the this material.
  40982. *
  40983. * If sets to null, the scene one is in use.
  40984. */
  40985. set: function (value) {
  40986. this._attachImageProcessingConfiguration(value);
  40987. },
  40988. enumerable: true,
  40989. configurable: true
  40990. });
  40991. /**
  40992. * Attaches a new image processing configuration to the PBR Material.
  40993. * @param configuration
  40994. */
  40995. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  40996. var _this = this;
  40997. if (doNotBuild === void 0) { doNotBuild = false; }
  40998. if (configuration === this._imageProcessingConfiguration) {
  40999. return;
  41000. }
  41001. // Detaches observer.
  41002. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41003. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41004. }
  41005. // Pick the scene configuration if needed.
  41006. if (!configuration) {
  41007. var camera = this.getCamera();
  41008. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  41009. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  41010. }
  41011. else {
  41012. this._imageProcessingConfiguration = configuration;
  41013. }
  41014. // Attaches observer.
  41015. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41016. _this._updateParameters();
  41017. });
  41018. // Ensure the effect will be rebuilt.
  41019. if (!doNotBuild) {
  41020. this._updateParameters();
  41021. }
  41022. };
  41023. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  41024. /**
  41025. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  41026. */
  41027. get: function () {
  41028. return this.imageProcessingConfiguration.colorCurves;
  41029. },
  41030. /**
  41031. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  41032. */
  41033. set: function (value) {
  41034. this.imageProcessingConfiguration.colorCurves = value;
  41035. },
  41036. enumerable: true,
  41037. configurable: true
  41038. });
  41039. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  41040. /**
  41041. * Gets wether the color curves effect is enabled.
  41042. */
  41043. get: function () {
  41044. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41045. },
  41046. /**
  41047. * Sets wether the color curves effect is enabled.
  41048. */
  41049. set: function (value) {
  41050. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41051. },
  41052. enumerable: true,
  41053. configurable: true
  41054. });
  41055. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  41056. /**
  41057. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  41058. */
  41059. get: function () {
  41060. return this.imageProcessingConfiguration.colorGradingTexture;
  41061. },
  41062. /**
  41063. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  41064. */
  41065. set: function (value) {
  41066. this.imageProcessingConfiguration.colorGradingTexture = value;
  41067. },
  41068. enumerable: true,
  41069. configurable: true
  41070. });
  41071. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  41072. /**
  41073. * Gets wether the color grading effect is enabled.
  41074. */
  41075. get: function () {
  41076. return this.imageProcessingConfiguration.colorGradingEnabled;
  41077. },
  41078. /**
  41079. * Gets wether the color grading effect is enabled.
  41080. */
  41081. set: function (value) {
  41082. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41083. },
  41084. enumerable: true,
  41085. configurable: true
  41086. });
  41087. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  41088. /**
  41089. * Gets exposure used in the effect.
  41090. */
  41091. get: function () {
  41092. return this.imageProcessingConfiguration.exposure;
  41093. },
  41094. /**
  41095. * Sets exposure used in the effect.
  41096. */
  41097. set: function (value) {
  41098. this.imageProcessingConfiguration.exposure = value;
  41099. },
  41100. enumerable: true,
  41101. configurable: true
  41102. });
  41103. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  41104. /**
  41105. * Gets wether tonemapping is enabled or not.
  41106. */
  41107. get: function () {
  41108. return this._imageProcessingConfiguration.toneMappingEnabled;
  41109. },
  41110. /**
  41111. * Sets wether tonemapping is enabled or not
  41112. */
  41113. set: function (value) {
  41114. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41115. },
  41116. enumerable: true,
  41117. configurable: true
  41118. });
  41119. ;
  41120. ;
  41121. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  41122. /**
  41123. * Gets contrast used in the effect.
  41124. */
  41125. get: function () {
  41126. return this.imageProcessingConfiguration.contrast;
  41127. },
  41128. /**
  41129. * Sets contrast used in the effect.
  41130. */
  41131. set: function (value) {
  41132. this.imageProcessingConfiguration.contrast = value;
  41133. },
  41134. enumerable: true,
  41135. configurable: true
  41136. });
  41137. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  41138. /**
  41139. * Gets Vignette stretch size.
  41140. */
  41141. get: function () {
  41142. return this.imageProcessingConfiguration.vignetteStretch;
  41143. },
  41144. /**
  41145. * Sets Vignette stretch size.
  41146. */
  41147. set: function (value) {
  41148. this.imageProcessingConfiguration.vignetteStretch = value;
  41149. },
  41150. enumerable: true,
  41151. configurable: true
  41152. });
  41153. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  41154. /**
  41155. * Gets Vignette centre X Offset.
  41156. */
  41157. get: function () {
  41158. return this.imageProcessingConfiguration.vignetteCentreX;
  41159. },
  41160. /**
  41161. * Sets Vignette centre X Offset.
  41162. */
  41163. set: function (value) {
  41164. this.imageProcessingConfiguration.vignetteCentreX = value;
  41165. },
  41166. enumerable: true,
  41167. configurable: true
  41168. });
  41169. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  41170. /**
  41171. * Gets Vignette centre Y Offset.
  41172. */
  41173. get: function () {
  41174. return this.imageProcessingConfiguration.vignetteCentreY;
  41175. },
  41176. /**
  41177. * Sets Vignette centre Y Offset.
  41178. */
  41179. set: function (value) {
  41180. this.imageProcessingConfiguration.vignetteCentreY = value;
  41181. },
  41182. enumerable: true,
  41183. configurable: true
  41184. });
  41185. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  41186. /**
  41187. * Gets Vignette weight or intensity of the vignette effect.
  41188. */
  41189. get: function () {
  41190. return this.imageProcessingConfiguration.vignetteWeight;
  41191. },
  41192. /**
  41193. * Sets Vignette weight or intensity of the vignette effect.
  41194. */
  41195. set: function (value) {
  41196. this.imageProcessingConfiguration.vignetteWeight = value;
  41197. },
  41198. enumerable: true,
  41199. configurable: true
  41200. });
  41201. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  41202. /**
  41203. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41204. * if vignetteEnabled is set to true.
  41205. */
  41206. get: function () {
  41207. return this.imageProcessingConfiguration.vignetteColor;
  41208. },
  41209. /**
  41210. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41211. * if vignetteEnabled is set to true.
  41212. */
  41213. set: function (value) {
  41214. this.imageProcessingConfiguration.vignetteColor = value;
  41215. },
  41216. enumerable: true,
  41217. configurable: true
  41218. });
  41219. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  41220. /**
  41221. * Gets Camera field of view used by the Vignette effect.
  41222. */
  41223. get: function () {
  41224. return this.imageProcessingConfiguration.vignetteCameraFov;
  41225. },
  41226. /**
  41227. * Sets Camera field of view used by the Vignette effect.
  41228. */
  41229. set: function (value) {
  41230. this.imageProcessingConfiguration.vignetteCameraFov = value;
  41231. },
  41232. enumerable: true,
  41233. configurable: true
  41234. });
  41235. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  41236. /**
  41237. * Gets the vignette blend mode allowing different kind of effect.
  41238. */
  41239. get: function () {
  41240. return this.imageProcessingConfiguration.vignetteBlendMode;
  41241. },
  41242. /**
  41243. * Sets the vignette blend mode allowing different kind of effect.
  41244. */
  41245. set: function (value) {
  41246. this.imageProcessingConfiguration.vignetteBlendMode = value;
  41247. },
  41248. enumerable: true,
  41249. configurable: true
  41250. });
  41251. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  41252. /**
  41253. * Gets wether the vignette effect is enabled.
  41254. */
  41255. get: function () {
  41256. return this.imageProcessingConfiguration.vignetteEnabled;
  41257. },
  41258. /**
  41259. * Sets wether the vignette effect is enabled.
  41260. */
  41261. set: function (value) {
  41262. this.imageProcessingConfiguration.vignetteEnabled = value;
  41263. },
  41264. enumerable: true,
  41265. configurable: true
  41266. });
  41267. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  41268. /**
  41269. * Gets wether the input of the processing is in Gamma or Linear Space.
  41270. */
  41271. get: function () {
  41272. return this._fromLinearSpace;
  41273. },
  41274. /**
  41275. * Sets wether the input of the processing is in Gamma or Linear Space.
  41276. */
  41277. set: function (value) {
  41278. if (this._fromLinearSpace === value) {
  41279. return;
  41280. }
  41281. this._fromLinearSpace = value;
  41282. this._updateParameters();
  41283. },
  41284. enumerable: true,
  41285. configurable: true
  41286. });
  41287. ImageProcessingPostProcess.prototype.getClassName = function () {
  41288. return "ImageProcessingPostProcess";
  41289. };
  41290. ImageProcessingPostProcess.prototype._updateParameters = function () {
  41291. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  41292. this.imageProcessingConfiguration.prepareDefines(this._defines);
  41293. var defines = "";
  41294. for (var define in this._defines) {
  41295. if (this._defines[define]) {
  41296. defines += "#define " + define + ";\r\n";
  41297. }
  41298. }
  41299. var samplers = ["textureSampler"];
  41300. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  41301. var uniforms = ["scale"];
  41302. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  41303. this.updateEffect(defines, uniforms, samplers);
  41304. };
  41305. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  41306. _super.prototype.dispose.call(this, camera);
  41307. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41308. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41309. }
  41310. this.imageProcessingConfiguration.applyByPostProcess = false;
  41311. };
  41312. __decorate([
  41313. BABYLON.serialize()
  41314. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  41315. return ImageProcessingPostProcess;
  41316. }(BABYLON.PostProcess));
  41317. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  41318. })(BABYLON || (BABYLON = {}));
  41319. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  41320. var BABYLON;
  41321. (function (BABYLON) {
  41322. /**
  41323. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41324. * It can help converting any input color in a desired output one. This can then be used to create effects
  41325. * from sepia, black and white to sixties or futuristic rendering...
  41326. *
  41327. * The only supported format is currently 3dl.
  41328. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41329. */
  41330. var ColorGradingTexture = (function (_super) {
  41331. __extends(ColorGradingTexture, _super);
  41332. /**
  41333. * Instantiates a ColorGradingTexture from the following parameters.
  41334. *
  41335. * @param url The location of the color gradind data (currently only supporting 3dl)
  41336. * @param scene The scene the texture will be used in
  41337. */
  41338. function ColorGradingTexture(url, scene) {
  41339. var _this = _super.call(this, scene) || this;
  41340. if (!url) {
  41341. return _this;
  41342. }
  41343. _this._textureMatrix = BABYLON.Matrix.Identity();
  41344. _this.name = url;
  41345. _this.url = url;
  41346. _this.hasAlpha = false;
  41347. _this.isCube = false;
  41348. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41349. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41350. _this.anisotropicFilteringLevel = 1;
  41351. _this._texture = _this._getFromCache(url, true);
  41352. if (!_this._texture) {
  41353. if (!scene.useDelayedTextureLoading) {
  41354. _this.loadTexture();
  41355. }
  41356. else {
  41357. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41358. }
  41359. }
  41360. return _this;
  41361. }
  41362. /**
  41363. * Returns the texture matrix used in most of the material.
  41364. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41365. */
  41366. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41367. return this._textureMatrix;
  41368. };
  41369. /**
  41370. * Occurs when the file being loaded is a .3dl LUT file.
  41371. */
  41372. ColorGradingTexture.prototype.load3dlTexture = function () {
  41373. var _this = this;
  41374. var mipLevels = 0;
  41375. var floatArrayView = null;
  41376. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41377. this._texture = texture;
  41378. var callback = function (text) {
  41379. var data;
  41380. var tempData;
  41381. var line;
  41382. var lines = text.split('\n');
  41383. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41384. var maxColor = 0;
  41385. for (var i = 0; i < lines.length; i++) {
  41386. line = lines[i];
  41387. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41388. continue;
  41389. if (line.indexOf('#') === 0)
  41390. continue;
  41391. var words = line.split(" ");
  41392. if (size === 0) {
  41393. // Number of space + one
  41394. size = words.length;
  41395. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41396. tempData = new Float32Array(size * size * size * 4);
  41397. continue;
  41398. }
  41399. if (size != 0) {
  41400. var r = Math.max(parseInt(words[0]), 0);
  41401. var g = Math.max(parseInt(words[1]), 0);
  41402. var b = Math.max(parseInt(words[2]), 0);
  41403. maxColor = Math.max(r, maxColor);
  41404. maxColor = Math.max(g, maxColor);
  41405. maxColor = Math.max(b, maxColor);
  41406. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41407. tempData[pixelStorageIndex + 0] = r;
  41408. tempData[pixelStorageIndex + 1] = g;
  41409. tempData[pixelStorageIndex + 2] = b;
  41410. pixelIndexSlice++;
  41411. if (pixelIndexSlice % size == 0) {
  41412. pixelIndexH++;
  41413. pixelIndexSlice = 0;
  41414. if (pixelIndexH % size == 0) {
  41415. pixelIndexW++;
  41416. pixelIndexH = 0;
  41417. }
  41418. }
  41419. }
  41420. }
  41421. for (var i = 0; i < tempData.length; i++) {
  41422. if (i > 0 && (i + 1) % 4 === 0) {
  41423. data[i] = 255;
  41424. }
  41425. else {
  41426. var value = tempData[i];
  41427. data[i] = (value / maxColor * 255);
  41428. }
  41429. }
  41430. texture.updateSize(size * size, size);
  41431. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41432. };
  41433. BABYLON.Tools.LoadFile(this.url, callback);
  41434. return this._texture;
  41435. };
  41436. /**
  41437. * Starts the loading process of the texture.
  41438. */
  41439. ColorGradingTexture.prototype.loadTexture = function () {
  41440. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41441. this.load3dlTexture();
  41442. }
  41443. };
  41444. /**
  41445. * Clones the color gradind texture.
  41446. */
  41447. ColorGradingTexture.prototype.clone = function () {
  41448. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41449. // Base texture
  41450. newTexture.level = this.level;
  41451. return newTexture;
  41452. };
  41453. /**
  41454. * Called during delayed load for textures.
  41455. */
  41456. ColorGradingTexture.prototype.delayLoad = function () {
  41457. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41458. return;
  41459. }
  41460. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41461. this._texture = this._getFromCache(this.url, true);
  41462. if (!this._texture) {
  41463. this.loadTexture();
  41464. }
  41465. };
  41466. /**
  41467. * Parses a color grading texture serialized by Babylon.
  41468. * @param parsedTexture The texture information being parsedTexture
  41469. * @param scene The scene to load the texture in
  41470. * @param rootUrl The root url of the data assets to load
  41471. * @return A color gradind texture
  41472. */
  41473. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41474. var texture = null;
  41475. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41476. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  41477. texture.name = parsedTexture.name;
  41478. texture.level = parsedTexture.level;
  41479. }
  41480. return texture;
  41481. };
  41482. /**
  41483. * Serializes the LUT texture to json format.
  41484. */
  41485. ColorGradingTexture.prototype.serialize = function () {
  41486. if (!this.name) {
  41487. return null;
  41488. }
  41489. var serializationObject = {};
  41490. serializationObject.name = this.name;
  41491. serializationObject.level = this.level;
  41492. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41493. return serializationObject;
  41494. };
  41495. /**
  41496. * Empty line regex stored for GC.
  41497. */
  41498. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41499. return ColorGradingTexture;
  41500. }(BABYLON.BaseTexture));
  41501. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41502. })(BABYLON || (BABYLON = {}));
  41503. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41504. var BABYLON;
  41505. (function (BABYLON) {
  41506. /**
  41507. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41508. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41509. * 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;
  41510. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41511. */
  41512. var ColorCurves = (function () {
  41513. function ColorCurves() {
  41514. this._dirty = true;
  41515. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41516. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41517. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41518. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41519. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41520. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41521. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41522. this._globalHue = 30;
  41523. this._globalDensity = 0;
  41524. this._globalSaturation = 0;
  41525. this._globalExposure = 0;
  41526. this._highlightsHue = 30;
  41527. this._highlightsDensity = 0;
  41528. this._highlightsSaturation = 0;
  41529. this._highlightsExposure = 0;
  41530. this._midtonesHue = 30;
  41531. this._midtonesDensity = 0;
  41532. this._midtonesSaturation = 0;
  41533. this._midtonesExposure = 0;
  41534. this._shadowsHue = 30;
  41535. this._shadowsDensity = 0;
  41536. this._shadowsSaturation = 0;
  41537. this._shadowsExposure = 0;
  41538. }
  41539. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41540. /**
  41541. * Gets the global Hue value.
  41542. * 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).
  41543. */
  41544. get: function () {
  41545. return this._globalHue;
  41546. },
  41547. /**
  41548. * Sets the global Hue value.
  41549. * 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).
  41550. */
  41551. set: function (value) {
  41552. this._globalHue = value;
  41553. this._dirty = true;
  41554. },
  41555. enumerable: true,
  41556. configurable: true
  41557. });
  41558. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41559. /**
  41560. * Gets the global Density value.
  41561. * 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.
  41562. * Values less than zero provide a filter of opposite hue.
  41563. */
  41564. get: function () {
  41565. return this._globalDensity;
  41566. },
  41567. /**
  41568. * Sets the global Density value.
  41569. * 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.
  41570. * Values less than zero provide a filter of opposite hue.
  41571. */
  41572. set: function (value) {
  41573. this._globalDensity = value;
  41574. this._dirty = true;
  41575. },
  41576. enumerable: true,
  41577. configurable: true
  41578. });
  41579. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41580. /**
  41581. * Gets the global Saturation value.
  41582. * 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.
  41583. */
  41584. get: function () {
  41585. return this._globalSaturation;
  41586. },
  41587. /**
  41588. * Sets the global Saturation value.
  41589. * 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.
  41590. */
  41591. set: function (value) {
  41592. this._globalSaturation = value;
  41593. this._dirty = true;
  41594. },
  41595. enumerable: true,
  41596. configurable: true
  41597. });
  41598. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41599. /**
  41600. * Gets the highlights Hue value.
  41601. * 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).
  41602. */
  41603. get: function () {
  41604. return this._highlightsHue;
  41605. },
  41606. /**
  41607. * Sets the highlights Hue value.
  41608. * 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).
  41609. */
  41610. set: function (value) {
  41611. this._highlightsHue = value;
  41612. this._dirty = true;
  41613. },
  41614. enumerable: true,
  41615. configurable: true
  41616. });
  41617. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41618. /**
  41619. * Gets the highlights Density value.
  41620. * 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.
  41621. * Values less than zero provide a filter of opposite hue.
  41622. */
  41623. get: function () {
  41624. return this._highlightsDensity;
  41625. },
  41626. /**
  41627. * Sets the highlights Density value.
  41628. * 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.
  41629. * Values less than zero provide a filter of opposite hue.
  41630. */
  41631. set: function (value) {
  41632. this._highlightsDensity = value;
  41633. this._dirty = true;
  41634. },
  41635. enumerable: true,
  41636. configurable: true
  41637. });
  41638. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41639. /**
  41640. * Gets the highlights Saturation value.
  41641. * 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.
  41642. */
  41643. get: function () {
  41644. return this._highlightsSaturation;
  41645. },
  41646. /**
  41647. * Sets the highlights Saturation value.
  41648. * 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.
  41649. */
  41650. set: function (value) {
  41651. this._highlightsSaturation = value;
  41652. this._dirty = true;
  41653. },
  41654. enumerable: true,
  41655. configurable: true
  41656. });
  41657. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41658. /**
  41659. * Gets the highlights Exposure value.
  41660. * 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.
  41661. */
  41662. get: function () {
  41663. return this._highlightsExposure;
  41664. },
  41665. /**
  41666. * Sets the highlights Exposure value.
  41667. * 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.
  41668. */
  41669. set: function (value) {
  41670. this._highlightsExposure = value;
  41671. this._dirty = true;
  41672. },
  41673. enumerable: true,
  41674. configurable: true
  41675. });
  41676. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41677. /**
  41678. * Gets the midtones Hue value.
  41679. * 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).
  41680. */
  41681. get: function () {
  41682. return this._midtonesHue;
  41683. },
  41684. /**
  41685. * Sets the midtones Hue value.
  41686. * 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).
  41687. */
  41688. set: function (value) {
  41689. this._midtonesHue = value;
  41690. this._dirty = true;
  41691. },
  41692. enumerable: true,
  41693. configurable: true
  41694. });
  41695. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41696. /**
  41697. * Gets the midtones Density value.
  41698. * 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.
  41699. * Values less than zero provide a filter of opposite hue.
  41700. */
  41701. get: function () {
  41702. return this._midtonesDensity;
  41703. },
  41704. /**
  41705. * Sets the midtones Density value.
  41706. * 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.
  41707. * Values less than zero provide a filter of opposite hue.
  41708. */
  41709. set: function (value) {
  41710. this._midtonesDensity = value;
  41711. this._dirty = true;
  41712. },
  41713. enumerable: true,
  41714. configurable: true
  41715. });
  41716. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41717. /**
  41718. * Gets the midtones Saturation value.
  41719. * 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.
  41720. */
  41721. get: function () {
  41722. return this._midtonesSaturation;
  41723. },
  41724. /**
  41725. * Sets the midtones Saturation value.
  41726. * 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.
  41727. */
  41728. set: function (value) {
  41729. this._midtonesSaturation = value;
  41730. this._dirty = true;
  41731. },
  41732. enumerable: true,
  41733. configurable: true
  41734. });
  41735. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41736. /**
  41737. * Gets the midtones Exposure value.
  41738. * 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.
  41739. */
  41740. get: function () {
  41741. return this._midtonesExposure;
  41742. },
  41743. /**
  41744. * Sets the midtones Exposure value.
  41745. * 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.
  41746. */
  41747. set: function (value) {
  41748. this._midtonesExposure = value;
  41749. this._dirty = true;
  41750. },
  41751. enumerable: true,
  41752. configurable: true
  41753. });
  41754. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41755. /**
  41756. * Gets the shadows Hue value.
  41757. * 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).
  41758. */
  41759. get: function () {
  41760. return this._shadowsHue;
  41761. },
  41762. /**
  41763. * Sets the shadows Hue value.
  41764. * 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).
  41765. */
  41766. set: function (value) {
  41767. this._shadowsHue = value;
  41768. this._dirty = true;
  41769. },
  41770. enumerable: true,
  41771. configurable: true
  41772. });
  41773. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41774. /**
  41775. * Gets the shadows Density value.
  41776. * 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.
  41777. * Values less than zero provide a filter of opposite hue.
  41778. */
  41779. get: function () {
  41780. return this._shadowsDensity;
  41781. },
  41782. /**
  41783. * Sets the shadows Density value.
  41784. * 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.
  41785. * Values less than zero provide a filter of opposite hue.
  41786. */
  41787. set: function (value) {
  41788. this._shadowsDensity = value;
  41789. this._dirty = true;
  41790. },
  41791. enumerable: true,
  41792. configurable: true
  41793. });
  41794. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41795. /**
  41796. * Gets the shadows Saturation value.
  41797. * 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.
  41798. */
  41799. get: function () {
  41800. return this._shadowsSaturation;
  41801. },
  41802. /**
  41803. * Sets the shadows Saturation value.
  41804. * 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.
  41805. */
  41806. set: function (value) {
  41807. this._shadowsSaturation = value;
  41808. this._dirty = true;
  41809. },
  41810. enumerable: true,
  41811. configurable: true
  41812. });
  41813. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41814. /**
  41815. * Gets the shadows Exposure value.
  41816. * 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.
  41817. */
  41818. get: function () {
  41819. return this._shadowsExposure;
  41820. },
  41821. /**
  41822. * Sets the shadows Exposure value.
  41823. * 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.
  41824. */
  41825. set: function (value) {
  41826. this._shadowsExposure = value;
  41827. this._dirty = true;
  41828. },
  41829. enumerable: true,
  41830. configurable: true
  41831. });
  41832. ColorCurves.prototype.getClassName = function () {
  41833. return "ColorCurves";
  41834. };
  41835. /**
  41836. * Binds the color curves to the shader.
  41837. * @param colorCurves The color curve to bind
  41838. * @param effect The effect to bind to
  41839. */
  41840. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41841. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41842. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41843. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41844. if (colorCurves._dirty) {
  41845. colorCurves._dirty = false;
  41846. // Fill in global info.
  41847. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41848. // Compute highlights info.
  41849. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41850. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41851. // Compute midtones info.
  41852. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41853. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41854. // Compute shadows info.
  41855. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41856. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41857. // Compute deltas (neutral is midtones).
  41858. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41859. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41860. }
  41861. if (effect) {
  41862. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41863. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41864. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41865. }
  41866. };
  41867. /**
  41868. * Prepare the list of uniforms associated with the ColorCurves effects.
  41869. * @param uniformsList The list of uniforms used in the effect
  41870. */
  41871. ColorCurves.PrepareUniforms = function (uniformsList) {
  41872. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41873. };
  41874. /**
  41875. * Returns color grading data based on a hue, density, saturation and exposure value.
  41876. * @param filterHue The hue of the color filter.
  41877. * @param filterDensity The density of the color filter.
  41878. * @param saturation The saturation.
  41879. * @param exposure The exposure.
  41880. * @param result The result data container.
  41881. */
  41882. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41883. if (hue == null) {
  41884. return;
  41885. }
  41886. hue = ColorCurves.clamp(hue, 0, 360);
  41887. density = ColorCurves.clamp(density, -100, 100);
  41888. saturation = ColorCurves.clamp(saturation, -100, 100);
  41889. exposure = ColorCurves.clamp(exposure, -100, 100);
  41890. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41891. // so that the maximum filter density is only 50% control. This provides fine control
  41892. // for small values and reasonable range.
  41893. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41894. density *= 0.5;
  41895. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41896. if (density < 0) {
  41897. density *= -1;
  41898. hue = (hue + 180) % 360;
  41899. }
  41900. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41901. result.scaleToRef(2, result);
  41902. result.a = 1 + 0.01 * saturation;
  41903. };
  41904. /**
  41905. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41906. * @param value The input slider value in range [-100,100].
  41907. * @returns Adjusted value.
  41908. */
  41909. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41910. value /= 100;
  41911. var x = Math.abs(value);
  41912. x = Math.pow(x, 2);
  41913. if (value < 0) {
  41914. x *= -1;
  41915. }
  41916. x *= 100;
  41917. return x;
  41918. };
  41919. /**
  41920. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41921. * @param hue The hue (H) input.
  41922. * @param saturation The saturation (S) input.
  41923. * @param brightness The brightness (B) input.
  41924. * @result An RGBA color represented as Vector4.
  41925. */
  41926. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41927. var h = ColorCurves.clamp(hue, 0, 360);
  41928. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41929. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41930. if (s === 0) {
  41931. result.r = v;
  41932. result.g = v;
  41933. result.b = v;
  41934. }
  41935. else {
  41936. // sector 0 to 5
  41937. h /= 60;
  41938. var i = Math.floor(h);
  41939. // fractional part of h
  41940. var f = h - i;
  41941. var p = v * (1 - s);
  41942. var q = v * (1 - s * f);
  41943. var t = v * (1 - s * (1 - f));
  41944. switch (i) {
  41945. case 0:
  41946. result.r = v;
  41947. result.g = t;
  41948. result.b = p;
  41949. break;
  41950. case 1:
  41951. result.r = q;
  41952. result.g = v;
  41953. result.b = p;
  41954. break;
  41955. case 2:
  41956. result.r = p;
  41957. result.g = v;
  41958. result.b = t;
  41959. break;
  41960. case 3:
  41961. result.r = p;
  41962. result.g = q;
  41963. result.b = v;
  41964. break;
  41965. case 4:
  41966. result.r = t;
  41967. result.g = p;
  41968. result.b = v;
  41969. break;
  41970. default:// case 5:
  41971. result.r = v;
  41972. result.g = p;
  41973. result.b = q;
  41974. break;
  41975. }
  41976. }
  41977. result.a = 1;
  41978. };
  41979. /**
  41980. * Returns a value clamped between min and max
  41981. * @param value The value to clamp
  41982. * @param min The minimum of value
  41983. * @param max The maximum of value
  41984. * @returns The clamped value.
  41985. */
  41986. ColorCurves.clamp = function (value, min, max) {
  41987. return Math.min(Math.max(value, min), max);
  41988. };
  41989. /**
  41990. * Clones the current color curve instance.
  41991. * @return The cloned curves
  41992. */
  41993. ColorCurves.prototype.clone = function () {
  41994. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41995. };
  41996. /**
  41997. * Serializes the current color curve instance to a json representation.
  41998. * @return a JSON representation
  41999. */
  42000. ColorCurves.prototype.serialize = function () {
  42001. return BABYLON.SerializationHelper.Serialize(this);
  42002. };
  42003. /**
  42004. * Parses the color curve from a json representation.
  42005. * @param source the JSON source to parse
  42006. * @return The parsed curves
  42007. */
  42008. ColorCurves.Parse = function (source) {
  42009. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42010. };
  42011. __decorate([
  42012. BABYLON.serialize()
  42013. ], ColorCurves.prototype, "_globalHue", void 0);
  42014. __decorate([
  42015. BABYLON.serialize()
  42016. ], ColorCurves.prototype, "_globalDensity", void 0);
  42017. __decorate([
  42018. BABYLON.serialize()
  42019. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42020. __decorate([
  42021. BABYLON.serialize()
  42022. ], ColorCurves.prototype, "_globalExposure", void 0);
  42023. __decorate([
  42024. BABYLON.serialize()
  42025. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42026. __decorate([
  42027. BABYLON.serialize()
  42028. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42029. __decorate([
  42030. BABYLON.serialize()
  42031. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42032. __decorate([
  42033. BABYLON.serialize()
  42034. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42035. __decorate([
  42036. BABYLON.serialize()
  42037. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42038. __decorate([
  42039. BABYLON.serialize()
  42040. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42041. __decorate([
  42042. BABYLON.serialize()
  42043. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42044. __decorate([
  42045. BABYLON.serialize()
  42046. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42047. return ColorCurves;
  42048. }());
  42049. BABYLON.ColorCurves = ColorCurves;
  42050. })(BABYLON || (BABYLON = {}));
  42051. //# sourceMappingURL=babylon.colorCurves.js.map
  42052. var BABYLON;
  42053. (function (BABYLON) {
  42054. var PostProcessRenderPipelineManager = (function () {
  42055. function PostProcessRenderPipelineManager() {
  42056. this._renderPipelines = {};
  42057. }
  42058. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  42059. this._renderPipelines[renderPipeline._name] = renderPipeline;
  42060. };
  42061. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  42062. var renderPipeline = this._renderPipelines[renderPipelineName];
  42063. if (!renderPipeline) {
  42064. return;
  42065. }
  42066. renderPipeline._attachCameras(cameras, unique);
  42067. };
  42068. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  42069. var renderPipeline = this._renderPipelines[renderPipelineName];
  42070. if (!renderPipeline) {
  42071. return;
  42072. }
  42073. renderPipeline._detachCameras(cameras);
  42074. };
  42075. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42076. var renderPipeline = this._renderPipelines[renderPipelineName];
  42077. if (!renderPipeline) {
  42078. return;
  42079. }
  42080. renderPipeline._enableEffect(renderEffectName, cameras);
  42081. };
  42082. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42083. var renderPipeline = this._renderPipelines[renderPipelineName];
  42084. if (!renderPipeline) {
  42085. return;
  42086. }
  42087. renderPipeline._disableEffect(renderEffectName, cameras);
  42088. };
  42089. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  42090. var renderPipeline = this._renderPipelines[renderPipelineName];
  42091. if (!renderPipeline) {
  42092. return;
  42093. }
  42094. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  42095. };
  42096. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  42097. var renderPipeline = this._renderPipelines[renderPipelineName];
  42098. if (!renderPipeline) {
  42099. return;
  42100. }
  42101. renderPipeline._disableDisplayOnlyPass(cameras);
  42102. };
  42103. PostProcessRenderPipelineManager.prototype.update = function () {
  42104. for (var renderPipelineName in this._renderPipelines) {
  42105. var pipeline = this._renderPipelines[renderPipelineName];
  42106. if (!pipeline.isSupported) {
  42107. pipeline.dispose();
  42108. delete this._renderPipelines[renderPipelineName];
  42109. }
  42110. else {
  42111. pipeline._update();
  42112. }
  42113. }
  42114. };
  42115. return PostProcessRenderPipelineManager;
  42116. }());
  42117. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  42118. })(BABYLON || (BABYLON = {}));
  42119. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  42120. var BABYLON;
  42121. (function (BABYLON) {
  42122. var PostProcessRenderPass = (function () {
  42123. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  42124. this._enabled = true;
  42125. this._refCount = 0;
  42126. this._name = name;
  42127. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  42128. this.setRenderList(renderList);
  42129. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  42130. this._renderTexture.onAfterRenderObservable.add(afterRender);
  42131. this._scene = scene;
  42132. this._renderList = renderList;
  42133. }
  42134. // private
  42135. PostProcessRenderPass.prototype._incRefCount = function () {
  42136. if (this._refCount === 0) {
  42137. this._scene.customRenderTargets.push(this._renderTexture);
  42138. }
  42139. return ++this._refCount;
  42140. };
  42141. PostProcessRenderPass.prototype._decRefCount = function () {
  42142. this._refCount--;
  42143. if (this._refCount <= 0) {
  42144. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  42145. }
  42146. return this._refCount;
  42147. };
  42148. PostProcessRenderPass.prototype._update = function () {
  42149. this.setRenderList(this._renderList);
  42150. };
  42151. // public
  42152. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  42153. this._renderTexture.renderList = renderList;
  42154. };
  42155. PostProcessRenderPass.prototype.getRenderTexture = function () {
  42156. return this._renderTexture;
  42157. };
  42158. return PostProcessRenderPass;
  42159. }());
  42160. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  42161. })(BABYLON || (BABYLON = {}));
  42162. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  42163. var BABYLON;
  42164. (function (BABYLON) {
  42165. var PostProcessRenderEffect = (function () {
  42166. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  42167. this._engine = engine;
  42168. this._name = name;
  42169. this._singleInstance = singleInstance || true;
  42170. this._getPostProcess = getPostProcess;
  42171. this._cameras = [];
  42172. this._indicesForCamera = [];
  42173. this._postProcesses = {};
  42174. this._renderPasses = {};
  42175. this._renderEffectAsPasses = {};
  42176. }
  42177. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  42178. get: function () {
  42179. for (var index in this._postProcesses) {
  42180. if (!this._postProcesses[index].isSupported) {
  42181. return false;
  42182. }
  42183. }
  42184. return true;
  42185. },
  42186. enumerable: true,
  42187. configurable: true
  42188. });
  42189. PostProcessRenderEffect.prototype._update = function () {
  42190. for (var renderPassName in this._renderPasses) {
  42191. this._renderPasses[renderPassName]._update();
  42192. }
  42193. };
  42194. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  42195. this._renderPasses[renderPass._name] = renderPass;
  42196. this._linkParameters();
  42197. };
  42198. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  42199. delete this._renderPasses[renderPass._name];
  42200. this._linkParameters();
  42201. };
  42202. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  42203. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  42204. this._linkParameters();
  42205. };
  42206. PostProcessRenderEffect.prototype.getPass = function (passName) {
  42207. for (var renderPassName in this._renderPasses) {
  42208. if (renderPassName === passName) {
  42209. return this._renderPasses[passName];
  42210. }
  42211. }
  42212. };
  42213. PostProcessRenderEffect.prototype.emptyPasses = function () {
  42214. this._renderPasses = {};
  42215. this._linkParameters();
  42216. };
  42217. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  42218. var cameraKey;
  42219. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42220. for (var i = 0; i < _cam.length; i++) {
  42221. var camera = _cam[i];
  42222. var cameraName = camera.name;
  42223. if (this._singleInstance) {
  42224. cameraKey = 0;
  42225. }
  42226. else {
  42227. cameraKey = cameraName;
  42228. }
  42229. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  42230. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  42231. if (!this._indicesForCamera[cameraName]) {
  42232. this._indicesForCamera[cameraName] = [];
  42233. }
  42234. this._indicesForCamera[cameraName].push(index);
  42235. if (this._cameras.indexOf(camera) === -1) {
  42236. this._cameras[cameraName] = camera;
  42237. }
  42238. for (var passName in this._renderPasses) {
  42239. this._renderPasses[passName]._incRefCount();
  42240. }
  42241. }
  42242. this._linkParameters();
  42243. };
  42244. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  42245. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42246. for (var i = 0; i < _cam.length; i++) {
  42247. var camera = _cam[i];
  42248. var cameraName = camera.name;
  42249. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42250. var index = this._cameras.indexOf(cameraName);
  42251. this._indicesForCamera.splice(index, 1);
  42252. this._cameras.splice(index, 1);
  42253. for (var passName in this._renderPasses) {
  42254. this._renderPasses[passName]._decRefCount();
  42255. }
  42256. }
  42257. };
  42258. PostProcessRenderEffect.prototype._enable = function (cameras) {
  42259. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42260. for (var i = 0; i < _cam.length; i++) {
  42261. var camera = _cam[i];
  42262. var cameraName = camera.name;
  42263. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  42264. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  42265. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  42266. }
  42267. }
  42268. for (var passName in this._renderPasses) {
  42269. this._renderPasses[passName]._incRefCount();
  42270. }
  42271. }
  42272. };
  42273. PostProcessRenderEffect.prototype._disable = function (cameras) {
  42274. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42275. for (var i = 0; i < _cam.length; i++) {
  42276. var camera = _cam[i];
  42277. var cameraName = camera.Name;
  42278. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42279. for (var passName in this._renderPasses) {
  42280. this._renderPasses[passName]._decRefCount();
  42281. }
  42282. }
  42283. };
  42284. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  42285. if (this._singleInstance) {
  42286. return this._postProcesses[0];
  42287. }
  42288. else {
  42289. return this._postProcesses[camera.name];
  42290. }
  42291. };
  42292. PostProcessRenderEffect.prototype._linkParameters = function () {
  42293. var _this = this;
  42294. for (var index in this._postProcesses) {
  42295. if (this.applyParameters) {
  42296. this.applyParameters(this._postProcesses[index]);
  42297. }
  42298. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  42299. _this._linkTextures(effect);
  42300. });
  42301. }
  42302. };
  42303. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  42304. for (var renderPassName in this._renderPasses) {
  42305. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  42306. }
  42307. for (var renderEffectName in this._renderEffectAsPasses) {
  42308. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  42309. }
  42310. };
  42311. return PostProcessRenderEffect;
  42312. }());
  42313. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  42314. })(BABYLON || (BABYLON = {}));
  42315. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  42316. var BABYLON;
  42317. (function (BABYLON) {
  42318. var PostProcessRenderPipeline = (function () {
  42319. function PostProcessRenderPipeline(engine, name) {
  42320. this._engine = engine;
  42321. this._name = name;
  42322. this._renderEffects = new Array();
  42323. this._renderEffectsForIsolatedPass = new Array();
  42324. this._cameras = [];
  42325. }
  42326. PostProcessRenderPipeline.prototype.getClassName = function () {
  42327. return "PostProcessRenderPipeline";
  42328. };
  42329. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  42330. get: function () {
  42331. for (var renderEffectName in this._renderEffects) {
  42332. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42333. if (!this._renderEffects[renderEffectName].isSupported) {
  42334. return false;
  42335. }
  42336. }
  42337. }
  42338. return true;
  42339. },
  42340. enumerable: true,
  42341. configurable: true
  42342. });
  42343. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  42344. this._renderEffects[renderEffect._name] = renderEffect;
  42345. };
  42346. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  42347. var renderEffects = this._renderEffects[renderEffectName];
  42348. if (!renderEffects) {
  42349. return;
  42350. }
  42351. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42352. };
  42353. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  42354. var renderEffects = this._renderEffects[renderEffectName];
  42355. if (!renderEffects) {
  42356. return;
  42357. }
  42358. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42359. };
  42360. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  42361. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42362. var indicesToDelete = [];
  42363. var i;
  42364. for (i = 0; i < _cam.length; i++) {
  42365. var camera = _cam[i];
  42366. var cameraName = camera.name;
  42367. if (this._cameras.indexOf(camera) === -1) {
  42368. this._cameras[cameraName] = camera;
  42369. }
  42370. else if (unique) {
  42371. indicesToDelete.push(i);
  42372. }
  42373. }
  42374. for (i = 0; i < indicesToDelete.length; i++) {
  42375. cameras.splice(indicesToDelete[i], 1);
  42376. }
  42377. for (var renderEffectName in this._renderEffects) {
  42378. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42379. this._renderEffects[renderEffectName]._attachCameras(_cam);
  42380. }
  42381. }
  42382. };
  42383. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  42384. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42385. for (var renderEffectName in this._renderEffects) {
  42386. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42387. this._renderEffects[renderEffectName]._detachCameras(_cam);
  42388. }
  42389. }
  42390. for (var i = 0; i < _cam.length; i++) {
  42391. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  42392. }
  42393. };
  42394. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  42395. var _this = this;
  42396. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42397. var pass = null;
  42398. var renderEffectName;
  42399. for (renderEffectName in this._renderEffects) {
  42400. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42401. pass = this._renderEffects[renderEffectName].getPass(passName);
  42402. if (pass != null) {
  42403. break;
  42404. }
  42405. }
  42406. }
  42407. if (pass === null) {
  42408. return;
  42409. }
  42410. for (renderEffectName in this._renderEffects) {
  42411. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42412. this._renderEffects[renderEffectName]._disable(_cam);
  42413. }
  42414. }
  42415. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  42416. for (var i = 0; i < _cam.length; i++) {
  42417. var camera = _cam[i];
  42418. var cameraName = camera.name;
  42419. 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); });
  42420. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  42421. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  42422. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  42423. }
  42424. };
  42425. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  42426. var _this = this;
  42427. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42428. for (var i = 0; i < _cam.length; i++) {
  42429. var camera = _cam[i];
  42430. var cameraName = camera.name;
  42431. 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); });
  42432. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  42433. }
  42434. for (var renderEffectName in this._renderEffects) {
  42435. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42436. this._renderEffects[renderEffectName]._enable(_cam);
  42437. }
  42438. }
  42439. };
  42440. PostProcessRenderPipeline.prototype._update = function () {
  42441. for (var renderEffectName in this._renderEffects) {
  42442. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42443. this._renderEffects[renderEffectName]._update();
  42444. }
  42445. }
  42446. for (var i = 0; i < this._cameras.length; i++) {
  42447. var cameraName = this._cameras[i].name;
  42448. if (this._renderEffectsForIsolatedPass[cameraName]) {
  42449. this._renderEffectsForIsolatedPass[cameraName]._update();
  42450. }
  42451. }
  42452. };
  42453. PostProcessRenderPipeline.prototype._reset = function () {
  42454. this._renderEffects = new Array();
  42455. this._renderEffectsForIsolatedPass = new Array();
  42456. };
  42457. PostProcessRenderPipeline.prototype.dispose = function () {
  42458. // Must be implemented by children
  42459. };
  42460. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  42461. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  42462. __decorate([
  42463. BABYLON.serialize()
  42464. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  42465. return PostProcessRenderPipeline;
  42466. }());
  42467. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  42468. })(BABYLON || (BABYLON = {}));
  42469. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  42470. var BABYLON;
  42471. (function (BABYLON) {
  42472. var DefaultRenderingPipeline = (function (_super) {
  42473. __extends(DefaultRenderingPipeline, _super);
  42474. /**
  42475. * @constructor
  42476. * @param {string} name - The rendering pipeline name
  42477. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  42478. * @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)
  42479. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  42480. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  42481. */
  42482. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  42483. if (automaticBuild === void 0) { automaticBuild = true; }
  42484. var _this = _super.call(this, scene.getEngine(), name) || this;
  42485. _this.PassPostProcessId = "PassPostProcessEffect";
  42486. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  42487. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  42488. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  42489. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  42490. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  42491. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  42492. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  42493. // IAnimatable
  42494. _this.animations = [];
  42495. // Values
  42496. _this._bloomEnabled = false;
  42497. _this._fxaaEnabled = false;
  42498. _this._imageProcessingEnabled = true;
  42499. _this._bloomScale = 0.6;
  42500. _this._buildAllowed = true;
  42501. /**
  42502. * Specifies the size of the bloom blur kernel, relative to the final output size
  42503. */
  42504. _this.bloomKernel = 64;
  42505. /**
  42506. * Specifies the weight of the bloom in the final rendering
  42507. */
  42508. _this._bloomWeight = 0.15;
  42509. _this._cameras = cameras || [];
  42510. _this._buildAllowed = automaticBuild;
  42511. // Initialize
  42512. _this._scene = scene;
  42513. var caps = _this._scene.getEngine().getCaps();
  42514. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  42515. // Misc
  42516. if (_this._hdr) {
  42517. if (caps.textureHalfFloatRender) {
  42518. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  42519. }
  42520. else if (caps.textureFloatRender) {
  42521. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42522. }
  42523. }
  42524. else {
  42525. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42526. }
  42527. // Attach
  42528. scene.postProcessRenderPipelineManager.addPipeline(_this);
  42529. _this._buildPipeline();
  42530. return _this;
  42531. }
  42532. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  42533. get: function () {
  42534. return this._bloomWeight;
  42535. },
  42536. set: function (value) {
  42537. if (this._bloomWeight === value) {
  42538. return;
  42539. }
  42540. this._bloomWeight = value;
  42541. if (this._hdr && this.copyBack) {
  42542. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  42543. }
  42544. },
  42545. enumerable: true,
  42546. configurable: true
  42547. });
  42548. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  42549. get: function () {
  42550. return this._bloomScale;
  42551. },
  42552. set: function (value) {
  42553. if (this._bloomScale === value) {
  42554. return;
  42555. }
  42556. this._bloomScale = value;
  42557. this._buildPipeline();
  42558. },
  42559. enumerable: true,
  42560. configurable: true
  42561. });
  42562. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  42563. get: function () {
  42564. return this._bloomEnabled;
  42565. },
  42566. set: function (enabled) {
  42567. if (this._bloomEnabled === enabled) {
  42568. return;
  42569. }
  42570. this._bloomEnabled = enabled;
  42571. this._buildPipeline();
  42572. },
  42573. enumerable: true,
  42574. configurable: true
  42575. });
  42576. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  42577. get: function () {
  42578. return this._fxaaEnabled;
  42579. },
  42580. set: function (enabled) {
  42581. if (this._fxaaEnabled === enabled) {
  42582. return;
  42583. }
  42584. this._fxaaEnabled = enabled;
  42585. this._buildPipeline();
  42586. },
  42587. enumerable: true,
  42588. configurable: true
  42589. });
  42590. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  42591. get: function () {
  42592. return this._imageProcessingEnabled;
  42593. },
  42594. set: function (enabled) {
  42595. if (this._imageProcessingEnabled === enabled) {
  42596. return;
  42597. }
  42598. this._imageProcessingEnabled = enabled;
  42599. this._buildPipeline();
  42600. },
  42601. enumerable: true,
  42602. configurable: true
  42603. });
  42604. /**
  42605. * Force the compilation of the entire pipeline.
  42606. */
  42607. DefaultRenderingPipeline.prototype.prepare = function () {
  42608. var previousState = this._buildAllowed;
  42609. this._buildAllowed = true;
  42610. this._buildPipeline();
  42611. this._buildAllowed = previousState;
  42612. };
  42613. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  42614. var _this = this;
  42615. if (!this._buildAllowed) {
  42616. return;
  42617. }
  42618. var engine = this._scene.getEngine();
  42619. this._disposePostProcesses();
  42620. this._reset();
  42621. if (this.bloomEnabled) {
  42622. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42623. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  42624. if (!this._hdr) {
  42625. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42626. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  42627. this.highlights.autoClear = false;
  42628. this.highlights.alwaysForcePOT = true;
  42629. }
  42630. 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);
  42631. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  42632. this.blurX.alwaysForcePOT = true;
  42633. this.blurX.autoClear = false;
  42634. this.blurX.onActivateObservable.add(function () {
  42635. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  42636. _this.blurX.kernel = _this.bloomKernel * dw;
  42637. });
  42638. 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);
  42639. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  42640. this.blurY.alwaysForcePOT = true;
  42641. this.blurY.autoClear = false;
  42642. this.blurY.onActivateObservable.add(function () {
  42643. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  42644. _this.blurY.kernel = _this.bloomKernel * dh;
  42645. });
  42646. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42647. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  42648. this.copyBack.alwaysForcePOT = true;
  42649. if (this._hdr) {
  42650. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  42651. var w = this.bloomWeight;
  42652. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  42653. }
  42654. else {
  42655. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  42656. }
  42657. this.copyBack.autoClear = false;
  42658. }
  42659. if (this._imageProcessingEnabled) {
  42660. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42661. if (this._hdr) {
  42662. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  42663. }
  42664. }
  42665. if (this.fxaaEnabled) {
  42666. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42667. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  42668. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42669. }
  42670. else {
  42671. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42672. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  42673. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42674. }
  42675. if (this.bloomEnabled) {
  42676. if (this._hdr) {
  42677. this.copyBack.shareOutputWith(this.blurX);
  42678. if (this.imageProcessing) {
  42679. this.imageProcessing.shareOutputWith(this.pass);
  42680. this.imageProcessing.autoClear = false;
  42681. }
  42682. else if (this.fxaa) {
  42683. this.fxaa.shareOutputWith(this.pass);
  42684. }
  42685. else {
  42686. this.finalMerge.shareOutputWith(this.pass);
  42687. }
  42688. }
  42689. else {
  42690. if (this.fxaa) {
  42691. this.fxaa.shareOutputWith(this.pass);
  42692. }
  42693. else {
  42694. this.finalMerge.shareOutputWith(this.pass);
  42695. }
  42696. }
  42697. }
  42698. if (this._cameras !== null) {
  42699. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  42700. }
  42701. };
  42702. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  42703. for (var i = 0; i < this._cameras.length; i++) {
  42704. var camera = this._cameras[i];
  42705. if (this.pass) {
  42706. this.pass.dispose(camera);
  42707. }
  42708. if (this.highlights) {
  42709. this.highlights.dispose(camera);
  42710. }
  42711. if (this.blurX) {
  42712. this.blurX.dispose(camera);
  42713. }
  42714. if (this.blurY) {
  42715. this.blurY.dispose(camera);
  42716. }
  42717. if (this.copyBack) {
  42718. this.copyBack.dispose(camera);
  42719. }
  42720. if (this.imageProcessing) {
  42721. this.imageProcessing.dispose(camera);
  42722. }
  42723. if (this.fxaa) {
  42724. this.fxaa.dispose(camera);
  42725. }
  42726. if (this.finalMerge) {
  42727. this.finalMerge.dispose(camera);
  42728. }
  42729. }
  42730. this.pass = null;
  42731. this.highlights = null;
  42732. this.blurX = null;
  42733. this.blurY = null;
  42734. this.copyBack = null;
  42735. this.imageProcessing = null;
  42736. this.fxaa = null;
  42737. this.finalMerge = null;
  42738. };
  42739. // Dispose
  42740. DefaultRenderingPipeline.prototype.dispose = function () {
  42741. this._disposePostProcesses();
  42742. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  42743. _super.prototype.dispose.call(this);
  42744. };
  42745. // Serialize rendering pipeline
  42746. DefaultRenderingPipeline.prototype.serialize = function () {
  42747. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42748. serializationObject.customType = "DefaultRenderingPipeline";
  42749. return serializationObject;
  42750. };
  42751. // Parse serialized pipeline
  42752. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  42753. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  42754. };
  42755. __decorate([
  42756. BABYLON.serialize()
  42757. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  42758. __decorate([
  42759. BABYLON.serialize()
  42760. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  42761. __decorate([
  42762. BABYLON.serialize()
  42763. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  42764. __decorate([
  42765. BABYLON.serialize()
  42766. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  42767. __decorate([
  42768. BABYLON.serialize()
  42769. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  42770. __decorate([
  42771. BABYLON.serialize()
  42772. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  42773. __decorate([
  42774. BABYLON.serialize()
  42775. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  42776. __decorate([
  42777. BABYLON.serialize()
  42778. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  42779. return DefaultRenderingPipeline;
  42780. }(BABYLON.PostProcessRenderPipeline));
  42781. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  42782. })(BABYLON || (BABYLON = {}));
  42783. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  42784. var BABYLON;
  42785. (function (BABYLON) {
  42786. /**
  42787. * This groups together the common properties used for image processing either in direct forward pass
  42788. * or through post processing effect depending on the use of the image processing pipeline in your scene
  42789. * or not.
  42790. */
  42791. var ImageProcessingConfiguration = (function () {
  42792. function ImageProcessingConfiguration() {
  42793. /**
  42794. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  42795. */
  42796. this.colorCurves = new BABYLON.ColorCurves();
  42797. this._colorCurvesEnabled = false;
  42798. this._colorGradingEnabled = false;
  42799. this._colorGradingWithGreenDepth = false;
  42800. this._colorGradingBGR = false;
  42801. this._exposure = 1.0;
  42802. this._toneMappingEnabled = false;
  42803. this._contrast = 1.0;
  42804. /**
  42805. * Vignette stretch size.
  42806. */
  42807. this.vignetteStretch = 0;
  42808. /**
  42809. * Vignette centre X Offset.
  42810. */
  42811. this.vignetteCentreX = 0;
  42812. /**
  42813. * Vignette centre Y Offset.
  42814. */
  42815. this.vignetteCentreY = 0;
  42816. /**
  42817. * Vignette weight or intensity of the vignette effect.
  42818. */
  42819. this.vignetteWeight = 1.5;
  42820. /**
  42821. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  42822. * if vignetteEnabled is set to true.
  42823. */
  42824. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  42825. /**
  42826. * Camera field of view used by the Vignette effect.
  42827. */
  42828. this.vignetteCameraFov = 0.5;
  42829. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  42830. this._vignetteEnabled = false;
  42831. this._applyByPostProcess = false;
  42832. /**
  42833. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  42834. * @type {BABYLON.Observable}
  42835. */
  42836. this.onUpdateParameters = new BABYLON.Observable();
  42837. }
  42838. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  42839. /**
  42840. * Gets wether the color curves effect is enabled.
  42841. */
  42842. get: function () {
  42843. return this._colorCurvesEnabled;
  42844. },
  42845. /**
  42846. * Sets wether the color curves effect is enabled.
  42847. */
  42848. set: function (value) {
  42849. if (this._colorCurvesEnabled === value) {
  42850. return;
  42851. }
  42852. this._colorCurvesEnabled = value;
  42853. this._updateParameters();
  42854. },
  42855. enumerable: true,
  42856. configurable: true
  42857. });
  42858. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  42859. /**
  42860. * Gets wether the color grading effect is enabled.
  42861. */
  42862. get: function () {
  42863. return this._colorGradingEnabled;
  42864. },
  42865. /**
  42866. * Sets wether the color grading effect is enabled.
  42867. */
  42868. set: function (value) {
  42869. if (this._colorGradingEnabled === value) {
  42870. return;
  42871. }
  42872. this._colorGradingEnabled = value;
  42873. this._updateParameters();
  42874. },
  42875. enumerable: true,
  42876. configurable: true
  42877. });
  42878. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  42879. /**
  42880. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  42881. */
  42882. get: function () {
  42883. return this._colorGradingWithGreenDepth;
  42884. },
  42885. /**
  42886. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  42887. */
  42888. set: function (value) {
  42889. if (this._colorGradingWithGreenDepth === value) {
  42890. return;
  42891. }
  42892. this._colorGradingWithGreenDepth = value;
  42893. this._updateParameters();
  42894. },
  42895. enumerable: true,
  42896. configurable: true
  42897. });
  42898. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  42899. /**
  42900. * Gets wether the color grading texture contains BGR values.
  42901. */
  42902. get: function () {
  42903. return this._colorGradingBGR;
  42904. },
  42905. /**
  42906. * Sets wether the color grading texture contains BGR values.
  42907. */
  42908. set: function (value) {
  42909. if (this._colorGradingBGR === value) {
  42910. return;
  42911. }
  42912. this._colorGradingBGR = value;
  42913. this._updateParameters();
  42914. },
  42915. enumerable: true,
  42916. configurable: true
  42917. });
  42918. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  42919. /**
  42920. * Gets the Exposure used in the effect.
  42921. */
  42922. get: function () {
  42923. return this._exposure;
  42924. },
  42925. /**
  42926. * Sets the Exposure used in the effect.
  42927. */
  42928. set: function (value) {
  42929. if (this._exposure === value) {
  42930. return;
  42931. }
  42932. this._exposure = value;
  42933. this._updateParameters();
  42934. },
  42935. enumerable: true,
  42936. configurable: true
  42937. });
  42938. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  42939. /**
  42940. * Gets wether the tone mapping effect is enabled.
  42941. */
  42942. get: function () {
  42943. return this._toneMappingEnabled;
  42944. },
  42945. /**
  42946. * Sets wether the tone mapping effect is enabled.
  42947. */
  42948. set: function (value) {
  42949. if (this._toneMappingEnabled === value) {
  42950. return;
  42951. }
  42952. this._toneMappingEnabled = value;
  42953. this._updateParameters();
  42954. },
  42955. enumerable: true,
  42956. configurable: true
  42957. });
  42958. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  42959. /**
  42960. * Gets the contrast used in the effect.
  42961. */
  42962. get: function () {
  42963. return this._contrast;
  42964. },
  42965. /**
  42966. * Sets the contrast used in the effect.
  42967. */
  42968. set: function (value) {
  42969. if (this._contrast === value) {
  42970. return;
  42971. }
  42972. this._contrast = value;
  42973. this._updateParameters();
  42974. },
  42975. enumerable: true,
  42976. configurable: true
  42977. });
  42978. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  42979. /**
  42980. * Gets the vignette blend mode allowing different kind of effect.
  42981. */
  42982. get: function () {
  42983. return this._vignetteBlendMode;
  42984. },
  42985. /**
  42986. * Sets the vignette blend mode allowing different kind of effect.
  42987. */
  42988. set: function (value) {
  42989. if (this._vignetteBlendMode === value) {
  42990. return;
  42991. }
  42992. this._vignetteBlendMode = value;
  42993. this._updateParameters();
  42994. },
  42995. enumerable: true,
  42996. configurable: true
  42997. });
  42998. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  42999. /**
  43000. * Gets wether the vignette effect is enabled.
  43001. */
  43002. get: function () {
  43003. return this._vignetteEnabled;
  43004. },
  43005. /**
  43006. * Sets wether the vignette effect is enabled.
  43007. */
  43008. set: function (value) {
  43009. if (this._vignetteEnabled === value) {
  43010. return;
  43011. }
  43012. this._vignetteEnabled = value;
  43013. this._updateParameters();
  43014. },
  43015. enumerable: true,
  43016. configurable: true
  43017. });
  43018. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  43019. /**
  43020. * Gets wether the image processing is applied through a post process or not.
  43021. */
  43022. get: function () {
  43023. return this._applyByPostProcess;
  43024. },
  43025. /**
  43026. * Sets wether the image processing is applied through a post process or not.
  43027. */
  43028. set: function (value) {
  43029. if (this._applyByPostProcess === value) {
  43030. return;
  43031. }
  43032. this._applyByPostProcess = value;
  43033. this._updateParameters();
  43034. },
  43035. enumerable: true,
  43036. configurable: true
  43037. });
  43038. /**
  43039. * Method called each time the image processing information changes requires to recompile the effect.
  43040. */
  43041. ImageProcessingConfiguration.prototype._updateParameters = function () {
  43042. this.onUpdateParameters.notifyObservers(this);
  43043. };
  43044. ImageProcessingConfiguration.prototype.getClassName = function () {
  43045. return "ImageProcessingConfiguration";
  43046. };
  43047. /**
  43048. * Prepare the list of uniforms associated with the Image Processing effects.
  43049. * @param uniformsList The list of uniforms used in the effect
  43050. * @param defines the list of defines currently in use
  43051. */
  43052. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  43053. if (defines.EXPOSURE) {
  43054. uniforms.push("exposureLinear");
  43055. }
  43056. if (defines.CONTRAST) {
  43057. uniforms.push("contrast");
  43058. }
  43059. if (defines.COLORGRADING) {
  43060. uniforms.push("colorTransformSettings");
  43061. }
  43062. if (defines.VIGNETTE) {
  43063. uniforms.push("vInverseScreenSize");
  43064. uniforms.push("vignetteSettings1");
  43065. uniforms.push("vignetteSettings2");
  43066. }
  43067. if (defines.COLORCURVES) {
  43068. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  43069. }
  43070. };
  43071. /**
  43072. * Prepare the list of samplers associated with the Image Processing effects.
  43073. * @param uniformsList The list of uniforms used in the effect
  43074. * @param defines the list of defines currently in use
  43075. */
  43076. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  43077. if (defines.COLORGRADING) {
  43078. samplersList.push("txColorTransform");
  43079. }
  43080. };
  43081. /**
  43082. * Prepare the list of defines associated to the shader.
  43083. * @param defines the list of defines to complete
  43084. */
  43085. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  43086. defines.VIGNETTE = this.vignetteEnabled;
  43087. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  43088. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  43089. defines.TONEMAPPING = this.toneMappingEnabled;
  43090. defines.CONTRAST = (this.contrast !== 1.0);
  43091. defines.EXPOSURE = (this.exposure !== 1.0);
  43092. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  43093. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  43094. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  43095. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  43096. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  43097. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  43098. };
  43099. /**
  43100. * Returns true if all the image processing information are ready.
  43101. */
  43102. ImageProcessingConfiguration.prototype.isReady = function () {
  43103. // Color Grading texure can not be none blocking.
  43104. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  43105. };
  43106. /**
  43107. * Binds the image processing to the shader.
  43108. * @param effect The effect to bind to
  43109. */
  43110. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  43111. if (aspectRatio === void 0) { aspectRatio = 1; }
  43112. // Color Curves
  43113. if (this._colorCurvesEnabled) {
  43114. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  43115. }
  43116. // Vignette
  43117. if (this._vignetteEnabled) {
  43118. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  43119. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  43120. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  43121. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  43122. var vignetteScaleX = vignetteScaleY * aspectRatio;
  43123. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  43124. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  43125. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  43126. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  43127. var vignettePower = -2.0 * this.vignetteWeight;
  43128. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  43129. }
  43130. // Exposure
  43131. effect.setFloat("exposureLinear", this.exposure);
  43132. // Contrast
  43133. effect.setFloat("contrast", this.contrast);
  43134. // Color transform settings
  43135. if (this.colorGradingTexture) {
  43136. effect.setTexture("txColorTransform", this.colorGradingTexture);
  43137. var textureSize = this.colorGradingTexture.getSize().height;
  43138. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  43139. 0.5 / textureSize, // textureOffset
  43140. textureSize, // textureSize
  43141. this.colorGradingTexture.level // weight
  43142. );
  43143. }
  43144. };
  43145. /**
  43146. * Clones the current image processing instance.
  43147. * @return The cloned image processing
  43148. */
  43149. ImageProcessingConfiguration.prototype.clone = function () {
  43150. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  43151. };
  43152. /**
  43153. * Serializes the current image processing instance to a json representation.
  43154. * @return a JSON representation
  43155. */
  43156. ImageProcessingConfiguration.prototype.serialize = function () {
  43157. return BABYLON.SerializationHelper.Serialize(this);
  43158. };
  43159. /**
  43160. * Parses the image processing from a json representation.
  43161. * @param source the JSON source to parse
  43162. * @return The parsed image processing
  43163. */
  43164. ImageProcessingConfiguration.Parse = function (source) {
  43165. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  43166. };
  43167. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  43168. /**
  43169. * Used to apply the vignette as a mix with the pixel color.
  43170. */
  43171. get: function () {
  43172. return this._VIGNETTEMODE_MULTIPLY;
  43173. },
  43174. enumerable: true,
  43175. configurable: true
  43176. });
  43177. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  43178. /**
  43179. * Used to apply the vignette as a replacement of the pixel color.
  43180. */
  43181. get: function () {
  43182. return this._VIGNETTEMODE_OPAQUE;
  43183. },
  43184. enumerable: true,
  43185. configurable: true
  43186. });
  43187. // Static constants associated to the image processing.
  43188. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  43189. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  43190. __decorate([
  43191. BABYLON.serializeAsColorCurves()
  43192. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  43193. __decorate([
  43194. BABYLON.serialize()
  43195. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  43196. __decorate([
  43197. BABYLON.serializeAsTexture()
  43198. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  43199. __decorate([
  43200. BABYLON.serialize()
  43201. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  43202. __decorate([
  43203. BABYLON.serialize()
  43204. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  43205. __decorate([
  43206. BABYLON.serialize()
  43207. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  43208. __decorate([
  43209. BABYLON.serialize()
  43210. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  43211. __decorate([
  43212. BABYLON.serialize()
  43213. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  43214. __decorate([
  43215. BABYLON.serialize()
  43216. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  43217. __decorate([
  43218. BABYLON.serialize()
  43219. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  43220. __decorate([
  43221. BABYLON.serialize()
  43222. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  43223. __decorate([
  43224. BABYLON.serialize()
  43225. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  43226. __decorate([
  43227. BABYLON.serialize()
  43228. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  43229. __decorate([
  43230. BABYLON.serializeAsColor4()
  43231. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  43232. __decorate([
  43233. BABYLON.serialize()
  43234. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  43235. __decorate([
  43236. BABYLON.serialize()
  43237. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  43238. __decorate([
  43239. BABYLON.serialize()
  43240. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  43241. __decorate([
  43242. BABYLON.serialize()
  43243. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  43244. return ImageProcessingConfiguration;
  43245. }());
  43246. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  43247. })(BABYLON || (BABYLON = {}));
  43248. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  43249. /// <reference path="babylon.mesh.ts" />
  43250. var BABYLON;
  43251. (function (BABYLON) {
  43252. var GroundMesh = (function (_super) {
  43253. __extends(GroundMesh, _super);
  43254. function GroundMesh(name, scene) {
  43255. var _this = _super.call(this, name, scene) || this;
  43256. _this.generateOctree = false;
  43257. _this._worldInverse = new BABYLON.Matrix();
  43258. return _this;
  43259. }
  43260. GroundMesh.prototype.getClassName = function () {
  43261. return "GroundMesh";
  43262. };
  43263. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  43264. get: function () {
  43265. return Math.min(this._subdivisionsX, this._subdivisionsY);
  43266. },
  43267. enumerable: true,
  43268. configurable: true
  43269. });
  43270. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  43271. get: function () {
  43272. return this._subdivisionsX;
  43273. },
  43274. enumerable: true,
  43275. configurable: true
  43276. });
  43277. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  43278. get: function () {
  43279. return this._subdivisionsY;
  43280. },
  43281. enumerable: true,
  43282. configurable: true
  43283. });
  43284. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  43285. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  43286. this._subdivisionsX = chunksCount;
  43287. this._subdivisionsY = chunksCount;
  43288. this.subdivide(chunksCount);
  43289. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  43290. };
  43291. /**
  43292. * Returns a height (y) value in the Worl system :
  43293. * the ground altitude at the coordinates (x, z) expressed in the World system.
  43294. * Returns the ground y position if (x, z) are outside the ground surface.
  43295. */
  43296. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  43297. var world = this.getWorldMatrix();
  43298. var invMat = BABYLON.Tmp.Matrix[5];
  43299. world.invertToRef(invMat);
  43300. var tmpVect = BABYLON.Tmp.Vector3[8];
  43301. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  43302. x = tmpVect.x;
  43303. z = tmpVect.z;
  43304. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43305. return this.position.y;
  43306. }
  43307. if (!this._heightQuads || this._heightQuads.length == 0) {
  43308. this._initHeightQuads();
  43309. this._computeHeightQuads();
  43310. }
  43311. var facet = this._getFacetAt(x, z);
  43312. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  43313. // return y in the World system
  43314. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  43315. return tmpVect.y;
  43316. };
  43317. /**
  43318. * Returns a normalized vector (Vector3) orthogonal to the ground
  43319. * at the ground coordinates (x, z) expressed in the World system.
  43320. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  43321. */
  43322. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  43323. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  43324. this.getNormalAtCoordinatesToRef(x, z, normal);
  43325. return normal;
  43326. };
  43327. /**
  43328. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  43329. * at the ground coordinates (x, z) expressed in the World system.
  43330. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  43331. * Returns the GroundMesh.
  43332. */
  43333. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  43334. var world = this.getWorldMatrix();
  43335. var tmpMat = BABYLON.Tmp.Matrix[5];
  43336. world.invertToRef(tmpMat);
  43337. var tmpVect = BABYLON.Tmp.Vector3[8];
  43338. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  43339. x = tmpVect.x;
  43340. z = tmpVect.z;
  43341. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43342. return this;
  43343. }
  43344. if (!this._heightQuads || this._heightQuads.length == 0) {
  43345. this._initHeightQuads();
  43346. this._computeHeightQuads();
  43347. }
  43348. var facet = this._getFacetAt(x, z);
  43349. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  43350. return this;
  43351. };
  43352. /**
  43353. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  43354. * if the ground has been updated.
  43355. * This can be used in the render loop.
  43356. * Returns the GroundMesh.
  43357. */
  43358. GroundMesh.prototype.updateCoordinateHeights = function () {
  43359. if (!this._heightQuads || this._heightQuads.length == 0) {
  43360. this._initHeightQuads();
  43361. }
  43362. this._computeHeightQuads();
  43363. return this;
  43364. };
  43365. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  43366. GroundMesh.prototype._getFacetAt = function (x, z) {
  43367. // retrieve col and row from x, z coordinates in the ground local system
  43368. var subdivisionsX = this._subdivisionsX;
  43369. var subdivisionsY = this._subdivisionsY;
  43370. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  43371. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  43372. var quad = this._heightQuads[row * this._subdivisionsX + col];
  43373. var facet;
  43374. if (z < quad.slope.x * x + quad.slope.y) {
  43375. facet = quad.facet1;
  43376. }
  43377. else {
  43378. facet = quad.facet2;
  43379. }
  43380. return facet;
  43381. };
  43382. // Creates and populates the heightMap array with "facet" elements :
  43383. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  43384. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43385. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43386. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43387. // Returns the GroundMesh.
  43388. GroundMesh.prototype._initHeightQuads = function () {
  43389. var subdivisionsX = this._subdivisionsX;
  43390. var subdivisionsY = this._subdivisionsY;
  43391. this._heightQuads = new Array();
  43392. for (var row = 0; row < subdivisionsY; row++) {
  43393. for (var col = 0; col < subdivisionsX; col++) {
  43394. 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) };
  43395. this._heightQuads[row * subdivisionsX + col] = quad;
  43396. }
  43397. }
  43398. return this;
  43399. };
  43400. // Compute each quad element values and update the the heightMap array :
  43401. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43402. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43403. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43404. // Returns the GroundMesh.
  43405. GroundMesh.prototype._computeHeightQuads = function () {
  43406. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43407. var v1 = BABYLON.Tmp.Vector3[3];
  43408. var v2 = BABYLON.Tmp.Vector3[2];
  43409. var v3 = BABYLON.Tmp.Vector3[1];
  43410. var v4 = BABYLON.Tmp.Vector3[0];
  43411. var v1v2 = BABYLON.Tmp.Vector3[4];
  43412. var v1v3 = BABYLON.Tmp.Vector3[5];
  43413. var v1v4 = BABYLON.Tmp.Vector3[6];
  43414. var norm1 = BABYLON.Tmp.Vector3[7];
  43415. var norm2 = BABYLON.Tmp.Vector3[8];
  43416. var i = 0;
  43417. var j = 0;
  43418. var k = 0;
  43419. var cd = 0; // 2D slope coefficient : z = cd * x + h
  43420. var h = 0;
  43421. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  43422. var d2 = 0;
  43423. var subdivisionsX = this._subdivisionsX;
  43424. var subdivisionsY = this._subdivisionsY;
  43425. for (var row = 0; row < subdivisionsY; row++) {
  43426. for (var col = 0; col < subdivisionsX; col++) {
  43427. i = col * 3;
  43428. j = row * (subdivisionsX + 1) * 3;
  43429. k = (row + 1) * (subdivisionsX + 1) * 3;
  43430. v1.x = positions[j + i];
  43431. v1.y = positions[j + i + 1];
  43432. v1.z = positions[j + i + 2];
  43433. v2.x = positions[j + i + 3];
  43434. v2.y = positions[j + i + 4];
  43435. v2.z = positions[j + i + 5];
  43436. v3.x = positions[k + i];
  43437. v3.y = positions[k + i + 1];
  43438. v3.z = positions[k + i + 2];
  43439. v4.x = positions[k + i + 3];
  43440. v4.y = positions[k + i + 4];
  43441. v4.z = positions[k + i + 5];
  43442. // 2D slope V1V4
  43443. cd = (v4.z - v1.z) / (v4.x - v1.x);
  43444. h = v1.z - cd * v1.x; // v1 belongs to the slope
  43445. // facet equations :
  43446. // we compute each facet normal vector
  43447. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  43448. // we compute the value d by applying the equation to v1 which belongs to the plane
  43449. // then we store the facet equation in a Vector4
  43450. v2.subtractToRef(v1, v1v2);
  43451. v3.subtractToRef(v1, v1v3);
  43452. v4.subtractToRef(v1, v1v4);
  43453. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  43454. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  43455. norm1.normalize();
  43456. norm2.normalize();
  43457. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  43458. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  43459. var quad = this._heightQuads[row * subdivisionsX + col];
  43460. quad.slope.copyFromFloats(cd, h);
  43461. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  43462. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  43463. }
  43464. }
  43465. return this;
  43466. };
  43467. GroundMesh.prototype.serialize = function (serializationObject) {
  43468. _super.prototype.serialize.call(this, serializationObject);
  43469. serializationObject.subdivisionsX = this._subdivisionsX;
  43470. serializationObject.subdivisionsY = this._subdivisionsY;
  43471. serializationObject.minX = this._minX;
  43472. serializationObject.maxX = this._maxX;
  43473. serializationObject.minZ = this._minZ;
  43474. serializationObject.maxZ = this._maxZ;
  43475. serializationObject.width = this._width;
  43476. serializationObject.height = this._height;
  43477. };
  43478. GroundMesh.Parse = function (parsedMesh, scene) {
  43479. var result = new GroundMesh(parsedMesh.name, scene);
  43480. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  43481. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  43482. result._minX = parsedMesh.minX;
  43483. result._maxX = parsedMesh.maxX;
  43484. result._minZ = parsedMesh.minZ;
  43485. result._maxZ = parsedMesh.maxZ;
  43486. result._width = parsedMesh.width;
  43487. result._height = parsedMesh.height;
  43488. return result;
  43489. };
  43490. return GroundMesh;
  43491. }(BABYLON.Mesh));
  43492. BABYLON.GroundMesh = GroundMesh;
  43493. })(BABYLON || (BABYLON = {}));
  43494. //# sourceMappingURL=babylon.groundMesh.js.map
  43495. var BABYLON;
  43496. (function (BABYLON) {
  43497. /**
  43498. * Creates an instance based on a source mesh.
  43499. */
  43500. var InstancedMesh = (function (_super) {
  43501. __extends(InstancedMesh, _super);
  43502. function InstancedMesh(name, source) {
  43503. var _this = _super.call(this, name, source.getScene()) || this;
  43504. source.instances.push(_this);
  43505. _this._sourceMesh = source;
  43506. _this.position.copyFrom(source.position);
  43507. _this.rotation.copyFrom(source.rotation);
  43508. _this.scaling.copyFrom(source.scaling);
  43509. if (source.rotationQuaternion) {
  43510. _this.rotationQuaternion = source.rotationQuaternion.clone();
  43511. }
  43512. _this.infiniteDistance = source.infiniteDistance;
  43513. _this.setPivotMatrix(source.getPivotMatrix());
  43514. _this.refreshBoundingInfo();
  43515. _this._syncSubMeshes();
  43516. return _this;
  43517. }
  43518. /**
  43519. * Returns the string "InstancedMesh".
  43520. */
  43521. InstancedMesh.prototype.getClassName = function () {
  43522. return "InstancedMesh";
  43523. };
  43524. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  43525. // Methods
  43526. get: function () {
  43527. return this._sourceMesh.receiveShadows;
  43528. },
  43529. enumerable: true,
  43530. configurable: true
  43531. });
  43532. Object.defineProperty(InstancedMesh.prototype, "material", {
  43533. get: function () {
  43534. return this._sourceMesh.material;
  43535. },
  43536. enumerable: true,
  43537. configurable: true
  43538. });
  43539. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  43540. get: function () {
  43541. return this._sourceMesh.visibility;
  43542. },
  43543. enumerable: true,
  43544. configurable: true
  43545. });
  43546. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  43547. get: function () {
  43548. return this._sourceMesh.skeleton;
  43549. },
  43550. enumerable: true,
  43551. configurable: true
  43552. });
  43553. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  43554. get: function () {
  43555. return this._sourceMesh.renderingGroupId;
  43556. },
  43557. enumerable: true,
  43558. configurable: true
  43559. });
  43560. /**
  43561. * Returns the total number of vertices (integer).
  43562. */
  43563. InstancedMesh.prototype.getTotalVertices = function () {
  43564. return this._sourceMesh.getTotalVertices();
  43565. };
  43566. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  43567. get: function () {
  43568. return this._sourceMesh;
  43569. },
  43570. enumerable: true,
  43571. configurable: true
  43572. });
  43573. /**
  43574. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  43575. */
  43576. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  43577. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  43578. };
  43579. /**
  43580. * Sets the vertex data of the mesh geometry for the requested `kind`.
  43581. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  43582. * The `data` are either a numeric array either a Float32Array.
  43583. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  43584. * 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).
  43585. * Note that a new underlying VertexBuffer object is created each call.
  43586. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  43587. *
  43588. * Possible `kind` values :
  43589. * - BABYLON.VertexBuffer.PositionKind
  43590. * - BABYLON.VertexBuffer.UVKind
  43591. * - BABYLON.VertexBuffer.UV2Kind
  43592. * - BABYLON.VertexBuffer.UV3Kind
  43593. * - BABYLON.VertexBuffer.UV4Kind
  43594. * - BABYLON.VertexBuffer.UV5Kind
  43595. * - BABYLON.VertexBuffer.UV6Kind
  43596. * - BABYLON.VertexBuffer.ColorKind
  43597. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43598. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43599. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43600. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43601. *
  43602. * Returns the Mesh.
  43603. */
  43604. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  43605. if (this.sourceMesh) {
  43606. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  43607. }
  43608. return this.sourceMesh;
  43609. };
  43610. /**
  43611. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  43612. * If the mesh has no geometry, it is simply returned as it is.
  43613. * The `data` are either a numeric array either a Float32Array.
  43614. * No new underlying VertexBuffer object is created.
  43615. * 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.
  43616. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  43617. *
  43618. * Possible `kind` values :
  43619. * - BABYLON.VertexBuffer.PositionKind
  43620. * - BABYLON.VertexBuffer.UVKind
  43621. * - BABYLON.VertexBuffer.UV2Kind
  43622. * - BABYLON.VertexBuffer.UV3Kind
  43623. * - BABYLON.VertexBuffer.UV4Kind
  43624. * - BABYLON.VertexBuffer.UV5Kind
  43625. * - BABYLON.VertexBuffer.UV6Kind
  43626. * - BABYLON.VertexBuffer.ColorKind
  43627. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43628. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43629. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43630. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43631. *
  43632. * Returns the Mesh.
  43633. */
  43634. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  43635. if (this.sourceMesh) {
  43636. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  43637. }
  43638. return this.sourceMesh;
  43639. };
  43640. /**
  43641. * Sets the mesh indices.
  43642. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  43643. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  43644. * This method creates a new index buffer each call.
  43645. * Returns the Mesh.
  43646. */
  43647. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  43648. if (this.sourceMesh) {
  43649. this.sourceMesh.setIndices(indices, totalVertices);
  43650. }
  43651. return this.sourceMesh;
  43652. };
  43653. /**
  43654. * Boolean : True if the mesh owns the requested kind of data.
  43655. */
  43656. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  43657. return this._sourceMesh.isVerticesDataPresent(kind);
  43658. };
  43659. /**
  43660. * Returns an array of indices (IndicesArray).
  43661. */
  43662. InstancedMesh.prototype.getIndices = function () {
  43663. return this._sourceMesh.getIndices();
  43664. };
  43665. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  43666. get: function () {
  43667. return this._sourceMesh._positions;
  43668. },
  43669. enumerable: true,
  43670. configurable: true
  43671. });
  43672. /**
  43673. * Sets a new updated BoundingInfo to the mesh.
  43674. * Returns the mesh.
  43675. */
  43676. InstancedMesh.prototype.refreshBoundingInfo = function () {
  43677. var meshBB = this._sourceMesh.getBoundingInfo();
  43678. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  43679. this._updateBoundingInfo();
  43680. return this;
  43681. };
  43682. InstancedMesh.prototype._preActivate = function () {
  43683. if (this._currentLOD) {
  43684. this._currentLOD._preActivate();
  43685. }
  43686. return this;
  43687. };
  43688. InstancedMesh.prototype._activate = function (renderId) {
  43689. if (this._currentLOD) {
  43690. this._currentLOD._registerInstanceForRenderId(this, renderId);
  43691. }
  43692. return this;
  43693. };
  43694. /**
  43695. * Returns the current associated LOD AbstractMesh.
  43696. */
  43697. InstancedMesh.prototype.getLOD = function (camera) {
  43698. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  43699. if (this._currentLOD === this.sourceMesh) {
  43700. return this;
  43701. }
  43702. return this._currentLOD;
  43703. };
  43704. InstancedMesh.prototype._syncSubMeshes = function () {
  43705. this.releaseSubMeshes();
  43706. if (this._sourceMesh.subMeshes) {
  43707. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  43708. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  43709. }
  43710. }
  43711. return this;
  43712. };
  43713. InstancedMesh.prototype._generatePointsArray = function () {
  43714. return this._sourceMesh._generatePointsArray();
  43715. };
  43716. /**
  43717. * Creates a new InstancedMesh from the current mesh.
  43718. * - name (string) : the cloned mesh name
  43719. * - newParent (optional Node) : the optional Node to parent the clone to.
  43720. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  43721. *
  43722. * Returns the clone.
  43723. */
  43724. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43725. var result = this._sourceMesh.createInstance(name);
  43726. // Deep copy
  43727. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  43728. // Bounding info
  43729. this.refreshBoundingInfo();
  43730. // Parent
  43731. if (newParent) {
  43732. result.parent = newParent;
  43733. }
  43734. if (!doNotCloneChildren) {
  43735. // Children
  43736. for (var index = 0; index < this.getScene().meshes.length; index++) {
  43737. var mesh = this.getScene().meshes[index];
  43738. if (mesh.parent === this) {
  43739. mesh.clone(mesh.name, result);
  43740. }
  43741. }
  43742. }
  43743. result.computeWorldMatrix(true);
  43744. return result;
  43745. };
  43746. /**
  43747. * Disposes the InstancedMesh.
  43748. * Returns nothing.
  43749. */
  43750. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  43751. // Remove from mesh
  43752. var index = this._sourceMesh.instances.indexOf(this);
  43753. this._sourceMesh.instances.splice(index, 1);
  43754. _super.prototype.dispose.call(this, doNotRecurse);
  43755. };
  43756. return InstancedMesh;
  43757. }(BABYLON.AbstractMesh));
  43758. BABYLON.InstancedMesh = InstancedMesh;
  43759. })(BABYLON || (BABYLON = {}));
  43760. //# sourceMappingURL=babylon.instancedMesh.js.map
  43761. /// <reference path="babylon.mesh.ts" />
  43762. var BABYLON;
  43763. (function (BABYLON) {
  43764. var LinesMesh = (function (_super) {
  43765. __extends(LinesMesh, _super);
  43766. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  43767. if (parent === void 0) { parent = null; }
  43768. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  43769. _this.useVertexColor = useVertexColor;
  43770. _this.color = new BABYLON.Color3(1, 1, 1);
  43771. _this.alpha = 1;
  43772. if (source) {
  43773. _this.color = source.color.clone();
  43774. _this.alpha = source.alpha;
  43775. _this.useVertexColor = source.useVertexColor;
  43776. }
  43777. _this._intersectionThreshold = 0.1;
  43778. var options = {
  43779. attributes: [BABYLON.VertexBuffer.PositionKind],
  43780. uniforms: ["world", "viewProjection"],
  43781. needAlphaBlending: false,
  43782. };
  43783. if (!useVertexColor) {
  43784. options.uniforms.push("color");
  43785. options.needAlphaBlending = true;
  43786. }
  43787. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  43788. return _this;
  43789. }
  43790. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  43791. /**
  43792. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43793. * This margin is expressed in world space coordinates, so its value may vary.
  43794. * Default value is 0.1
  43795. * @returns the intersection Threshold value.
  43796. */
  43797. get: function () {
  43798. return this._intersectionThreshold;
  43799. },
  43800. /**
  43801. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43802. * This margin is expressed in world space coordinates, so its value may vary.
  43803. * @param value the new threshold to apply
  43804. */
  43805. set: function (value) {
  43806. if (this._intersectionThreshold === value) {
  43807. return;
  43808. }
  43809. this._intersectionThreshold = value;
  43810. if (this.geometry) {
  43811. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  43812. }
  43813. },
  43814. enumerable: true,
  43815. configurable: true
  43816. });
  43817. /**
  43818. * Returns the string "LineMesh"
  43819. */
  43820. LinesMesh.prototype.getClassName = function () {
  43821. return "LinesMesh";
  43822. };
  43823. Object.defineProperty(LinesMesh.prototype, "material", {
  43824. get: function () {
  43825. return this._colorShader;
  43826. },
  43827. enumerable: true,
  43828. configurable: true
  43829. });
  43830. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  43831. get: function () {
  43832. return false;
  43833. },
  43834. enumerable: true,
  43835. configurable: true
  43836. });
  43837. LinesMesh.prototype.createInstance = function (name) {
  43838. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  43839. return null;
  43840. };
  43841. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  43842. // VBOs
  43843. this._geometry._bind(this._colorShader.getEffect());
  43844. // Color
  43845. if (!this.useVertexColor) {
  43846. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  43847. }
  43848. return this;
  43849. };
  43850. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  43851. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  43852. return this;
  43853. }
  43854. var engine = this.getScene().getEngine();
  43855. // Draw order
  43856. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  43857. return this;
  43858. };
  43859. LinesMesh.prototype.dispose = function (doNotRecurse) {
  43860. this._colorShader.dispose();
  43861. _super.prototype.dispose.call(this, doNotRecurse);
  43862. };
  43863. /**
  43864. * Returns a new LineMesh object cloned from the current one.
  43865. */
  43866. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43867. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  43868. };
  43869. return LinesMesh;
  43870. }(BABYLON.Mesh));
  43871. BABYLON.LinesMesh = LinesMesh;
  43872. })(BABYLON || (BABYLON = {}));
  43873. //# sourceMappingURL=babylon.linesMesh.js.map
  43874. var BABYLON;
  43875. (function (BABYLON) {
  43876. var StandardMaterialDefines = (function (_super) {
  43877. __extends(StandardMaterialDefines, _super);
  43878. function StandardMaterialDefines() {
  43879. var _this = _super.call(this) || this;
  43880. _this.MAINUV1 = false;
  43881. _this.MAINUV2 = false;
  43882. _this.DIFFUSE = false;
  43883. _this.DIFFUSEDIRECTUV = 0;
  43884. _this.AMBIENT = false;
  43885. _this.AMBIENTDIRECTUV = 0;
  43886. _this.OPACITY = false;
  43887. _this.OPACITYDIRECTUV = 0;
  43888. _this.OPACITYRGB = false;
  43889. _this.REFLECTION = false;
  43890. _this.EMISSIVE = false;
  43891. _this.EMISSIVEDIRECTUV = 0;
  43892. _this.SPECULAR = false;
  43893. _this.SPECULARDIRECTUV = 0;
  43894. _this.BUMP = false;
  43895. _this.BUMPDIRECTUV = 0;
  43896. _this.PARALLAX = false;
  43897. _this.PARALLAXOCCLUSION = false;
  43898. _this.SPECULAROVERALPHA = false;
  43899. _this.CLIPPLANE = false;
  43900. _this.ALPHATEST = false;
  43901. _this.ALPHAFROMDIFFUSE = false;
  43902. _this.POINTSIZE = false;
  43903. _this.FOG = false;
  43904. _this.SPECULARTERM = false;
  43905. _this.DIFFUSEFRESNEL = false;
  43906. _this.OPACITYFRESNEL = false;
  43907. _this.REFLECTIONFRESNEL = false;
  43908. _this.REFRACTIONFRESNEL = false;
  43909. _this.EMISSIVEFRESNEL = false;
  43910. _this.FRESNEL = false;
  43911. _this.NORMAL = false;
  43912. _this.UV1 = false;
  43913. _this.UV2 = false;
  43914. _this.VERTEXCOLOR = false;
  43915. _this.VERTEXALPHA = false;
  43916. _this.NUM_BONE_INFLUENCERS = 0;
  43917. _this.BonesPerMesh = 0;
  43918. _this.INSTANCES = false;
  43919. _this.GLOSSINESS = false;
  43920. _this.ROUGHNESS = false;
  43921. _this.EMISSIVEASILLUMINATION = false;
  43922. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43923. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43924. _this.LIGHTMAP = false;
  43925. _this.LIGHTMAPDIRECTUV = 0;
  43926. _this.USELIGHTMAPASSHADOWMAP = false;
  43927. _this.REFLECTIONMAP_3D = false;
  43928. _this.REFLECTIONMAP_SPHERICAL = false;
  43929. _this.REFLECTIONMAP_PLANAR = false;
  43930. _this.REFLECTIONMAP_CUBIC = false;
  43931. _this.REFLECTIONMAP_PROJECTION = false;
  43932. _this.REFLECTIONMAP_SKYBOX = false;
  43933. _this.REFLECTIONMAP_EXPLICIT = false;
  43934. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43935. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43936. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43937. _this.INVERTCUBICMAP = false;
  43938. _this.LOGARITHMICDEPTH = false;
  43939. _this.REFRACTION = false;
  43940. _this.REFRACTIONMAP_3D = false;
  43941. _this.REFLECTIONOVERALPHA = false;
  43942. _this.TWOSIDEDLIGHTING = false;
  43943. _this.SHADOWFLOAT = false;
  43944. _this.MORPHTARGETS = false;
  43945. _this.MORPHTARGETS_NORMAL = false;
  43946. _this.MORPHTARGETS_TANGENT = false;
  43947. _this.NUM_MORPH_INFLUENCERS = 0;
  43948. _this.USERIGHTHANDEDSYSTEM = false;
  43949. _this.IMAGEPROCESSING = false;
  43950. _this.VIGNETTE = false;
  43951. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43952. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43953. _this.TONEMAPPING = false;
  43954. _this.CONTRAST = false;
  43955. _this.COLORCURVES = false;
  43956. _this.COLORGRADING = false;
  43957. _this.SAMPLER3DGREENDEPTH = false;
  43958. _this.SAMPLER3DBGRMAP = false;
  43959. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43960. _this.EXPOSURE = false;
  43961. _this.rebuild();
  43962. return _this;
  43963. }
  43964. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43965. var modes = [
  43966. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43967. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43968. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43969. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43970. ];
  43971. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43972. var mode = modes_1[_i];
  43973. this[mode] = (mode === modeToEnable);
  43974. }
  43975. };
  43976. return StandardMaterialDefines;
  43977. }(BABYLON.MaterialDefines));
  43978. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43979. var StandardMaterial = (function (_super) {
  43980. __extends(StandardMaterial, _super);
  43981. function StandardMaterial(name, scene) {
  43982. var _this = _super.call(this, name, scene) || this;
  43983. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43984. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43985. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43986. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43987. _this.specularPower = 64;
  43988. _this._useAlphaFromDiffuseTexture = false;
  43989. _this._useEmissiveAsIllumination = false;
  43990. _this._linkEmissiveWithDiffuse = false;
  43991. _this._useSpecularOverAlpha = false;
  43992. _this._useReflectionOverAlpha = false;
  43993. _this._disableLighting = false;
  43994. _this._useParallax = false;
  43995. _this._useParallaxOcclusion = false;
  43996. _this.parallaxScaleBias = 0.05;
  43997. _this._roughness = 0;
  43998. _this.indexOfRefraction = 0.98;
  43999. _this.invertRefractionY = true;
  44000. _this._useLightmapAsShadowmap = false;
  44001. _this._useReflectionFresnelFromSpecular = false;
  44002. _this._useGlossinessFromSpecularMapAlpha = false;
  44003. _this._maxSimultaneousLights = 4;
  44004. /**
  44005. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44006. */
  44007. _this._invertNormalMapX = false;
  44008. /**
  44009. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44010. */
  44011. _this._invertNormalMapY = false;
  44012. /**
  44013. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44014. */
  44015. _this._twoSidedLighting = false;
  44016. _this._renderTargets = new BABYLON.SmartArray(16);
  44017. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  44018. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44019. // Setup the default processing configuration to the scene.
  44020. _this._attachImageProcessingConfiguration(null);
  44021. _this.getRenderTargetTextures = function () {
  44022. _this._renderTargets.reset();
  44023. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44024. _this._renderTargets.push(_this._reflectionTexture);
  44025. }
  44026. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44027. _this._renderTargets.push(_this._refractionTexture);
  44028. }
  44029. return _this._renderTargets;
  44030. };
  44031. return _this;
  44032. }
  44033. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  44034. /**
  44035. * Gets the image processing configuration used either in this material.
  44036. */
  44037. get: function () {
  44038. return this._imageProcessingConfiguration;
  44039. },
  44040. /**
  44041. * Sets the Default image processing configuration used either in the this material.
  44042. *
  44043. * If sets to null, the scene one is in use.
  44044. */
  44045. set: function (value) {
  44046. this._attachImageProcessingConfiguration(value);
  44047. // Ensure the effect will be rebuilt.
  44048. this._markAllSubMeshesAsTexturesDirty();
  44049. },
  44050. enumerable: true,
  44051. configurable: true
  44052. });
  44053. /**
  44054. * Attaches a new image processing configuration to the Standard Material.
  44055. * @param configuration
  44056. */
  44057. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44058. var _this = this;
  44059. if (configuration === this._imageProcessingConfiguration) {
  44060. return;
  44061. }
  44062. // Detaches observer.
  44063. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44064. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44065. }
  44066. // Pick the scene configuration if needed.
  44067. if (!configuration) {
  44068. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44069. }
  44070. else {
  44071. this._imageProcessingConfiguration = configuration;
  44072. }
  44073. // Attaches observer.
  44074. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44075. _this._markAllSubMeshesAsImageProcessingDirty();
  44076. });
  44077. };
  44078. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  44079. /**
  44080. * Gets wether the color curves effect is enabled.
  44081. */
  44082. get: function () {
  44083. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44084. },
  44085. /**
  44086. * Sets wether the color curves effect is enabled.
  44087. */
  44088. set: function (value) {
  44089. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44090. },
  44091. enumerable: true,
  44092. configurable: true
  44093. });
  44094. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  44095. /**
  44096. * Gets wether the color grading effect is enabled.
  44097. */
  44098. get: function () {
  44099. return this.imageProcessingConfiguration.colorGradingEnabled;
  44100. },
  44101. /**
  44102. * Gets wether the color grading effect is enabled.
  44103. */
  44104. set: function (value) {
  44105. this.imageProcessingConfiguration.colorGradingEnabled = value;
  44106. },
  44107. enumerable: true,
  44108. configurable: true
  44109. });
  44110. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  44111. /**
  44112. * Gets wether tonemapping is enabled or not.
  44113. */
  44114. get: function () {
  44115. return this._imageProcessingConfiguration.toneMappingEnabled;
  44116. },
  44117. /**
  44118. * Sets wether tonemapping is enabled or not
  44119. */
  44120. set: function (value) {
  44121. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44122. },
  44123. enumerable: true,
  44124. configurable: true
  44125. });
  44126. ;
  44127. ;
  44128. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  44129. /**
  44130. * The camera exposure used on this material.
  44131. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44132. * This corresponds to a photographic exposure.
  44133. */
  44134. get: function () {
  44135. return this._imageProcessingConfiguration.exposure;
  44136. },
  44137. /**
  44138. * The camera exposure used on this material.
  44139. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44140. * This corresponds to a photographic exposure.
  44141. */
  44142. set: function (value) {
  44143. this._imageProcessingConfiguration.exposure = value;
  44144. },
  44145. enumerable: true,
  44146. configurable: true
  44147. });
  44148. ;
  44149. ;
  44150. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  44151. /**
  44152. * Gets The camera contrast used on this material.
  44153. */
  44154. get: function () {
  44155. return this._imageProcessingConfiguration.contrast;
  44156. },
  44157. /**
  44158. * Sets The camera contrast used on this material.
  44159. */
  44160. set: function (value) {
  44161. this._imageProcessingConfiguration.contrast = value;
  44162. },
  44163. enumerable: true,
  44164. configurable: true
  44165. });
  44166. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  44167. /**
  44168. * Gets the Color Grading 2D Lookup Texture.
  44169. */
  44170. get: function () {
  44171. return this._imageProcessingConfiguration.colorGradingTexture;
  44172. },
  44173. /**
  44174. * Sets the Color Grading 2D Lookup Texture.
  44175. */
  44176. set: function (value) {
  44177. this._imageProcessingConfiguration.colorGradingTexture = value;
  44178. },
  44179. enumerable: true,
  44180. configurable: true
  44181. });
  44182. StandardMaterial.prototype.getClassName = function () {
  44183. return "StandardMaterial";
  44184. };
  44185. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  44186. get: function () {
  44187. return this._useLogarithmicDepth;
  44188. },
  44189. set: function (value) {
  44190. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44191. this._markAllSubMeshesAsMiscDirty();
  44192. },
  44193. enumerable: true,
  44194. configurable: true
  44195. });
  44196. StandardMaterial.prototype.needAlphaBlending = function () {
  44197. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  44198. };
  44199. StandardMaterial.prototype.needAlphaTesting = function () {
  44200. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  44201. };
  44202. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  44203. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  44204. };
  44205. StandardMaterial.prototype.getAlphaTestTexture = function () {
  44206. return this._diffuseTexture;
  44207. };
  44208. /**
  44209. * Child classes can use it to update shaders
  44210. */
  44211. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44212. if (this.isFrozen) {
  44213. if (this._wasPreviouslyReady && subMesh.effect) {
  44214. return true;
  44215. }
  44216. }
  44217. if (!subMesh._materialDefines) {
  44218. subMesh._materialDefines = new StandardMaterialDefines();
  44219. }
  44220. var scene = this.getScene();
  44221. var defines = subMesh._materialDefines;
  44222. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44223. if (defines._renderId === scene.getRenderId()) {
  44224. return true;
  44225. }
  44226. }
  44227. var engine = scene.getEngine();
  44228. // Lights
  44229. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44230. // Textures
  44231. if (defines._areTexturesDirty) {
  44232. defines._needUVs = false;
  44233. defines.MAINUV1 = false;
  44234. defines.MAINUV2 = false;
  44235. if (scene.texturesEnabled) {
  44236. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44237. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  44238. return false;
  44239. }
  44240. else {
  44241. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  44242. }
  44243. }
  44244. else {
  44245. defines.DIFFUSE = false;
  44246. }
  44247. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44248. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44249. return false;
  44250. }
  44251. else {
  44252. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44253. }
  44254. }
  44255. else {
  44256. defines.AMBIENT = false;
  44257. }
  44258. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44259. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44260. return false;
  44261. }
  44262. else {
  44263. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44264. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44265. }
  44266. }
  44267. else {
  44268. defines.OPACITY = false;
  44269. }
  44270. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44271. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  44272. return false;
  44273. }
  44274. else {
  44275. defines._needNormals = true;
  44276. defines.REFLECTION = true;
  44277. defines.ROUGHNESS = (this._roughness > 0);
  44278. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  44279. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  44280. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  44281. switch (this._reflectionTexture.coordinatesMode) {
  44282. case BABYLON.Texture.CUBIC_MODE:
  44283. case BABYLON.Texture.INVCUBIC_MODE:
  44284. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  44285. break;
  44286. case BABYLON.Texture.EXPLICIT_MODE:
  44287. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  44288. break;
  44289. case BABYLON.Texture.PLANAR_MODE:
  44290. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  44291. break;
  44292. case BABYLON.Texture.PROJECTION_MODE:
  44293. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  44294. break;
  44295. case BABYLON.Texture.SKYBOX_MODE:
  44296. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  44297. break;
  44298. case BABYLON.Texture.SPHERICAL_MODE:
  44299. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  44300. break;
  44301. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44302. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  44303. break;
  44304. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44305. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  44306. break;
  44307. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44308. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  44309. break;
  44310. }
  44311. }
  44312. }
  44313. else {
  44314. defines.REFLECTION = false;
  44315. }
  44316. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44317. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44318. return false;
  44319. }
  44320. else {
  44321. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44322. }
  44323. }
  44324. else {
  44325. defines.EMISSIVE = false;
  44326. }
  44327. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44328. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44329. return false;
  44330. }
  44331. else {
  44332. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44333. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44334. }
  44335. }
  44336. else {
  44337. defines.LIGHTMAP = false;
  44338. }
  44339. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44340. if (!this._specularTexture.isReadyOrNotBlocking()) {
  44341. return false;
  44342. }
  44343. else {
  44344. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  44345. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  44346. }
  44347. }
  44348. else {
  44349. defines.SPECULAR = false;
  44350. }
  44351. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  44352. // Bump texure can not be not blocking.
  44353. if (!this._bumpTexture.isReady()) {
  44354. return false;
  44355. }
  44356. else {
  44357. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44358. defines.PARALLAX = this._useParallax;
  44359. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  44360. }
  44361. }
  44362. else {
  44363. defines.BUMP = false;
  44364. }
  44365. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44366. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  44367. return false;
  44368. }
  44369. else {
  44370. defines._needUVs = true;
  44371. defines.REFRACTION = true;
  44372. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  44373. }
  44374. }
  44375. else {
  44376. defines.REFRACTION = false;
  44377. }
  44378. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  44379. }
  44380. else {
  44381. defines.DIFFUSE = false;
  44382. defines.AMBIENT = false;
  44383. defines.OPACITY = false;
  44384. defines.REFLECTION = false;
  44385. defines.EMISSIVE = false;
  44386. defines.LIGHTMAP = false;
  44387. defines.BUMP = false;
  44388. defines.REFRACTION = false;
  44389. }
  44390. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  44391. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  44392. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  44393. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44394. }
  44395. if (defines._areImageProcessingDirty) {
  44396. if (!this._imageProcessingConfiguration.isReady()) {
  44397. return false;
  44398. }
  44399. this._imageProcessingConfiguration.prepareDefines(defines);
  44400. }
  44401. if (defines._areFresnelDirty) {
  44402. if (StandardMaterial.FresnelEnabled) {
  44403. // Fresnel
  44404. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  44405. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  44406. this._reflectionFresnelParameters) {
  44407. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  44408. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  44409. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  44410. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  44411. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  44412. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  44413. defines._needNormals = true;
  44414. defines.FRESNEL = true;
  44415. }
  44416. }
  44417. else {
  44418. defines.FRESNEL = false;
  44419. }
  44420. }
  44421. // Misc.
  44422. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  44423. // Attribs
  44424. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  44425. // Values that need to be evaluated on every frame
  44426. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  44427. // Get correct effect
  44428. if (defines.isDirty) {
  44429. defines.markAsProcessed();
  44430. scene.resetCachedMaterial();
  44431. // Fallbacks
  44432. var fallbacks = new BABYLON.EffectFallbacks();
  44433. if (defines.REFLECTION) {
  44434. fallbacks.addFallback(0, "REFLECTION");
  44435. }
  44436. if (defines.SPECULAR) {
  44437. fallbacks.addFallback(0, "SPECULAR");
  44438. }
  44439. if (defines.BUMP) {
  44440. fallbacks.addFallback(0, "BUMP");
  44441. }
  44442. if (defines.PARALLAX) {
  44443. fallbacks.addFallback(1, "PARALLAX");
  44444. }
  44445. if (defines.PARALLAXOCCLUSION) {
  44446. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44447. }
  44448. if (defines.SPECULAROVERALPHA) {
  44449. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44450. }
  44451. if (defines.FOG) {
  44452. fallbacks.addFallback(1, "FOG");
  44453. }
  44454. if (defines.POINTSIZE) {
  44455. fallbacks.addFallback(0, "POINTSIZE");
  44456. }
  44457. if (defines.LOGARITHMICDEPTH) {
  44458. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44459. }
  44460. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  44461. if (defines.SPECULARTERM) {
  44462. fallbacks.addFallback(0, "SPECULARTERM");
  44463. }
  44464. if (defines.DIFFUSEFRESNEL) {
  44465. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  44466. }
  44467. if (defines.OPACITYFRESNEL) {
  44468. fallbacks.addFallback(2, "OPACITYFRESNEL");
  44469. }
  44470. if (defines.REFLECTIONFRESNEL) {
  44471. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  44472. }
  44473. if (defines.EMISSIVEFRESNEL) {
  44474. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  44475. }
  44476. if (defines.FRESNEL) {
  44477. fallbacks.addFallback(4, "FRESNEL");
  44478. }
  44479. //Attributes
  44480. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44481. if (defines.NORMAL) {
  44482. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44483. }
  44484. if (defines.UV1) {
  44485. attribs.push(BABYLON.VertexBuffer.UVKind);
  44486. }
  44487. if (defines.UV2) {
  44488. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44489. }
  44490. if (defines.VERTEXCOLOR) {
  44491. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44492. }
  44493. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44494. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44495. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44496. var shaderName = "default";
  44497. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  44498. "vFogInfos", "vFogColor", "pointSize",
  44499. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44500. "mBones",
  44501. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44502. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  44503. "logarithmicDepthConstant", "vNormalReoderParams"
  44504. ];
  44505. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  44506. var uniformBuffers = ["Material", "Scene"];
  44507. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44508. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44509. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44510. uniformsNames: uniforms,
  44511. uniformBuffersNames: uniformBuffers,
  44512. samplers: samplers,
  44513. defines: defines,
  44514. maxSimultaneousLights: this._maxSimultaneousLights
  44515. });
  44516. if (this.customShaderNameResolve) {
  44517. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  44518. }
  44519. var join = defines.toString();
  44520. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  44521. attributes: attribs,
  44522. uniformsNames: uniforms,
  44523. uniformBuffersNames: uniformBuffers,
  44524. samplers: samplers,
  44525. defines: join,
  44526. fallbacks: fallbacks,
  44527. onCompiled: this.onCompiled,
  44528. onError: this.onError,
  44529. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44530. }, engine), defines);
  44531. this.buildUniformLayout();
  44532. }
  44533. if (!subMesh.effect.isReady()) {
  44534. return false;
  44535. }
  44536. defines._renderId = scene.getRenderId();
  44537. this._wasPreviouslyReady = true;
  44538. return true;
  44539. };
  44540. StandardMaterial.prototype.buildUniformLayout = function () {
  44541. // Order is important !
  44542. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  44543. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  44544. this._uniformBuffer.addUniform("opacityParts", 4);
  44545. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  44546. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  44547. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  44548. this._uniformBuffer.addUniform("refractionRightColor", 4);
  44549. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  44550. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  44551. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  44552. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  44553. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44554. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44555. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44556. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44557. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  44558. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44559. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  44560. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44561. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44562. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44563. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44564. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44565. this._uniformBuffer.addUniform("specularMatrix", 16);
  44566. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44567. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  44568. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44569. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44570. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44571. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44572. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44573. this._uniformBuffer.addUniform("pointSize", 1);
  44574. this._uniformBuffer.create();
  44575. };
  44576. StandardMaterial.prototype.unbind = function () {
  44577. if (this._activeEffect) {
  44578. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44579. this._activeEffect.setTexture("reflection2DSampler", null);
  44580. }
  44581. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44582. this._activeEffect.setTexture("refraction2DSampler", null);
  44583. }
  44584. }
  44585. _super.prototype.unbind.call(this);
  44586. };
  44587. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44588. var scene = this.getScene();
  44589. var defines = subMesh._materialDefines;
  44590. if (!defines) {
  44591. return;
  44592. }
  44593. var effect = subMesh.effect;
  44594. this._activeEffect = effect;
  44595. // Matrices
  44596. this.bindOnlyWorldMatrix(world);
  44597. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44598. // Bones
  44599. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44600. if (mustRebind) {
  44601. this._uniformBuffer.bindToEffect(effect, "Material");
  44602. this.bindViewProjection(effect);
  44603. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44604. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44605. // Fresnel
  44606. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44607. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44608. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44609. }
  44610. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44611. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44612. }
  44613. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44614. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44615. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44616. }
  44617. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44618. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44619. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44620. }
  44621. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44622. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44623. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44624. }
  44625. }
  44626. // Textures
  44627. if (scene.texturesEnabled) {
  44628. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44629. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44630. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44631. }
  44632. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44633. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44634. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44635. }
  44636. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44637. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44638. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44639. }
  44640. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44641. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44642. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44643. }
  44644. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44645. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44646. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44647. }
  44648. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44649. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44650. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44651. }
  44652. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44653. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44654. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44655. }
  44656. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44657. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44658. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44659. if (scene._mirroredCameraPosition) {
  44660. 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);
  44661. }
  44662. else {
  44663. 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);
  44664. }
  44665. }
  44666. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44667. var depth = 1.0;
  44668. if (!this._refractionTexture.isCube) {
  44669. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44670. if (this._refractionTexture.depth) {
  44671. depth = this._refractionTexture.depth;
  44672. }
  44673. }
  44674. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44675. }
  44676. }
  44677. // Point size
  44678. if (this.pointsCloud) {
  44679. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44680. }
  44681. if (defines.SPECULARTERM) {
  44682. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44683. }
  44684. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44685. // Diffuse
  44686. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44687. }
  44688. // Textures
  44689. if (scene.texturesEnabled) {
  44690. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44691. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44692. }
  44693. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44694. effect.setTexture("ambientSampler", this._ambientTexture);
  44695. }
  44696. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44697. effect.setTexture("opacitySampler", this._opacityTexture);
  44698. }
  44699. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44700. if (this._reflectionTexture.isCube) {
  44701. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44702. }
  44703. else {
  44704. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44705. }
  44706. }
  44707. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44708. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44709. }
  44710. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44711. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44712. }
  44713. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44714. effect.setTexture("specularSampler", this._specularTexture);
  44715. }
  44716. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44717. effect.setTexture("bumpSampler", this._bumpTexture);
  44718. }
  44719. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44720. var depth = 1.0;
  44721. if (this._refractionTexture.isCube) {
  44722. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44723. }
  44724. else {
  44725. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44726. }
  44727. }
  44728. }
  44729. // Clip plane
  44730. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44731. // Colors
  44732. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44733. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44734. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44735. }
  44736. if (mustRebind || !this.isFrozen) {
  44737. // Lights
  44738. if (scene.lightsEnabled && !this._disableLighting) {
  44739. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44740. }
  44741. // View
  44742. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44743. this.bindView(effect);
  44744. }
  44745. // Fog
  44746. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44747. // Morph targets
  44748. if (defines.NUM_MORPH_INFLUENCERS) {
  44749. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44750. }
  44751. // Log. depth
  44752. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44753. // image processing
  44754. this._imageProcessingConfiguration.bind(this._activeEffect);
  44755. }
  44756. this._uniformBuffer.update();
  44757. this._afterBind(mesh, this._activeEffect);
  44758. };
  44759. StandardMaterial.prototype.getAnimatables = function () {
  44760. var results = [];
  44761. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44762. results.push(this._diffuseTexture);
  44763. }
  44764. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44765. results.push(this._ambientTexture);
  44766. }
  44767. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44768. results.push(this._opacityTexture);
  44769. }
  44770. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44771. results.push(this._reflectionTexture);
  44772. }
  44773. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44774. results.push(this._emissiveTexture);
  44775. }
  44776. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44777. results.push(this._specularTexture);
  44778. }
  44779. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44780. results.push(this._bumpTexture);
  44781. }
  44782. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44783. results.push(this._lightmapTexture);
  44784. }
  44785. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44786. results.push(this._refractionTexture);
  44787. }
  44788. return results;
  44789. };
  44790. StandardMaterial.prototype.getActiveTextures = function () {
  44791. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44792. if (this._diffuseTexture) {
  44793. activeTextures.push(this._diffuseTexture);
  44794. }
  44795. if (this._ambientTexture) {
  44796. activeTextures.push(this._ambientTexture);
  44797. }
  44798. if (this._opacityTexture) {
  44799. activeTextures.push(this._opacityTexture);
  44800. }
  44801. if (this._reflectionTexture) {
  44802. activeTextures.push(this._reflectionTexture);
  44803. }
  44804. if (this._emissiveTexture) {
  44805. activeTextures.push(this._emissiveTexture);
  44806. }
  44807. if (this._specularTexture) {
  44808. activeTextures.push(this._specularTexture);
  44809. }
  44810. if (this._bumpTexture) {
  44811. activeTextures.push(this._bumpTexture);
  44812. }
  44813. if (this._lightmapTexture) {
  44814. activeTextures.push(this._lightmapTexture);
  44815. }
  44816. if (this._refractionTexture) {
  44817. activeTextures.push(this._refractionTexture);
  44818. }
  44819. return activeTextures;
  44820. };
  44821. StandardMaterial.prototype.hasTexture = function (texture) {
  44822. if (_super.prototype.hasTexture.call(this, texture)) {
  44823. return true;
  44824. }
  44825. if (this._diffuseTexture === texture) {
  44826. return true;
  44827. }
  44828. if (this._ambientTexture === texture) {
  44829. return true;
  44830. }
  44831. if (this._opacityTexture === texture) {
  44832. return true;
  44833. }
  44834. if (this._reflectionTexture === texture) {
  44835. return true;
  44836. }
  44837. if (this._emissiveTexture === texture) {
  44838. return true;
  44839. }
  44840. if (this._specularTexture === texture) {
  44841. return true;
  44842. }
  44843. if (this._bumpTexture === texture) {
  44844. return true;
  44845. }
  44846. if (this._lightmapTexture === texture) {
  44847. return true;
  44848. }
  44849. if (this._refractionTexture === texture) {
  44850. return true;
  44851. }
  44852. return false;
  44853. };
  44854. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44855. if (forceDisposeTextures) {
  44856. if (this._diffuseTexture) {
  44857. this._diffuseTexture.dispose();
  44858. }
  44859. if (this._ambientTexture) {
  44860. this._ambientTexture.dispose();
  44861. }
  44862. if (this._opacityTexture) {
  44863. this._opacityTexture.dispose();
  44864. }
  44865. if (this._reflectionTexture) {
  44866. this._reflectionTexture.dispose();
  44867. }
  44868. if (this._emissiveTexture) {
  44869. this._emissiveTexture.dispose();
  44870. }
  44871. if (this._specularTexture) {
  44872. this._specularTexture.dispose();
  44873. }
  44874. if (this._bumpTexture) {
  44875. this._bumpTexture.dispose();
  44876. }
  44877. if (this._lightmapTexture) {
  44878. this._lightmapTexture.dispose();
  44879. }
  44880. if (this._refractionTexture) {
  44881. this._refractionTexture.dispose();
  44882. }
  44883. }
  44884. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44885. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44886. }
  44887. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44888. };
  44889. StandardMaterial.prototype.clone = function (name) {
  44890. var _this = this;
  44891. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44892. result.name = name;
  44893. result.id = name;
  44894. return result;
  44895. };
  44896. StandardMaterial.prototype.serialize = function () {
  44897. return BABYLON.SerializationHelper.Serialize(this);
  44898. };
  44899. // Statics
  44900. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44901. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44902. };
  44903. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44904. get: function () {
  44905. return StandardMaterial._DiffuseTextureEnabled;
  44906. },
  44907. set: function (value) {
  44908. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44909. return;
  44910. }
  44911. StandardMaterial._DiffuseTextureEnabled = value;
  44912. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44913. },
  44914. enumerable: true,
  44915. configurable: true
  44916. });
  44917. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44918. get: function () {
  44919. return StandardMaterial._AmbientTextureEnabled;
  44920. },
  44921. set: function (value) {
  44922. if (StandardMaterial._AmbientTextureEnabled === value) {
  44923. return;
  44924. }
  44925. StandardMaterial._AmbientTextureEnabled = value;
  44926. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44927. },
  44928. enumerable: true,
  44929. configurable: true
  44930. });
  44931. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44932. get: function () {
  44933. return StandardMaterial._OpacityTextureEnabled;
  44934. },
  44935. set: function (value) {
  44936. if (StandardMaterial._OpacityTextureEnabled === value) {
  44937. return;
  44938. }
  44939. StandardMaterial._OpacityTextureEnabled = value;
  44940. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44941. },
  44942. enumerable: true,
  44943. configurable: true
  44944. });
  44945. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44946. get: function () {
  44947. return StandardMaterial._ReflectionTextureEnabled;
  44948. },
  44949. set: function (value) {
  44950. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44951. return;
  44952. }
  44953. StandardMaterial._ReflectionTextureEnabled = value;
  44954. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44955. },
  44956. enumerable: true,
  44957. configurable: true
  44958. });
  44959. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44960. get: function () {
  44961. return StandardMaterial._EmissiveTextureEnabled;
  44962. },
  44963. set: function (value) {
  44964. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44965. return;
  44966. }
  44967. StandardMaterial._EmissiveTextureEnabled = value;
  44968. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44969. },
  44970. enumerable: true,
  44971. configurable: true
  44972. });
  44973. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44974. get: function () {
  44975. return StandardMaterial._SpecularTextureEnabled;
  44976. },
  44977. set: function (value) {
  44978. if (StandardMaterial._SpecularTextureEnabled === value) {
  44979. return;
  44980. }
  44981. StandardMaterial._SpecularTextureEnabled = value;
  44982. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44983. },
  44984. enumerable: true,
  44985. configurable: true
  44986. });
  44987. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44988. get: function () {
  44989. return StandardMaterial._BumpTextureEnabled;
  44990. },
  44991. set: function (value) {
  44992. if (StandardMaterial._BumpTextureEnabled === value) {
  44993. return;
  44994. }
  44995. StandardMaterial._BumpTextureEnabled = value;
  44996. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44997. },
  44998. enumerable: true,
  44999. configurable: true
  45000. });
  45001. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  45002. get: function () {
  45003. return StandardMaterial._LightmapTextureEnabled;
  45004. },
  45005. set: function (value) {
  45006. if (StandardMaterial._LightmapTextureEnabled === value) {
  45007. return;
  45008. }
  45009. StandardMaterial._LightmapTextureEnabled = value;
  45010. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45011. },
  45012. enumerable: true,
  45013. configurable: true
  45014. });
  45015. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  45016. get: function () {
  45017. return StandardMaterial._RefractionTextureEnabled;
  45018. },
  45019. set: function (value) {
  45020. if (StandardMaterial._RefractionTextureEnabled === value) {
  45021. return;
  45022. }
  45023. StandardMaterial._RefractionTextureEnabled = value;
  45024. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45025. },
  45026. enumerable: true,
  45027. configurable: true
  45028. });
  45029. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  45030. get: function () {
  45031. return StandardMaterial._ColorGradingTextureEnabled;
  45032. },
  45033. set: function (value) {
  45034. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  45035. return;
  45036. }
  45037. StandardMaterial._ColorGradingTextureEnabled = value;
  45038. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45039. },
  45040. enumerable: true,
  45041. configurable: true
  45042. });
  45043. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  45044. get: function () {
  45045. return StandardMaterial._FresnelEnabled;
  45046. },
  45047. set: function (value) {
  45048. if (StandardMaterial._FresnelEnabled === value) {
  45049. return;
  45050. }
  45051. StandardMaterial._FresnelEnabled = value;
  45052. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  45053. },
  45054. enumerable: true,
  45055. configurable: true
  45056. });
  45057. // Flags used to enable or disable a type of texture for all Standard Materials
  45058. StandardMaterial._DiffuseTextureEnabled = true;
  45059. StandardMaterial._AmbientTextureEnabled = true;
  45060. StandardMaterial._OpacityTextureEnabled = true;
  45061. StandardMaterial._ReflectionTextureEnabled = true;
  45062. StandardMaterial._EmissiveTextureEnabled = true;
  45063. StandardMaterial._SpecularTextureEnabled = true;
  45064. StandardMaterial._BumpTextureEnabled = true;
  45065. StandardMaterial._LightmapTextureEnabled = true;
  45066. StandardMaterial._RefractionTextureEnabled = true;
  45067. StandardMaterial._ColorGradingTextureEnabled = true;
  45068. StandardMaterial._FresnelEnabled = true;
  45069. __decorate([
  45070. BABYLON.serializeAsTexture("diffuseTexture")
  45071. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  45072. __decorate([
  45073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45074. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  45075. __decorate([
  45076. BABYLON.serializeAsTexture("ambientTexture")
  45077. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  45078. __decorate([
  45079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45080. ], StandardMaterial.prototype, "ambientTexture", void 0);
  45081. __decorate([
  45082. BABYLON.serializeAsTexture("opacityTexture")
  45083. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  45084. __decorate([
  45085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45086. ], StandardMaterial.prototype, "opacityTexture", void 0);
  45087. __decorate([
  45088. BABYLON.serializeAsTexture("reflectionTexture")
  45089. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  45090. __decorate([
  45091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45092. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  45093. __decorate([
  45094. BABYLON.serializeAsTexture("emissiveTexture")
  45095. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  45096. __decorate([
  45097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45098. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  45099. __decorate([
  45100. BABYLON.serializeAsTexture("specularTexture")
  45101. ], StandardMaterial.prototype, "_specularTexture", void 0);
  45102. __decorate([
  45103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45104. ], StandardMaterial.prototype, "specularTexture", void 0);
  45105. __decorate([
  45106. BABYLON.serializeAsTexture("bumpTexture")
  45107. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  45108. __decorate([
  45109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45110. ], StandardMaterial.prototype, "bumpTexture", void 0);
  45111. __decorate([
  45112. BABYLON.serializeAsTexture("lightmapTexture")
  45113. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  45114. __decorate([
  45115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45116. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  45117. __decorate([
  45118. BABYLON.serializeAsTexture("refractionTexture")
  45119. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  45120. __decorate([
  45121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45122. ], StandardMaterial.prototype, "refractionTexture", void 0);
  45123. __decorate([
  45124. BABYLON.serializeAsColor3("ambient")
  45125. ], StandardMaterial.prototype, "ambientColor", void 0);
  45126. __decorate([
  45127. BABYLON.serializeAsColor3("diffuse")
  45128. ], StandardMaterial.prototype, "diffuseColor", void 0);
  45129. __decorate([
  45130. BABYLON.serializeAsColor3("specular")
  45131. ], StandardMaterial.prototype, "specularColor", void 0);
  45132. __decorate([
  45133. BABYLON.serializeAsColor3("emissive")
  45134. ], StandardMaterial.prototype, "emissiveColor", void 0);
  45135. __decorate([
  45136. BABYLON.serialize()
  45137. ], StandardMaterial.prototype, "specularPower", void 0);
  45138. __decorate([
  45139. BABYLON.serialize("useAlphaFromDiffuseTexture")
  45140. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  45141. __decorate([
  45142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45143. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  45144. __decorate([
  45145. BABYLON.serialize("useEmissiveAsIllumination")
  45146. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  45147. __decorate([
  45148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45149. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  45150. __decorate([
  45151. BABYLON.serialize("linkEmissiveWithDiffuse")
  45152. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  45153. __decorate([
  45154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45155. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  45156. __decorate([
  45157. BABYLON.serialize("useSpecularOverAlpha")
  45158. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  45159. __decorate([
  45160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45161. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  45162. __decorate([
  45163. BABYLON.serialize("useReflectionOverAlpha")
  45164. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  45165. __decorate([
  45166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45167. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  45168. __decorate([
  45169. BABYLON.serialize("disableLighting")
  45170. ], StandardMaterial.prototype, "_disableLighting", void 0);
  45171. __decorate([
  45172. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45173. ], StandardMaterial.prototype, "disableLighting", void 0);
  45174. __decorate([
  45175. BABYLON.serialize("useParallax")
  45176. ], StandardMaterial.prototype, "_useParallax", void 0);
  45177. __decorate([
  45178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45179. ], StandardMaterial.prototype, "useParallax", void 0);
  45180. __decorate([
  45181. BABYLON.serialize("useParallaxOcclusion")
  45182. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  45183. __decorate([
  45184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45185. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  45186. __decorate([
  45187. BABYLON.serialize()
  45188. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  45189. __decorate([
  45190. BABYLON.serialize("roughness")
  45191. ], StandardMaterial.prototype, "_roughness", void 0);
  45192. __decorate([
  45193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45194. ], StandardMaterial.prototype, "roughness", void 0);
  45195. __decorate([
  45196. BABYLON.serialize()
  45197. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  45198. __decorate([
  45199. BABYLON.serialize()
  45200. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  45201. __decorate([
  45202. BABYLON.serialize("useLightmapAsShadowmap")
  45203. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  45204. __decorate([
  45205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45206. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45207. __decorate([
  45208. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  45209. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  45210. __decorate([
  45211. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45212. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  45213. __decorate([
  45214. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  45215. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  45216. __decorate([
  45217. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45218. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  45219. __decorate([
  45220. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  45221. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  45222. __decorate([
  45223. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45224. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  45225. __decorate([
  45226. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  45227. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  45228. __decorate([
  45229. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45230. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  45231. __decorate([
  45232. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  45233. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  45234. __decorate([
  45235. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45236. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  45237. __decorate([
  45238. BABYLON.serialize("useReflectionFresnelFromSpecular")
  45239. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  45240. __decorate([
  45241. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45242. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  45243. __decorate([
  45244. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  45245. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  45246. __decorate([
  45247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45248. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  45249. __decorate([
  45250. BABYLON.serialize("maxSimultaneousLights")
  45251. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  45252. __decorate([
  45253. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45254. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  45255. __decorate([
  45256. BABYLON.serialize("invertNormalMapX")
  45257. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  45258. __decorate([
  45259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45260. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  45261. __decorate([
  45262. BABYLON.serialize("invertNormalMapY")
  45263. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  45264. __decorate([
  45265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45266. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  45267. __decorate([
  45268. BABYLON.serialize("twoSidedLighting")
  45269. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  45270. __decorate([
  45271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45272. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  45273. __decorate([
  45274. BABYLON.serialize()
  45275. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  45276. return StandardMaterial;
  45277. }(BABYLON.PushMaterial));
  45278. BABYLON.StandardMaterial = StandardMaterial;
  45279. })(BABYLON || (BABYLON = {}));
  45280. //# sourceMappingURL=babylon.standardMaterial.js.map
  45281. var BABYLON;
  45282. (function (BABYLON) {
  45283. /**
  45284. * This class implement a typical dictionary using a string as key and the generic type T as value.
  45285. * The underlying implementation relies on an associative array to ensure the best performances.
  45286. * The value can be anything including 'null' but except 'undefined'
  45287. */
  45288. var StringDictionary = (function () {
  45289. function StringDictionary() {
  45290. this._count = 0;
  45291. this._data = {};
  45292. }
  45293. /**
  45294. * This will clear this dictionary and copy the content from the 'source' one.
  45295. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  45296. * @param source the dictionary to take the content from and copy to this dictionary
  45297. */
  45298. StringDictionary.prototype.copyFrom = function (source) {
  45299. var _this = this;
  45300. this.clear();
  45301. source.forEach(function (t, v) { return _this.add(t, v); });
  45302. };
  45303. /**
  45304. * Get a value based from its key
  45305. * @param key the given key to get the matching value from
  45306. * @return the value if found, otherwise undefined is returned
  45307. */
  45308. StringDictionary.prototype.get = function (key) {
  45309. var val = this._data[key];
  45310. if (val !== undefined) {
  45311. return val;
  45312. }
  45313. return undefined;
  45314. };
  45315. /**
  45316. * Get a value from its key or add it if it doesn't exist.
  45317. * This method will ensure you that a given key/data will be present in the dictionary.
  45318. * @param key the given key to get the matching value from
  45319. * @param factory the factory that will create the value if the key is not present in the dictionary.
  45320. * The factory will only be invoked if there's no data for the given key.
  45321. * @return the value corresponding to the key.
  45322. */
  45323. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  45324. var val = this.get(key);
  45325. if (val !== undefined) {
  45326. return val;
  45327. }
  45328. val = factory(key);
  45329. if (val) {
  45330. this.add(key, val);
  45331. }
  45332. return val;
  45333. };
  45334. /**
  45335. * Get a value from its key if present in the dictionary otherwise add it
  45336. * @param key the key to get the value from
  45337. * @param val if there's no such key/value pair in the dictionary add it with this value
  45338. * @return the value corresponding to the key
  45339. */
  45340. StringDictionary.prototype.getOrAdd = function (key, val) {
  45341. var curVal = this.get(key);
  45342. if (curVal !== undefined) {
  45343. return curVal;
  45344. }
  45345. this.add(key, val);
  45346. return val;
  45347. };
  45348. /**
  45349. * Check if there's a given key in the dictionary
  45350. * @param key the key to check for
  45351. * @return true if the key is present, false otherwise
  45352. */
  45353. StringDictionary.prototype.contains = function (key) {
  45354. return this._data[key] !== undefined;
  45355. };
  45356. /**
  45357. * Add a new key and its corresponding value
  45358. * @param key the key to add
  45359. * @param value the value corresponding to the key
  45360. * @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
  45361. */
  45362. StringDictionary.prototype.add = function (key, value) {
  45363. if (this._data[key] !== undefined) {
  45364. return false;
  45365. }
  45366. this._data[key] = value;
  45367. ++this._count;
  45368. return true;
  45369. };
  45370. StringDictionary.prototype.set = function (key, value) {
  45371. if (this._data[key] === undefined) {
  45372. return false;
  45373. }
  45374. this._data[key] = value;
  45375. return true;
  45376. };
  45377. /**
  45378. * Get the element of the given key and remove it from the dictionary
  45379. * @param key
  45380. */
  45381. StringDictionary.prototype.getAndRemove = function (key) {
  45382. var val = this.get(key);
  45383. if (val !== undefined) {
  45384. delete this._data[key];
  45385. --this._count;
  45386. return val;
  45387. }
  45388. return null;
  45389. };
  45390. /**
  45391. * Remove a key/value from the dictionary.
  45392. * @param key the key to remove
  45393. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  45394. */
  45395. StringDictionary.prototype.remove = function (key) {
  45396. if (this.contains(key)) {
  45397. delete this._data[key];
  45398. --this._count;
  45399. return true;
  45400. }
  45401. return false;
  45402. };
  45403. /**
  45404. * Clear the whole content of the dictionary
  45405. */
  45406. StringDictionary.prototype.clear = function () {
  45407. this._data = {};
  45408. this._count = 0;
  45409. };
  45410. Object.defineProperty(StringDictionary.prototype, "count", {
  45411. get: function () {
  45412. return this._count;
  45413. },
  45414. enumerable: true,
  45415. configurable: true
  45416. });
  45417. /**
  45418. * Execute a callback on each key/val of the dictionary.
  45419. * Note that you can remove any element in this dictionary in the callback implementation
  45420. * @param callback the callback to execute on a given key/value pair
  45421. */
  45422. StringDictionary.prototype.forEach = function (callback) {
  45423. for (var cur in this._data) {
  45424. var val = this._data[cur];
  45425. callback(cur, val);
  45426. }
  45427. };
  45428. /**
  45429. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  45430. * If the callback returns null or undefined the method will iterate to the next key/value pair
  45431. * Note that you can remove any element in this dictionary in the callback implementation
  45432. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  45433. */
  45434. StringDictionary.prototype.first = function (callback) {
  45435. for (var cur in this._data) {
  45436. var val = this._data[cur];
  45437. var res = callback(cur, val);
  45438. if (res) {
  45439. return res;
  45440. }
  45441. }
  45442. return null;
  45443. };
  45444. return StringDictionary;
  45445. }());
  45446. BABYLON.StringDictionary = StringDictionary;
  45447. })(BABYLON || (BABYLON = {}));
  45448. //# sourceMappingURL=babylon.stringDictionary.js.map
  45449. var BABYLON;
  45450. (function (BABYLON) {
  45451. var DynamicFloatArrayElementInfo = (function () {
  45452. function DynamicFloatArrayElementInfo() {
  45453. }
  45454. return DynamicFloatArrayElementInfo;
  45455. }());
  45456. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  45457. /**
  45458. * 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.
  45459. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  45460. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  45461. * 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.
  45462. * 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.
  45463. * 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".
  45464. */
  45465. var DynamicFloatArray = (function () {
  45466. /**
  45467. * Construct an instance of the dynamic float array
  45468. * @param stride size of one element in float (i.e. not bytes!)
  45469. * @param initialElementCount the number of available entries at construction
  45470. */
  45471. function DynamicFloatArray(stride, initialElementCount) {
  45472. this.compareValueOffset = null;
  45473. this.sortingAscending = true;
  45474. this._stride = stride;
  45475. this.buffer = new Float32Array(stride * initialElementCount);
  45476. this._lastUsed = 0;
  45477. this._firstFree = 0;
  45478. this._allEntries = new Array(initialElementCount);
  45479. this._freeEntries = new Array(initialElementCount);
  45480. for (var i = 0; i < initialElementCount; i++) {
  45481. var element = new DynamicFloatArrayElementInfo();
  45482. element.offset = i * stride;
  45483. this._allEntries[i] = element;
  45484. this._freeEntries[initialElementCount - i - 1] = element;
  45485. }
  45486. }
  45487. /**
  45488. * Allocate an element in the array.
  45489. * @return the element info instance that contains the offset into the main buffer of the element's location.
  45490. * Beware, this offset may change when you call pack()
  45491. */
  45492. DynamicFloatArray.prototype.allocElement = function () {
  45493. if (this._freeEntries.length === 0) {
  45494. this._growBuffer();
  45495. }
  45496. var el = this._freeEntries.pop();
  45497. this._lastUsed = Math.max(el.offset, this._lastUsed);
  45498. if (el.offset === this._firstFree) {
  45499. if (this._freeEntries.length > 0) {
  45500. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  45501. }
  45502. else {
  45503. this._firstFree += this._stride;
  45504. }
  45505. }
  45506. return el;
  45507. };
  45508. /**
  45509. * Free the element corresponding to the given element info
  45510. * @param elInfo the element that describe the allocated element
  45511. */
  45512. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  45513. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  45514. this._freeEntries.push(elInfo);
  45515. };
  45516. /**
  45517. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  45518. * 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().
  45519. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  45520. */
  45521. DynamicFloatArray.prototype.pack = function () {
  45522. // no free slot? no need to pack
  45523. if (this._freeEntries.length === 0) {
  45524. return this.buffer;
  45525. }
  45526. // If the buffer is already packed the last used will always be lower than the first free
  45527. // 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.
  45528. if (this._lastUsed < this._firstFree) {
  45529. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  45530. return elementsBuffer_1;
  45531. }
  45532. var s = this._stride;
  45533. // 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
  45534. var lastFree = new DynamicFloatArrayElementInfo();
  45535. lastFree.offset = this.totalElementCount * s;
  45536. this._freeEntries.push(lastFree);
  45537. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  45538. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45539. var firstFreeSlotOffset = sortedFree[0].offset;
  45540. var freeZoneSize = 1;
  45541. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  45542. var prevOffset = sortedFree[0].offset;
  45543. for (var i = 1; i < sortedFree.length; i++) {
  45544. // 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
  45545. if (firstFreeSlotOffset >= occupiedZoneSize) {
  45546. break;
  45547. }
  45548. var curFree = sortedFree[i];
  45549. var curOffset = curFree.offset;
  45550. // Compute the distance between this offset and the previous
  45551. var distance = curOffset - prevOffset;
  45552. // If the distance is the stride size, they are adjacent, it good, move to the next
  45553. if (distance === s) {
  45554. // Free zone is one element bigger
  45555. ++freeZoneSize;
  45556. // as we're about to iterate to the next, the cur becomes the previous...
  45557. prevOffset = curOffset;
  45558. continue;
  45559. }
  45560. // Distance is bigger, which means there's x element between the previous free and this one
  45561. var usedRange = (distance / s) - 1;
  45562. // Two cases the free zone is smaller than the data to move or bigger
  45563. // Copy what can fit in the free zone
  45564. var curMoveOffset = curOffset - s;
  45565. var copyCount = Math.min(freeZoneSize, usedRange);
  45566. for (var j = 0; j < copyCount; j++) {
  45567. var freeI = firstFreeSlotOffset / s;
  45568. var curI = curMoveOffset / s;
  45569. var moveEl = sortedAll[curI];
  45570. this._moveElement(moveEl, firstFreeSlotOffset);
  45571. var replacedEl = sortedAll[freeI];
  45572. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  45573. replacedEl.offset = curMoveOffset;
  45574. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  45575. sortedAll[freeI] = moveEl;
  45576. sortedAll[curI] = replacedEl;
  45577. curMoveOffset -= s;
  45578. firstFreeSlotOffset += s;
  45579. }
  45580. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  45581. if (freeZoneSize <= usedRange) {
  45582. firstFreeSlotOffset = curMoveOffset + s;
  45583. freeZoneSize = 1 + copyCount;
  45584. }
  45585. else {
  45586. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  45587. }
  45588. // as we're about to iterate to the next, the cur becomes the previous...
  45589. prevOffset = curOffset;
  45590. }
  45591. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  45592. this._lastUsed = firstFreeSlotOffset - s;
  45593. this._firstFree = firstFreeSlotOffset;
  45594. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  45595. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  45596. this._allEntries = sortedAll;
  45597. return elementsBuffer;
  45598. };
  45599. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  45600. for (var i = 0; i < this._stride; i++) {
  45601. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  45602. }
  45603. element.offset = destOffset;
  45604. };
  45605. DynamicFloatArray.prototype._growBuffer = function () {
  45606. // Allocate the new buffer with 50% more entries, copy the content of the current one
  45607. var newElCount = Math.floor(this.totalElementCount * 1.5);
  45608. var newBuffer = new Float32Array(newElCount * this._stride);
  45609. newBuffer.set(this.buffer);
  45610. var curCount = this.totalElementCount;
  45611. var addedCount = newElCount - this.totalElementCount;
  45612. for (var i = 0; i < addedCount; i++) {
  45613. var element = new DynamicFloatArrayElementInfo();
  45614. element.offset = (curCount + i) * this.stride;
  45615. this._allEntries.push(element);
  45616. this._freeEntries[addedCount - i - 1] = element;
  45617. }
  45618. this._firstFree = curCount * this.stride;
  45619. this.buffer = newBuffer;
  45620. };
  45621. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  45622. /**
  45623. * Get the total count of entries that can fit in the current buffer
  45624. * @returns the elements count
  45625. */
  45626. get: function () {
  45627. return this._allEntries.length;
  45628. },
  45629. enumerable: true,
  45630. configurable: true
  45631. });
  45632. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  45633. /**
  45634. * Get the count of free entries that can still be allocated without resizing the buffer
  45635. * @returns the free elements count
  45636. */
  45637. get: function () {
  45638. return this._freeEntries.length;
  45639. },
  45640. enumerable: true,
  45641. configurable: true
  45642. });
  45643. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  45644. /**
  45645. * Get the count of allocated elements
  45646. * @returns the allocated elements count
  45647. */
  45648. get: function () {
  45649. return this._allEntries.length - this._freeEntries.length;
  45650. },
  45651. enumerable: true,
  45652. configurable: true
  45653. });
  45654. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  45655. /**
  45656. * Return the size of one element in float
  45657. * @returns the size in float
  45658. */
  45659. get: function () {
  45660. return this._stride;
  45661. },
  45662. enumerable: true,
  45663. configurable: true
  45664. });
  45665. DynamicFloatArray.prototype.sort = function () {
  45666. var _this = this;
  45667. if (!this.compareValueOffset) {
  45668. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  45669. }
  45670. var count = this.usedElementCount;
  45671. // Do we have to (re)create the sort table?
  45672. if (!this._sortTable || this._sortTable.length < count) {
  45673. // 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...
  45674. var newCount = Math.min(this.totalElementCount, count * 2);
  45675. this._sortTable = new Array(newCount);
  45676. }
  45677. if (!this._sortedTable || this._sortedTable.length !== count) {
  45678. this._sortedTable = new Array(count);
  45679. }
  45680. // Because, you know...
  45681. this.pack();
  45682. //let stride = this.stride;
  45683. //for (let i = 0; i < count; i++) {
  45684. // let si = this._sortTable[i];
  45685. // if (!si) {
  45686. // si = new SortInfo();
  45687. // this._sortTable[i] = si;
  45688. // }
  45689. // si.entry = this._allEntries[i];
  45690. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  45691. // si.swapedOffset = null;
  45692. // this._sortedTable[i] = si;
  45693. //}
  45694. var curOffset = 0;
  45695. var stride = this.stride;
  45696. for (var i = 0; i < count; i++, curOffset += stride) {
  45697. var si = this._sortTable[i];
  45698. if (!si) {
  45699. si = new SortInfo();
  45700. this._sortTable[i] = si;
  45701. }
  45702. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  45703. si.offset = curOffset;
  45704. si.swapedOffset = null;
  45705. this._sortedTable[i] = si;
  45706. }
  45707. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  45708. if (this.sortingAscending) {
  45709. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  45710. }
  45711. else {
  45712. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  45713. }
  45714. var swapElements = function (src, dst) {
  45715. for (var i = 0; i < stride; i++) {
  45716. var tps = _this.buffer[dst + i];
  45717. _this.buffer[dst + i] = _this.buffer[src + i];
  45718. _this.buffer[src + i] = tps;
  45719. }
  45720. };
  45721. // 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:
  45722. // 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),
  45723. // and I still want something with a good algorithm complexity.
  45724. // 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,
  45725. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  45726. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  45727. // 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
  45728. // until we find a SortInfo object without a swapedOffset which means we got the right location
  45729. // 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
  45730. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  45731. for (var i = 0; i < count; i++) {
  45732. // Get the element to move
  45733. var sourceSI = this._sortedTable[i];
  45734. var destSI = this._sortTable[i];
  45735. var sourceOff = sourceSI.offset;
  45736. // If the source changed location, find the new one
  45737. if (sourceSI.swapedOffset) {
  45738. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  45739. var curSI = sourceSI;
  45740. while (curSI.swapedOffset) {
  45741. curSI = this._sortTable[curSI.swapedOffset / stride];
  45742. }
  45743. // Finally get the right location
  45744. sourceOff = curSI.offset;
  45745. }
  45746. // Tag the element being replaced with its new location
  45747. destSI.swapedOffset = sourceOff;
  45748. // Swap elements (only if needed)
  45749. if (sourceOff !== destSI.offset) {
  45750. swapElements(sourceOff, destSI.offset);
  45751. }
  45752. // Update the offset in the corresponding DFAE
  45753. //sourceSI.entry.offset = destSI.entry.offset;
  45754. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  45755. }
  45756. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45757. return true;
  45758. };
  45759. return DynamicFloatArray;
  45760. }());
  45761. BABYLON.DynamicFloatArray = DynamicFloatArray;
  45762. var SortInfo = (function () {
  45763. function SortInfo() {
  45764. this.compareData = this.offset = this.swapedOffset = null;
  45765. }
  45766. return SortInfo;
  45767. }());
  45768. })(BABYLON || (BABYLON = {}));
  45769. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  45770. var BABYLON;
  45771. (function (BABYLON) {
  45772. var Condition = (function () {
  45773. function Condition(actionManager) {
  45774. this._actionManager = actionManager;
  45775. }
  45776. Condition.prototype.isValid = function () {
  45777. return true;
  45778. };
  45779. Condition.prototype._getProperty = function (propertyPath) {
  45780. return this._actionManager._getProperty(propertyPath);
  45781. };
  45782. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  45783. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45784. };
  45785. Condition.prototype.serialize = function () {
  45786. };
  45787. Condition.prototype._serialize = function (serializedCondition) {
  45788. return {
  45789. type: 2,
  45790. children: [],
  45791. name: serializedCondition.name,
  45792. properties: serializedCondition.properties
  45793. };
  45794. };
  45795. return Condition;
  45796. }());
  45797. BABYLON.Condition = Condition;
  45798. var ValueCondition = (function (_super) {
  45799. __extends(ValueCondition, _super);
  45800. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  45801. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  45802. var _this = _super.call(this, actionManager) || this;
  45803. _this.propertyPath = propertyPath;
  45804. _this.value = value;
  45805. _this.operator = operator;
  45806. _this._target = target;
  45807. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  45808. _this._property = _this._getProperty(_this.propertyPath);
  45809. return _this;
  45810. }
  45811. Object.defineProperty(ValueCondition, "IsEqual", {
  45812. get: function () {
  45813. return ValueCondition._IsEqual;
  45814. },
  45815. enumerable: true,
  45816. configurable: true
  45817. });
  45818. Object.defineProperty(ValueCondition, "IsDifferent", {
  45819. get: function () {
  45820. return ValueCondition._IsDifferent;
  45821. },
  45822. enumerable: true,
  45823. configurable: true
  45824. });
  45825. Object.defineProperty(ValueCondition, "IsGreater", {
  45826. get: function () {
  45827. return ValueCondition._IsGreater;
  45828. },
  45829. enumerable: true,
  45830. configurable: true
  45831. });
  45832. Object.defineProperty(ValueCondition, "IsLesser", {
  45833. get: function () {
  45834. return ValueCondition._IsLesser;
  45835. },
  45836. enumerable: true,
  45837. configurable: true
  45838. });
  45839. // Methods
  45840. ValueCondition.prototype.isValid = function () {
  45841. switch (this.operator) {
  45842. case ValueCondition.IsGreater:
  45843. return this._effectiveTarget[this._property] > this.value;
  45844. case ValueCondition.IsLesser:
  45845. return this._effectiveTarget[this._property] < this.value;
  45846. case ValueCondition.IsEqual:
  45847. case ValueCondition.IsDifferent:
  45848. var check;
  45849. if (this.value.equals) {
  45850. check = this.value.equals(this._effectiveTarget[this._property]);
  45851. }
  45852. else {
  45853. check = this.value === this._effectiveTarget[this._property];
  45854. }
  45855. return this.operator === ValueCondition.IsEqual ? check : !check;
  45856. }
  45857. return false;
  45858. };
  45859. ValueCondition.prototype.serialize = function () {
  45860. return this._serialize({
  45861. name: "ValueCondition",
  45862. properties: [
  45863. BABYLON.Action._GetTargetProperty(this._target),
  45864. { name: "propertyPath", value: this.propertyPath },
  45865. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45866. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  45867. ]
  45868. });
  45869. };
  45870. ValueCondition.GetOperatorName = function (operator) {
  45871. switch (operator) {
  45872. case ValueCondition._IsEqual: return "IsEqual";
  45873. case ValueCondition._IsDifferent: return "IsDifferent";
  45874. case ValueCondition._IsGreater: return "IsGreater";
  45875. case ValueCondition._IsLesser: return "IsLesser";
  45876. default: return "";
  45877. }
  45878. };
  45879. // Statics
  45880. ValueCondition._IsEqual = 0;
  45881. ValueCondition._IsDifferent = 1;
  45882. ValueCondition._IsGreater = 2;
  45883. ValueCondition._IsLesser = 3;
  45884. return ValueCondition;
  45885. }(Condition));
  45886. BABYLON.ValueCondition = ValueCondition;
  45887. var PredicateCondition = (function (_super) {
  45888. __extends(PredicateCondition, _super);
  45889. function PredicateCondition(actionManager, predicate) {
  45890. var _this = _super.call(this, actionManager) || this;
  45891. _this.predicate = predicate;
  45892. return _this;
  45893. }
  45894. PredicateCondition.prototype.isValid = function () {
  45895. return this.predicate();
  45896. };
  45897. return PredicateCondition;
  45898. }(Condition));
  45899. BABYLON.PredicateCondition = PredicateCondition;
  45900. var StateCondition = (function (_super) {
  45901. __extends(StateCondition, _super);
  45902. function StateCondition(actionManager, target, value) {
  45903. var _this = _super.call(this, actionManager) || this;
  45904. _this.value = value;
  45905. _this._target = target;
  45906. return _this;
  45907. }
  45908. // Methods
  45909. StateCondition.prototype.isValid = function () {
  45910. return this._target.state === this.value;
  45911. };
  45912. StateCondition.prototype.serialize = function () {
  45913. return this._serialize({
  45914. name: "StateCondition",
  45915. properties: [
  45916. BABYLON.Action._GetTargetProperty(this._target),
  45917. { name: "value", value: this.value }
  45918. ]
  45919. });
  45920. };
  45921. return StateCondition;
  45922. }(Condition));
  45923. BABYLON.StateCondition = StateCondition;
  45924. })(BABYLON || (BABYLON = {}));
  45925. //# sourceMappingURL=babylon.condition.js.map
  45926. var BABYLON;
  45927. (function (BABYLON) {
  45928. var Action = (function () {
  45929. function Action(triggerOptions, condition) {
  45930. this.triggerOptions = triggerOptions;
  45931. if (triggerOptions.parameter) {
  45932. this.trigger = triggerOptions.trigger;
  45933. this._triggerParameter = triggerOptions.parameter;
  45934. }
  45935. else {
  45936. this.trigger = triggerOptions;
  45937. }
  45938. this._nextActiveAction = this;
  45939. this._condition = condition;
  45940. }
  45941. // Methods
  45942. Action.prototype._prepare = function () {
  45943. };
  45944. Action.prototype.getTriggerParameter = function () {
  45945. return this._triggerParameter;
  45946. };
  45947. Action.prototype._executeCurrent = function (evt) {
  45948. if (this._nextActiveAction._condition) {
  45949. var condition = this._nextActiveAction._condition;
  45950. var currentRenderId = this._actionManager.getScene().getRenderId();
  45951. // We cache the current evaluation for the current frame
  45952. if (condition._evaluationId === currentRenderId) {
  45953. if (!condition._currentResult) {
  45954. return;
  45955. }
  45956. }
  45957. else {
  45958. condition._evaluationId = currentRenderId;
  45959. if (!condition.isValid()) {
  45960. condition._currentResult = false;
  45961. return;
  45962. }
  45963. condition._currentResult = true;
  45964. }
  45965. }
  45966. this._nextActiveAction.execute(evt);
  45967. this.skipToNextActiveAction();
  45968. };
  45969. Action.prototype.execute = function (evt) {
  45970. };
  45971. Action.prototype.skipToNextActiveAction = function () {
  45972. if (this._nextActiveAction._child) {
  45973. if (!this._nextActiveAction._child._actionManager) {
  45974. this._nextActiveAction._child._actionManager = this._actionManager;
  45975. }
  45976. this._nextActiveAction = this._nextActiveAction._child;
  45977. }
  45978. else {
  45979. this._nextActiveAction = this;
  45980. }
  45981. };
  45982. Action.prototype.then = function (action) {
  45983. this._child = action;
  45984. action._actionManager = this._actionManager;
  45985. action._prepare();
  45986. return action;
  45987. };
  45988. Action.prototype._getProperty = function (propertyPath) {
  45989. return this._actionManager._getProperty(propertyPath);
  45990. };
  45991. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  45992. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45993. };
  45994. Action.prototype.serialize = function (parent) {
  45995. };
  45996. // Called by BABYLON.Action objects in serialize(...). Internal use
  45997. Action.prototype._serialize = function (serializedAction, parent) {
  45998. var serializationObject = {
  45999. type: 1,
  46000. children: [],
  46001. name: serializedAction.name,
  46002. properties: serializedAction.properties || []
  46003. };
  46004. // Serialize child
  46005. if (this._child) {
  46006. this._child.serialize(serializationObject);
  46007. }
  46008. // Check if "this" has a condition
  46009. if (this._condition) {
  46010. var serializedCondition = this._condition.serialize();
  46011. serializedCondition.children.push(serializationObject);
  46012. if (parent) {
  46013. parent.children.push(serializedCondition);
  46014. }
  46015. return serializedCondition;
  46016. }
  46017. if (parent) {
  46018. parent.children.push(serializationObject);
  46019. }
  46020. return serializationObject;
  46021. };
  46022. Action._SerializeValueAsString = function (value) {
  46023. if (typeof value === "number") {
  46024. return value.toString();
  46025. }
  46026. if (typeof value === "boolean") {
  46027. return value ? "true" : "false";
  46028. }
  46029. if (value instanceof BABYLON.Vector2) {
  46030. return value.x + ", " + value.y;
  46031. }
  46032. if (value instanceof BABYLON.Vector3) {
  46033. return value.x + ", " + value.y + ", " + value.z;
  46034. }
  46035. if (value instanceof BABYLON.Color3) {
  46036. return value.r + ", " + value.g + ", " + value.b;
  46037. }
  46038. if (value instanceof BABYLON.Color4) {
  46039. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  46040. }
  46041. return value; // string
  46042. };
  46043. Action._GetTargetProperty = function (target) {
  46044. return {
  46045. name: "target",
  46046. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  46047. : target instanceof BABYLON.Light ? "LightProperties"
  46048. : target instanceof BABYLON.Camera ? "CameraProperties"
  46049. : "SceneProperties",
  46050. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  46051. };
  46052. };
  46053. return Action;
  46054. }());
  46055. BABYLON.Action = Action;
  46056. })(BABYLON || (BABYLON = {}));
  46057. //# sourceMappingURL=babylon.action.js.map
  46058. var BABYLON;
  46059. (function (BABYLON) {
  46060. /**
  46061. * ActionEvent is the event beint sent when an action is triggered.
  46062. */
  46063. var ActionEvent = (function () {
  46064. /**
  46065. * @param source The mesh or sprite that triggered the action.
  46066. * @param pointerX The X mouse cursor position at the time of the event
  46067. * @param pointerY The Y mouse cursor position at the time of the event
  46068. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  46069. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  46070. */
  46071. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  46072. this.source = source;
  46073. this.pointerX = pointerX;
  46074. this.pointerY = pointerY;
  46075. this.meshUnderPointer = meshUnderPointer;
  46076. this.sourceEvent = sourceEvent;
  46077. this.additionalData = additionalData;
  46078. }
  46079. /**
  46080. * Helper function to auto-create an ActionEvent from a source mesh.
  46081. * @param source The source mesh that triggered the event
  46082. * @param evt {Event} The original (browser) event
  46083. */
  46084. ActionEvent.CreateNew = function (source, evt, additionalData) {
  46085. var scene = source.getScene();
  46086. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  46087. };
  46088. /**
  46089. * Helper function to auto-create an ActionEvent from a source mesh.
  46090. * @param source The source sprite that triggered the event
  46091. * @param scene Scene associated with the sprite
  46092. * @param evt {Event} The original (browser) event
  46093. */
  46094. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  46095. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  46096. };
  46097. /**
  46098. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  46099. * @param scene the scene where the event occurred
  46100. * @param evt {Event} The original (browser) event
  46101. */
  46102. ActionEvent.CreateNewFromScene = function (scene, evt) {
  46103. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  46104. };
  46105. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  46106. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  46107. };
  46108. return ActionEvent;
  46109. }());
  46110. BABYLON.ActionEvent = ActionEvent;
  46111. /**
  46112. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  46113. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  46114. */
  46115. var ActionManager = (function () {
  46116. function ActionManager(scene) {
  46117. // Members
  46118. this.actions = new Array();
  46119. this.hoverCursor = '';
  46120. this._scene = scene;
  46121. scene._actionManagers.push(this);
  46122. }
  46123. Object.defineProperty(ActionManager, "NothingTrigger", {
  46124. get: function () {
  46125. return ActionManager._NothingTrigger;
  46126. },
  46127. enumerable: true,
  46128. configurable: true
  46129. });
  46130. Object.defineProperty(ActionManager, "OnPickTrigger", {
  46131. get: function () {
  46132. return ActionManager._OnPickTrigger;
  46133. },
  46134. enumerable: true,
  46135. configurable: true
  46136. });
  46137. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  46138. get: function () {
  46139. return ActionManager._OnLeftPickTrigger;
  46140. },
  46141. enumerable: true,
  46142. configurable: true
  46143. });
  46144. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  46145. get: function () {
  46146. return ActionManager._OnRightPickTrigger;
  46147. },
  46148. enumerable: true,
  46149. configurable: true
  46150. });
  46151. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  46152. get: function () {
  46153. return ActionManager._OnCenterPickTrigger;
  46154. },
  46155. enumerable: true,
  46156. configurable: true
  46157. });
  46158. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  46159. get: function () {
  46160. return ActionManager._OnPickDownTrigger;
  46161. },
  46162. enumerable: true,
  46163. configurable: true
  46164. });
  46165. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  46166. get: function () {
  46167. return ActionManager._OnDoublePickTrigger;
  46168. },
  46169. enumerable: true,
  46170. configurable: true
  46171. });
  46172. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  46173. get: function () {
  46174. return ActionManager._OnPickUpTrigger;
  46175. },
  46176. enumerable: true,
  46177. configurable: true
  46178. });
  46179. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  46180. /// This trigger will only be raised if you also declared a OnPickDown
  46181. get: function () {
  46182. return ActionManager._OnPickOutTrigger;
  46183. },
  46184. enumerable: true,
  46185. configurable: true
  46186. });
  46187. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  46188. get: function () {
  46189. return ActionManager._OnLongPressTrigger;
  46190. },
  46191. enumerable: true,
  46192. configurable: true
  46193. });
  46194. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  46195. get: function () {
  46196. return ActionManager._OnPointerOverTrigger;
  46197. },
  46198. enumerable: true,
  46199. configurable: true
  46200. });
  46201. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  46202. get: function () {
  46203. return ActionManager._OnPointerOutTrigger;
  46204. },
  46205. enumerable: true,
  46206. configurable: true
  46207. });
  46208. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  46209. get: function () {
  46210. return ActionManager._OnEveryFrameTrigger;
  46211. },
  46212. enumerable: true,
  46213. configurable: true
  46214. });
  46215. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  46216. get: function () {
  46217. return ActionManager._OnIntersectionEnterTrigger;
  46218. },
  46219. enumerable: true,
  46220. configurable: true
  46221. });
  46222. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  46223. get: function () {
  46224. return ActionManager._OnIntersectionExitTrigger;
  46225. },
  46226. enumerable: true,
  46227. configurable: true
  46228. });
  46229. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  46230. get: function () {
  46231. return ActionManager._OnKeyDownTrigger;
  46232. },
  46233. enumerable: true,
  46234. configurable: true
  46235. });
  46236. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  46237. get: function () {
  46238. return ActionManager._OnKeyUpTrigger;
  46239. },
  46240. enumerable: true,
  46241. configurable: true
  46242. });
  46243. // Methods
  46244. ActionManager.prototype.dispose = function () {
  46245. var index = this._scene._actionManagers.indexOf(this);
  46246. for (var i = 0; i < this.actions.length; i++) {
  46247. var action = this.actions[i];
  46248. ActionManager.Triggers[action.trigger]--;
  46249. if (ActionManager.Triggers[action.trigger] === 0) {
  46250. delete ActionManager.Triggers[action.trigger];
  46251. }
  46252. }
  46253. if (index > -1) {
  46254. this._scene._actionManagers.splice(index, 1);
  46255. }
  46256. };
  46257. ActionManager.prototype.getScene = function () {
  46258. return this._scene;
  46259. };
  46260. /**
  46261. * Does this action manager handles actions of any of the given triggers
  46262. * @param {number[]} triggers - the triggers to be tested
  46263. * @return {boolean} whether one (or more) of the triggers is handeled
  46264. */
  46265. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  46266. for (var index = 0; index < this.actions.length; index++) {
  46267. var action = this.actions[index];
  46268. if (triggers.indexOf(action.trigger) > -1) {
  46269. return true;
  46270. }
  46271. }
  46272. return false;
  46273. };
  46274. /**
  46275. * Does this action manager handles actions of a given trigger
  46276. * @param {number} trigger - the trigger to be tested
  46277. * @return {boolean} whether the trigger is handeled
  46278. */
  46279. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  46280. for (var index = 0; index < this.actions.length; index++) {
  46281. var action = this.actions[index];
  46282. if (action.trigger === trigger) {
  46283. return true;
  46284. }
  46285. }
  46286. return false;
  46287. };
  46288. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  46289. /**
  46290. * Does this action manager has pointer triggers
  46291. * @return {boolean} whether or not it has pointer triggers
  46292. */
  46293. get: function () {
  46294. for (var index = 0; index < this.actions.length; index++) {
  46295. var action = this.actions[index];
  46296. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  46297. return true;
  46298. }
  46299. }
  46300. return false;
  46301. },
  46302. enumerable: true,
  46303. configurable: true
  46304. });
  46305. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  46306. /**
  46307. * Does this action manager has pick triggers
  46308. * @return {boolean} whether or not it has pick triggers
  46309. */
  46310. get: function () {
  46311. for (var index = 0; index < this.actions.length; index++) {
  46312. var action = this.actions[index];
  46313. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  46314. return true;
  46315. }
  46316. }
  46317. return false;
  46318. },
  46319. enumerable: true,
  46320. configurable: true
  46321. });
  46322. Object.defineProperty(ActionManager, "HasTriggers", {
  46323. /**
  46324. * Does exist one action manager with at least one trigger
  46325. * @return {boolean} whether or not it exists one action manager with one trigger
  46326. **/
  46327. get: function () {
  46328. for (var t in ActionManager.Triggers) {
  46329. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46330. return true;
  46331. }
  46332. }
  46333. return false;
  46334. },
  46335. enumerable: true,
  46336. configurable: true
  46337. });
  46338. Object.defineProperty(ActionManager, "HasPickTriggers", {
  46339. /**
  46340. * Does exist one action manager with at least one pick trigger
  46341. * @return {boolean} whether or not it exists one action manager with one pick trigger
  46342. **/
  46343. get: function () {
  46344. for (var t in ActionManager.Triggers) {
  46345. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46346. var t_int = parseInt(t);
  46347. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  46348. return true;
  46349. }
  46350. }
  46351. }
  46352. return false;
  46353. },
  46354. enumerable: true,
  46355. configurable: true
  46356. });
  46357. /**
  46358. * Does exist one action manager that handles actions of a given trigger
  46359. * @param {number} trigger - the trigger to be tested
  46360. * @return {boolean} whether the trigger is handeled by at least one action manager
  46361. **/
  46362. ActionManager.HasSpecificTrigger = function (trigger) {
  46363. for (var t in ActionManager.Triggers) {
  46364. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46365. var t_int = parseInt(t);
  46366. if (t_int === trigger) {
  46367. return true;
  46368. }
  46369. }
  46370. }
  46371. return false;
  46372. };
  46373. /**
  46374. * Registers an action to this action manager
  46375. * @param {BABYLON.Action} action - the action to be registered
  46376. * @return {BABYLON.Action} the action amended (prepared) after registration
  46377. */
  46378. ActionManager.prototype.registerAction = function (action) {
  46379. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  46380. if (this.getScene().actionManager !== this) {
  46381. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  46382. return null;
  46383. }
  46384. }
  46385. this.actions.push(action);
  46386. if (ActionManager.Triggers[action.trigger]) {
  46387. ActionManager.Triggers[action.trigger]++;
  46388. }
  46389. else {
  46390. ActionManager.Triggers[action.trigger] = 1;
  46391. }
  46392. action._actionManager = this;
  46393. action._prepare();
  46394. return action;
  46395. };
  46396. /**
  46397. * Process a specific trigger
  46398. * @param {number} trigger - the trigger to process
  46399. * @param evt {BABYLON.ActionEvent} the event details to be processed
  46400. */
  46401. ActionManager.prototype.processTrigger = function (trigger, evt) {
  46402. for (var index = 0; index < this.actions.length; index++) {
  46403. var action = this.actions[index];
  46404. if (action.trigger === trigger) {
  46405. if (trigger === ActionManager.OnKeyUpTrigger
  46406. || trigger === ActionManager.OnKeyDownTrigger) {
  46407. var parameter = action.getTriggerParameter();
  46408. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  46409. if (!parameter.toLowerCase) {
  46410. continue;
  46411. }
  46412. var lowerCase = parameter.toLowerCase();
  46413. if (lowerCase !== evt.sourceEvent.key) {
  46414. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  46415. var actualkey = String.fromCharCode(unicode).toLowerCase();
  46416. if (actualkey !== lowerCase) {
  46417. continue;
  46418. }
  46419. }
  46420. }
  46421. }
  46422. action._executeCurrent(evt);
  46423. }
  46424. }
  46425. };
  46426. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  46427. var properties = propertyPath.split(".");
  46428. for (var index = 0; index < properties.length - 1; index++) {
  46429. target = target[properties[index]];
  46430. }
  46431. return target;
  46432. };
  46433. ActionManager.prototype._getProperty = function (propertyPath) {
  46434. var properties = propertyPath.split(".");
  46435. return properties[properties.length - 1];
  46436. };
  46437. ActionManager.prototype.serialize = function (name) {
  46438. var root = {
  46439. children: [],
  46440. name: name,
  46441. type: 3,
  46442. properties: [] // Empty for root but required
  46443. };
  46444. for (var i = 0; i < this.actions.length; i++) {
  46445. var triggerObject = {
  46446. type: 0,
  46447. children: [],
  46448. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  46449. properties: []
  46450. };
  46451. var triggerOptions = this.actions[i].triggerOptions;
  46452. if (triggerOptions && typeof triggerOptions !== "number") {
  46453. if (triggerOptions.parameter instanceof BABYLON.Node) {
  46454. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  46455. }
  46456. else {
  46457. var parameter = {};
  46458. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  46459. if (triggerOptions.parameter.mesh) {
  46460. parameter._meshId = triggerOptions.parameter.mesh.id;
  46461. }
  46462. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  46463. }
  46464. }
  46465. // Serialize child action, recursively
  46466. this.actions[i].serialize(triggerObject);
  46467. // Add serialized trigger
  46468. root.children.push(triggerObject);
  46469. }
  46470. return root;
  46471. };
  46472. ActionManager.Parse = function (parsedActions, object, scene) {
  46473. var actionManager = new BABYLON.ActionManager(scene);
  46474. if (object === null)
  46475. scene.actionManager = actionManager;
  46476. else
  46477. object.actionManager = actionManager;
  46478. // instanciate a new object
  46479. var instanciate = function (name, params) {
  46480. var newInstance = Object.create(BABYLON[name].prototype);
  46481. newInstance.constructor.apply(newInstance, params);
  46482. return newInstance;
  46483. };
  46484. var parseParameter = function (name, value, target, propertyPath) {
  46485. if (propertyPath === null) {
  46486. // String, boolean or float
  46487. var floatValue = parseFloat(value);
  46488. if (value === "true" || value === "false")
  46489. return value === "true";
  46490. else
  46491. return isNaN(floatValue) ? value : floatValue;
  46492. }
  46493. var effectiveTarget = propertyPath.split(".");
  46494. var values = value.split(",");
  46495. // Get effective Target
  46496. for (var i = 0; i < effectiveTarget.length; i++) {
  46497. target = target[effectiveTarget[i]];
  46498. }
  46499. // Return appropriate value with its type
  46500. if (typeof (target) === "boolean")
  46501. return values[0] === "true";
  46502. if (typeof (target) === "string")
  46503. return values[0];
  46504. // Parameters with multiple values such as Vector3 etc.
  46505. var split = new Array();
  46506. for (var i = 0; i < values.length; i++)
  46507. split.push(parseFloat(values[i]));
  46508. if (target instanceof BABYLON.Vector3)
  46509. return BABYLON.Vector3.FromArray(split);
  46510. if (target instanceof BABYLON.Vector4)
  46511. return BABYLON.Vector4.FromArray(split);
  46512. if (target instanceof BABYLON.Color3)
  46513. return BABYLON.Color3.FromArray(split);
  46514. if (target instanceof BABYLON.Color4)
  46515. return BABYLON.Color4.FromArray(split);
  46516. return parseFloat(values[0]);
  46517. };
  46518. // traverse graph per trigger
  46519. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  46520. if (combineArray === void 0) { combineArray = null; }
  46521. if (parsedAction.detached)
  46522. return;
  46523. var parameters = new Array();
  46524. var target = null;
  46525. var propertyPath = null;
  46526. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  46527. // Parameters
  46528. if (parsedAction.type === 2)
  46529. parameters.push(actionManager);
  46530. else
  46531. parameters.push(trigger);
  46532. if (combine) {
  46533. var actions = new Array();
  46534. for (var j = 0; j < parsedAction.combine.length; j++) {
  46535. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  46536. }
  46537. parameters.push(actions);
  46538. }
  46539. else {
  46540. for (var i = 0; i < parsedAction.properties.length; i++) {
  46541. var value = parsedAction.properties[i].value;
  46542. var name = parsedAction.properties[i].name;
  46543. var targetType = parsedAction.properties[i].targetType;
  46544. if (name === "target")
  46545. if (targetType !== null && targetType === "SceneProperties")
  46546. value = target = scene;
  46547. else
  46548. value = target = scene.getNodeByName(value);
  46549. else if (name === "parent")
  46550. value = scene.getNodeByName(value);
  46551. else if (name === "sound")
  46552. value = scene.getSoundByName(value);
  46553. else if (name !== "propertyPath") {
  46554. if (parsedAction.type === 2 && name === "operator")
  46555. value = BABYLON.ValueCondition[value];
  46556. else
  46557. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  46558. }
  46559. else {
  46560. propertyPath = value;
  46561. }
  46562. parameters.push(value);
  46563. }
  46564. }
  46565. if (combineArray === null) {
  46566. parameters.push(condition);
  46567. }
  46568. else {
  46569. parameters.push(null);
  46570. }
  46571. // If interpolate value action
  46572. if (parsedAction.name === "InterpolateValueAction") {
  46573. var param = parameters[parameters.length - 2];
  46574. parameters[parameters.length - 1] = param;
  46575. parameters[parameters.length - 2] = condition;
  46576. }
  46577. // Action or condition(s) and not CombineAction
  46578. var newAction = instanciate(parsedAction.name, parameters);
  46579. if (newAction instanceof BABYLON.Condition && condition !== null) {
  46580. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  46581. if (action)
  46582. action.then(nothing);
  46583. else
  46584. actionManager.registerAction(nothing);
  46585. action = nothing;
  46586. }
  46587. if (combineArray === null) {
  46588. if (newAction instanceof BABYLON.Condition) {
  46589. condition = newAction;
  46590. newAction = action;
  46591. }
  46592. else {
  46593. condition = null;
  46594. if (action)
  46595. action.then(newAction);
  46596. else
  46597. actionManager.registerAction(newAction);
  46598. }
  46599. }
  46600. else {
  46601. combineArray.push(newAction);
  46602. }
  46603. for (var i = 0; i < parsedAction.children.length; i++)
  46604. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  46605. };
  46606. // triggers
  46607. for (var i = 0; i < parsedActions.children.length; i++) {
  46608. var triggerParams;
  46609. var trigger = parsedActions.children[i];
  46610. if (trigger.properties.length > 0) {
  46611. var param = trigger.properties[0].value;
  46612. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  46613. if (value._meshId) {
  46614. value.mesh = scene.getMeshByID(value._meshId);
  46615. }
  46616. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  46617. }
  46618. else
  46619. triggerParams = BABYLON.ActionManager[trigger.name];
  46620. for (var j = 0; j < trigger.children.length; j++) {
  46621. if (!trigger.detached)
  46622. traverse(trigger.children[j], triggerParams, null, null);
  46623. }
  46624. }
  46625. };
  46626. ActionManager.GetTriggerName = function (trigger) {
  46627. switch (trigger) {
  46628. case 0: return "NothingTrigger";
  46629. case 1: return "OnPickTrigger";
  46630. case 2: return "OnLeftPickTrigger";
  46631. case 3: return "OnRightPickTrigger";
  46632. case 4: return "OnCenterPickTrigger";
  46633. case 5: return "OnPickDownTrigger";
  46634. case 6: return "OnPickUpTrigger";
  46635. case 7: return "OnLongPressTrigger";
  46636. case 8: return "OnPointerOverTrigger";
  46637. case 9: return "OnPointerOutTrigger";
  46638. case 10: return "OnEveryFrameTrigger";
  46639. case 11: return "OnIntersectionEnterTrigger";
  46640. case 12: return "OnIntersectionExitTrigger";
  46641. case 13: return "OnKeyDownTrigger";
  46642. case 14: return "OnKeyUpTrigger";
  46643. case 15: return "OnPickOutTrigger";
  46644. default: return "";
  46645. }
  46646. };
  46647. // Statics
  46648. ActionManager._NothingTrigger = 0;
  46649. ActionManager._OnPickTrigger = 1;
  46650. ActionManager._OnLeftPickTrigger = 2;
  46651. ActionManager._OnRightPickTrigger = 3;
  46652. ActionManager._OnCenterPickTrigger = 4;
  46653. ActionManager._OnPickDownTrigger = 5;
  46654. ActionManager._OnDoublePickTrigger = 6;
  46655. ActionManager._OnPickUpTrigger = 7;
  46656. ActionManager._OnLongPressTrigger = 8;
  46657. ActionManager._OnPointerOverTrigger = 9;
  46658. ActionManager._OnPointerOutTrigger = 10;
  46659. ActionManager._OnEveryFrameTrigger = 11;
  46660. ActionManager._OnIntersectionEnterTrigger = 12;
  46661. ActionManager._OnIntersectionExitTrigger = 13;
  46662. ActionManager._OnKeyDownTrigger = 14;
  46663. ActionManager._OnKeyUpTrigger = 15;
  46664. ActionManager._OnPickOutTrigger = 16;
  46665. ActionManager.Triggers = {};
  46666. return ActionManager;
  46667. }());
  46668. BABYLON.ActionManager = ActionManager;
  46669. })(BABYLON || (BABYLON = {}));
  46670. //# sourceMappingURL=babylon.actionManager.js.map
  46671. var BABYLON;
  46672. (function (BABYLON) {
  46673. var InterpolateValueAction = (function (_super) {
  46674. __extends(InterpolateValueAction, _super);
  46675. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  46676. if (duration === void 0) { duration = 1000; }
  46677. var _this = _super.call(this, triggerOptions, condition) || this;
  46678. _this.propertyPath = propertyPath;
  46679. _this.value = value;
  46680. _this.duration = duration;
  46681. _this.stopOtherAnimations = stopOtherAnimations;
  46682. _this.onInterpolationDone = onInterpolationDone;
  46683. _this._target = _this._effectiveTarget = target;
  46684. return _this;
  46685. }
  46686. InterpolateValueAction.prototype._prepare = function () {
  46687. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46688. this._property = this._getProperty(this.propertyPath);
  46689. };
  46690. InterpolateValueAction.prototype.execute = function () {
  46691. var scene = this._actionManager.getScene();
  46692. var keys = [
  46693. {
  46694. frame: 0,
  46695. value: this._effectiveTarget[this._property]
  46696. }, {
  46697. frame: 100,
  46698. value: this.value
  46699. }
  46700. ];
  46701. var dataType;
  46702. if (typeof this.value === "number") {
  46703. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  46704. }
  46705. else if (this.value instanceof BABYLON.Color3) {
  46706. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  46707. }
  46708. else if (this.value instanceof BABYLON.Vector3) {
  46709. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  46710. }
  46711. else if (this.value instanceof BABYLON.Matrix) {
  46712. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  46713. }
  46714. else if (this.value instanceof BABYLON.Quaternion) {
  46715. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  46716. }
  46717. else {
  46718. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  46719. return;
  46720. }
  46721. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  46722. animation.setKeys(keys);
  46723. if (this.stopOtherAnimations) {
  46724. scene.stopAnimation(this._effectiveTarget);
  46725. }
  46726. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  46727. };
  46728. InterpolateValueAction.prototype.serialize = function (parent) {
  46729. return _super.prototype._serialize.call(this, {
  46730. name: "InterpolateValueAction",
  46731. properties: [
  46732. BABYLON.Action._GetTargetProperty(this._target),
  46733. { name: "propertyPath", value: this.propertyPath },
  46734. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46735. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  46736. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  46737. ]
  46738. }, parent);
  46739. };
  46740. return InterpolateValueAction;
  46741. }(BABYLON.Action));
  46742. BABYLON.InterpolateValueAction = InterpolateValueAction;
  46743. })(BABYLON || (BABYLON = {}));
  46744. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  46745. var BABYLON;
  46746. (function (BABYLON) {
  46747. var SwitchBooleanAction = (function (_super) {
  46748. __extends(SwitchBooleanAction, _super);
  46749. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  46750. var _this = _super.call(this, triggerOptions, condition) || this;
  46751. _this.propertyPath = propertyPath;
  46752. _this._target = _this._effectiveTarget = target;
  46753. return _this;
  46754. }
  46755. SwitchBooleanAction.prototype._prepare = function () {
  46756. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46757. this._property = this._getProperty(this.propertyPath);
  46758. };
  46759. SwitchBooleanAction.prototype.execute = function () {
  46760. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  46761. };
  46762. SwitchBooleanAction.prototype.serialize = function (parent) {
  46763. return _super.prototype._serialize.call(this, {
  46764. name: "SwitchBooleanAction",
  46765. properties: [
  46766. BABYLON.Action._GetTargetProperty(this._target),
  46767. { name: "propertyPath", value: this.propertyPath }
  46768. ]
  46769. }, parent);
  46770. };
  46771. return SwitchBooleanAction;
  46772. }(BABYLON.Action));
  46773. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  46774. var SetStateAction = (function (_super) {
  46775. __extends(SetStateAction, _super);
  46776. function SetStateAction(triggerOptions, target, value, condition) {
  46777. var _this = _super.call(this, triggerOptions, condition) || this;
  46778. _this.value = value;
  46779. _this._target = target;
  46780. return _this;
  46781. }
  46782. SetStateAction.prototype.execute = function () {
  46783. this._target.state = this.value;
  46784. };
  46785. SetStateAction.prototype.serialize = function (parent) {
  46786. return _super.prototype._serialize.call(this, {
  46787. name: "SetStateAction",
  46788. properties: [
  46789. BABYLON.Action._GetTargetProperty(this._target),
  46790. { name: "value", value: this.value }
  46791. ]
  46792. }, parent);
  46793. };
  46794. return SetStateAction;
  46795. }(BABYLON.Action));
  46796. BABYLON.SetStateAction = SetStateAction;
  46797. var SetValueAction = (function (_super) {
  46798. __extends(SetValueAction, _super);
  46799. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  46800. var _this = _super.call(this, triggerOptions, condition) || this;
  46801. _this.propertyPath = propertyPath;
  46802. _this.value = value;
  46803. _this._target = _this._effectiveTarget = target;
  46804. return _this;
  46805. }
  46806. SetValueAction.prototype._prepare = function () {
  46807. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46808. this._property = this._getProperty(this.propertyPath);
  46809. };
  46810. SetValueAction.prototype.execute = function () {
  46811. this._effectiveTarget[this._property] = this.value;
  46812. if (this._target.markAsDirty) {
  46813. this._target.markAsDirty(this._property);
  46814. }
  46815. };
  46816. SetValueAction.prototype.serialize = function (parent) {
  46817. return _super.prototype._serialize.call(this, {
  46818. name: "SetValueAction",
  46819. properties: [
  46820. BABYLON.Action._GetTargetProperty(this._target),
  46821. { name: "propertyPath", value: this.propertyPath },
  46822. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46823. ]
  46824. }, parent);
  46825. };
  46826. return SetValueAction;
  46827. }(BABYLON.Action));
  46828. BABYLON.SetValueAction = SetValueAction;
  46829. var IncrementValueAction = (function (_super) {
  46830. __extends(IncrementValueAction, _super);
  46831. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  46832. var _this = _super.call(this, triggerOptions, condition) || this;
  46833. _this.propertyPath = propertyPath;
  46834. _this.value = value;
  46835. _this._target = _this._effectiveTarget = target;
  46836. return _this;
  46837. }
  46838. IncrementValueAction.prototype._prepare = function () {
  46839. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46840. this._property = this._getProperty(this.propertyPath);
  46841. if (typeof this._effectiveTarget[this._property] !== "number") {
  46842. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  46843. }
  46844. };
  46845. IncrementValueAction.prototype.execute = function () {
  46846. this._effectiveTarget[this._property] += this.value;
  46847. if (this._target.markAsDirty) {
  46848. this._target.markAsDirty(this._property);
  46849. }
  46850. };
  46851. IncrementValueAction.prototype.serialize = function (parent) {
  46852. return _super.prototype._serialize.call(this, {
  46853. name: "IncrementValueAction",
  46854. properties: [
  46855. BABYLON.Action._GetTargetProperty(this._target),
  46856. { name: "propertyPath", value: this.propertyPath },
  46857. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46858. ]
  46859. }, parent);
  46860. };
  46861. return IncrementValueAction;
  46862. }(BABYLON.Action));
  46863. BABYLON.IncrementValueAction = IncrementValueAction;
  46864. var PlayAnimationAction = (function (_super) {
  46865. __extends(PlayAnimationAction, _super);
  46866. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  46867. var _this = _super.call(this, triggerOptions, condition) || this;
  46868. _this.from = from;
  46869. _this.to = to;
  46870. _this.loop = loop;
  46871. _this._target = target;
  46872. return _this;
  46873. }
  46874. PlayAnimationAction.prototype._prepare = function () {
  46875. };
  46876. PlayAnimationAction.prototype.execute = function () {
  46877. var scene = this._actionManager.getScene();
  46878. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  46879. };
  46880. PlayAnimationAction.prototype.serialize = function (parent) {
  46881. return _super.prototype._serialize.call(this, {
  46882. name: "PlayAnimationAction",
  46883. properties: [
  46884. BABYLON.Action._GetTargetProperty(this._target),
  46885. { name: "from", value: String(this.from) },
  46886. { name: "to", value: String(this.to) },
  46887. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  46888. ]
  46889. }, parent);
  46890. };
  46891. return PlayAnimationAction;
  46892. }(BABYLON.Action));
  46893. BABYLON.PlayAnimationAction = PlayAnimationAction;
  46894. var StopAnimationAction = (function (_super) {
  46895. __extends(StopAnimationAction, _super);
  46896. function StopAnimationAction(triggerOptions, target, condition) {
  46897. var _this = _super.call(this, triggerOptions, condition) || this;
  46898. _this._target = target;
  46899. return _this;
  46900. }
  46901. StopAnimationAction.prototype._prepare = function () {
  46902. };
  46903. StopAnimationAction.prototype.execute = function () {
  46904. var scene = this._actionManager.getScene();
  46905. scene.stopAnimation(this._target);
  46906. };
  46907. StopAnimationAction.prototype.serialize = function (parent) {
  46908. return _super.prototype._serialize.call(this, {
  46909. name: "StopAnimationAction",
  46910. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  46911. }, parent);
  46912. };
  46913. return StopAnimationAction;
  46914. }(BABYLON.Action));
  46915. BABYLON.StopAnimationAction = StopAnimationAction;
  46916. var DoNothingAction = (function (_super) {
  46917. __extends(DoNothingAction, _super);
  46918. function DoNothingAction(triggerOptions, condition) {
  46919. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  46920. return _super.call(this, triggerOptions, condition) || this;
  46921. }
  46922. DoNothingAction.prototype.execute = function () {
  46923. };
  46924. DoNothingAction.prototype.serialize = function (parent) {
  46925. return _super.prototype._serialize.call(this, {
  46926. name: "DoNothingAction",
  46927. properties: []
  46928. }, parent);
  46929. };
  46930. return DoNothingAction;
  46931. }(BABYLON.Action));
  46932. BABYLON.DoNothingAction = DoNothingAction;
  46933. var CombineAction = (function (_super) {
  46934. __extends(CombineAction, _super);
  46935. function CombineAction(triggerOptions, children, condition) {
  46936. var _this = _super.call(this, triggerOptions, condition) || this;
  46937. _this.children = children;
  46938. return _this;
  46939. }
  46940. CombineAction.prototype._prepare = function () {
  46941. for (var index = 0; index < this.children.length; index++) {
  46942. this.children[index]._actionManager = this._actionManager;
  46943. this.children[index]._prepare();
  46944. }
  46945. };
  46946. CombineAction.prototype.execute = function (evt) {
  46947. for (var index = 0; index < this.children.length; index++) {
  46948. this.children[index].execute(evt);
  46949. }
  46950. };
  46951. CombineAction.prototype.serialize = function (parent) {
  46952. var serializationObject = _super.prototype._serialize.call(this, {
  46953. name: "CombineAction",
  46954. properties: [],
  46955. combine: []
  46956. }, parent);
  46957. for (var i = 0; i < this.children.length; i++) {
  46958. serializationObject.combine.push(this.children[i].serialize(null));
  46959. }
  46960. return serializationObject;
  46961. };
  46962. return CombineAction;
  46963. }(BABYLON.Action));
  46964. BABYLON.CombineAction = CombineAction;
  46965. var ExecuteCodeAction = (function (_super) {
  46966. __extends(ExecuteCodeAction, _super);
  46967. function ExecuteCodeAction(triggerOptions, func, condition) {
  46968. var _this = _super.call(this, triggerOptions, condition) || this;
  46969. _this.func = func;
  46970. return _this;
  46971. }
  46972. ExecuteCodeAction.prototype.execute = function (evt) {
  46973. this.func(evt);
  46974. };
  46975. return ExecuteCodeAction;
  46976. }(BABYLON.Action));
  46977. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  46978. var SetParentAction = (function (_super) {
  46979. __extends(SetParentAction, _super);
  46980. function SetParentAction(triggerOptions, target, parent, condition) {
  46981. var _this = _super.call(this, triggerOptions, condition) || this;
  46982. _this._target = target;
  46983. _this._parent = parent;
  46984. return _this;
  46985. }
  46986. SetParentAction.prototype._prepare = function () {
  46987. };
  46988. SetParentAction.prototype.execute = function () {
  46989. if (this._target.parent === this._parent) {
  46990. return;
  46991. }
  46992. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  46993. invertParentWorldMatrix.invert();
  46994. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  46995. this._target.parent = this._parent;
  46996. };
  46997. SetParentAction.prototype.serialize = function (parent) {
  46998. return _super.prototype._serialize.call(this, {
  46999. name: "SetParentAction",
  47000. properties: [
  47001. BABYLON.Action._GetTargetProperty(this._target),
  47002. BABYLON.Action._GetTargetProperty(this._parent),
  47003. ]
  47004. }, parent);
  47005. };
  47006. return SetParentAction;
  47007. }(BABYLON.Action));
  47008. BABYLON.SetParentAction = SetParentAction;
  47009. var PlaySoundAction = (function (_super) {
  47010. __extends(PlaySoundAction, _super);
  47011. function PlaySoundAction(triggerOptions, sound, condition) {
  47012. var _this = _super.call(this, triggerOptions, condition) || this;
  47013. _this._sound = sound;
  47014. return _this;
  47015. }
  47016. PlaySoundAction.prototype._prepare = function () {
  47017. };
  47018. PlaySoundAction.prototype.execute = function () {
  47019. if (this._sound !== undefined)
  47020. this._sound.play();
  47021. };
  47022. PlaySoundAction.prototype.serialize = function (parent) {
  47023. return _super.prototype._serialize.call(this, {
  47024. name: "PlaySoundAction",
  47025. properties: [{ name: "sound", value: this._sound.name }]
  47026. }, parent);
  47027. };
  47028. return PlaySoundAction;
  47029. }(BABYLON.Action));
  47030. BABYLON.PlaySoundAction = PlaySoundAction;
  47031. var StopSoundAction = (function (_super) {
  47032. __extends(StopSoundAction, _super);
  47033. function StopSoundAction(triggerOptions, sound, condition) {
  47034. var _this = _super.call(this, triggerOptions, condition) || this;
  47035. _this._sound = sound;
  47036. return _this;
  47037. }
  47038. StopSoundAction.prototype._prepare = function () {
  47039. };
  47040. StopSoundAction.prototype.execute = function () {
  47041. if (this._sound !== undefined)
  47042. this._sound.stop();
  47043. };
  47044. StopSoundAction.prototype.serialize = function (parent) {
  47045. return _super.prototype._serialize.call(this, {
  47046. name: "StopSoundAction",
  47047. properties: [{ name: "sound", value: this._sound.name }]
  47048. }, parent);
  47049. };
  47050. return StopSoundAction;
  47051. }(BABYLON.Action));
  47052. BABYLON.StopSoundAction = StopSoundAction;
  47053. })(BABYLON || (BABYLON = {}));
  47054. //# sourceMappingURL=babylon.directActions.js.map
  47055. var BABYLON;
  47056. (function (BABYLON) {
  47057. var Debug;
  47058. (function (Debug) {
  47059. /**
  47060. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  47061. */
  47062. var SkeletonViewer = (function () {
  47063. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  47064. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  47065. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  47066. this.skeleton = skeleton;
  47067. this.mesh = mesh;
  47068. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  47069. this.renderingGroupId = renderingGroupId;
  47070. this.color = BABYLON.Color3.White();
  47071. this._debugLines = [];
  47072. this._isEnabled = false;
  47073. this._scene = scene;
  47074. this.update();
  47075. this._renderFunction = this.update.bind(this);
  47076. }
  47077. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  47078. get: function () {
  47079. return this._isEnabled;
  47080. },
  47081. set: function (value) {
  47082. if (this._isEnabled === value) {
  47083. return;
  47084. }
  47085. this._isEnabled = value;
  47086. if (value) {
  47087. this._scene.registerBeforeRender(this._renderFunction);
  47088. }
  47089. else {
  47090. this._scene.unregisterBeforeRender(this._renderFunction);
  47091. }
  47092. },
  47093. enumerable: true,
  47094. configurable: true
  47095. });
  47096. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  47097. if (x === void 0) { x = 0; }
  47098. if (y === void 0) { y = 0; }
  47099. if (z === void 0) { z = 0; }
  47100. var tmat = BABYLON.Tmp.Matrix[0];
  47101. var parentBone = bone.getParent();
  47102. tmat.copyFrom(bone.getLocalMatrix());
  47103. if (x !== 0 || y !== 0 || z !== 0) {
  47104. var tmat2 = BABYLON.Tmp.Matrix[1];
  47105. BABYLON.Matrix.IdentityToRef(tmat2);
  47106. tmat2.m[12] = x;
  47107. tmat2.m[13] = y;
  47108. tmat2.m[14] = z;
  47109. tmat2.multiplyToRef(tmat, tmat);
  47110. }
  47111. if (parentBone) {
  47112. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  47113. }
  47114. tmat.multiplyToRef(meshMat, tmat);
  47115. position.x = tmat.m[12];
  47116. position.y = tmat.m[13];
  47117. position.z = tmat.m[14];
  47118. };
  47119. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  47120. var len = bones.length;
  47121. var meshPos = this.mesh.position;
  47122. for (var i = 0; i < len; i++) {
  47123. var bone = bones[i];
  47124. var points = this._debugLines[i];
  47125. if (!points) {
  47126. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47127. this._debugLines[i] = points;
  47128. }
  47129. this._getBonePosition(points[0], bone, meshMat);
  47130. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  47131. points[0].subtractInPlace(meshPos);
  47132. points[1].subtractInPlace(meshPos);
  47133. }
  47134. };
  47135. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  47136. var len = bones.length;
  47137. var boneNum = 0;
  47138. var meshPos = this.mesh.position;
  47139. for (var i = len - 1; i >= 0; i--) {
  47140. var childBone = bones[i];
  47141. var parentBone = childBone.getParent();
  47142. if (!parentBone) {
  47143. continue;
  47144. }
  47145. var points = this._debugLines[boneNum];
  47146. if (!points) {
  47147. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47148. this._debugLines[boneNum] = points;
  47149. }
  47150. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  47151. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  47152. points[0].subtractInPlace(meshPos);
  47153. points[1].subtractInPlace(meshPos);
  47154. boneNum++;
  47155. }
  47156. };
  47157. SkeletonViewer.prototype.update = function () {
  47158. if (this.autoUpdateBonesMatrices) {
  47159. this.skeleton.computeAbsoluteTransforms();
  47160. }
  47161. if (this.skeleton.bones[0].length === undefined) {
  47162. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  47163. }
  47164. else {
  47165. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  47166. }
  47167. if (!this._debugMesh) {
  47168. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  47169. this._debugMesh.renderingGroupId = this.renderingGroupId;
  47170. }
  47171. else {
  47172. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  47173. }
  47174. this._debugMesh.position.copyFrom(this.mesh.position);
  47175. this._debugMesh.color = this.color;
  47176. };
  47177. SkeletonViewer.prototype.dispose = function () {
  47178. if (this._debugMesh) {
  47179. this.isEnabled = false;
  47180. this._debugMesh.dispose();
  47181. this._debugMesh = null;
  47182. }
  47183. };
  47184. return SkeletonViewer;
  47185. }());
  47186. Debug.SkeletonViewer = SkeletonViewer;
  47187. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47188. })(BABYLON || (BABYLON = {}));
  47189. //# sourceMappingURL=babylon.skeletonViewer.js.map
  47190. var BABYLON;
  47191. (function (BABYLON) {
  47192. var Debug;
  47193. (function (Debug) {
  47194. var AxesViewer = (function () {
  47195. function AxesViewer(scene, scaleLines) {
  47196. if (scaleLines === void 0) { scaleLines = 1; }
  47197. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47198. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47199. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47200. this.scaleLines = 1;
  47201. this.scaleLines = scaleLines;
  47202. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  47203. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  47204. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  47205. this._xmesh.renderingGroupId = 2;
  47206. this._ymesh.renderingGroupId = 2;
  47207. this._zmesh.renderingGroupId = 2;
  47208. this._xmesh.material.checkReadyOnlyOnce = true;
  47209. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  47210. this._ymesh.material.checkReadyOnlyOnce = true;
  47211. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  47212. this._zmesh.material.checkReadyOnlyOnce = true;
  47213. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  47214. this.scene = scene;
  47215. }
  47216. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  47217. var scaleLines = this.scaleLines;
  47218. this._xmesh.position.copyFrom(position);
  47219. this._ymesh.position.copyFrom(position);
  47220. this._zmesh.position.copyFrom(position);
  47221. var point2 = this._xline[1];
  47222. point2.x = xaxis.x * scaleLines;
  47223. point2.y = xaxis.y * scaleLines;
  47224. point2.z = xaxis.z * scaleLines;
  47225. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  47226. point2 = this._yline[1];
  47227. point2.x = yaxis.x * scaleLines;
  47228. point2.y = yaxis.y * scaleLines;
  47229. point2.z = yaxis.z * scaleLines;
  47230. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  47231. point2 = this._zline[1];
  47232. point2.x = zaxis.x * scaleLines;
  47233. point2.y = zaxis.y * scaleLines;
  47234. point2.z = zaxis.z * scaleLines;
  47235. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  47236. };
  47237. AxesViewer.prototype.dispose = function () {
  47238. if (this._xmesh) {
  47239. this._xmesh.dispose();
  47240. this._ymesh.dispose();
  47241. this._zmesh.dispose();
  47242. this._xmesh = null;
  47243. this._ymesh = null;
  47244. this._zmesh = null;
  47245. this._xline = null;
  47246. this._yline = null;
  47247. this._zline = null;
  47248. this.scene = null;
  47249. }
  47250. };
  47251. return AxesViewer;
  47252. }());
  47253. Debug.AxesViewer = AxesViewer;
  47254. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47255. })(BABYLON || (BABYLON = {}));
  47256. //# sourceMappingURL=babylon.axesViewer.js.map
  47257. var BABYLON;
  47258. (function (BABYLON) {
  47259. var Debug;
  47260. (function (Debug) {
  47261. var BoneAxesViewer = (function (_super) {
  47262. __extends(BoneAxesViewer, _super);
  47263. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  47264. if (scaleLines === void 0) { scaleLines = 1; }
  47265. var _this = _super.call(this, scene, scaleLines) || this;
  47266. _this.pos = BABYLON.Vector3.Zero();
  47267. _this.xaxis = BABYLON.Vector3.Zero();
  47268. _this.yaxis = BABYLON.Vector3.Zero();
  47269. _this.zaxis = BABYLON.Vector3.Zero();
  47270. _this.mesh = mesh;
  47271. _this.bone = bone;
  47272. return _this;
  47273. }
  47274. BoneAxesViewer.prototype.update = function () {
  47275. var bone = this.bone;
  47276. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  47277. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  47278. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  47279. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  47280. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  47281. };
  47282. BoneAxesViewer.prototype.dispose = function () {
  47283. if (this.pos) {
  47284. this.pos = null;
  47285. this.xaxis = null;
  47286. this.yaxis = null;
  47287. this.zaxis = null;
  47288. this.mesh = null;
  47289. this.bone = null;
  47290. _super.prototype.dispose.call(this);
  47291. }
  47292. };
  47293. return BoneAxesViewer;
  47294. }(Debug.AxesViewer));
  47295. Debug.BoneAxesViewer = BoneAxesViewer;
  47296. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47297. })(BABYLON || (BABYLON = {}));
  47298. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  47299. var BABYLON;
  47300. (function (BABYLON) {
  47301. var RayHelper = (function () {
  47302. function RayHelper(ray) {
  47303. this.ray = ray;
  47304. }
  47305. RayHelper.CreateAndShow = function (ray, scene, color) {
  47306. var helper = new RayHelper(ray);
  47307. helper.show(scene, color);
  47308. return helper;
  47309. };
  47310. RayHelper.prototype.show = function (scene, color) {
  47311. if (!this._renderFunction) {
  47312. var ray = this.ray;
  47313. this._renderFunction = this._render.bind(this);
  47314. this._scene = scene;
  47315. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  47316. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  47317. this._scene.registerBeforeRender(this._renderFunction);
  47318. }
  47319. if (color) {
  47320. this._renderLine.color.copyFrom(color);
  47321. }
  47322. };
  47323. RayHelper.prototype.hide = function () {
  47324. if (this._renderFunction) {
  47325. this._scene.unregisterBeforeRender(this._renderFunction);
  47326. this._scene = null;
  47327. this._renderFunction = null;
  47328. this._renderLine.dispose();
  47329. this._renderLine = null;
  47330. this._renderPoints = null;
  47331. }
  47332. };
  47333. RayHelper.prototype._render = function () {
  47334. var ray = this.ray;
  47335. var point = this._renderPoints[1];
  47336. var len = Math.min(ray.length, 1000000);
  47337. point.copyFrom(ray.direction);
  47338. point.scaleInPlace(len);
  47339. point.addInPlace(ray.origin);
  47340. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  47341. };
  47342. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  47343. this._attachedToMesh = mesh;
  47344. var ray = this.ray;
  47345. if (!ray.direction) {
  47346. ray.direction = BABYLON.Vector3.Zero();
  47347. }
  47348. if (!ray.origin) {
  47349. ray.origin = BABYLON.Vector3.Zero();
  47350. }
  47351. if (length) {
  47352. ray.length = length;
  47353. }
  47354. if (!meshSpaceOrigin) {
  47355. meshSpaceOrigin = BABYLON.Vector3.Zero();
  47356. }
  47357. if (!meshSpaceDirection) {
  47358. // -1 so that this will work with Mesh.lookAt
  47359. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  47360. }
  47361. if (!this._meshSpaceDirection) {
  47362. this._meshSpaceDirection = meshSpaceDirection.clone();
  47363. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  47364. }
  47365. else {
  47366. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  47367. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  47368. }
  47369. if (!this._updateToMeshFunction) {
  47370. this._updateToMeshFunction = this._updateToMesh.bind(this);
  47371. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  47372. }
  47373. this._updateToMesh();
  47374. };
  47375. RayHelper.prototype.detachFromMesh = function () {
  47376. if (this._attachedToMesh) {
  47377. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  47378. this._attachedToMesh = null;
  47379. this._updateToMeshFunction = null;
  47380. }
  47381. };
  47382. RayHelper.prototype._updateToMesh = function () {
  47383. var ray = this.ray;
  47384. if (this._attachedToMesh._isDisposed) {
  47385. this.detachFromMesh();
  47386. return;
  47387. }
  47388. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  47389. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  47390. };
  47391. RayHelper.prototype.dispose = function () {
  47392. this.hide();
  47393. this.detachFromMesh();
  47394. this.ray = null;
  47395. };
  47396. return RayHelper;
  47397. }());
  47398. BABYLON.RayHelper = RayHelper;
  47399. })(BABYLON || (BABYLON = {}));
  47400. //# sourceMappingURL=babylon.rayHelper.js.map
  47401. var BABYLON;
  47402. (function (BABYLON) {
  47403. var DebugLayer = (function () {
  47404. function DebugLayer(scene) {
  47405. this._scene = scene;
  47406. }
  47407. /** Creates the inspector window. */
  47408. DebugLayer.prototype._createInspector = function (config) {
  47409. if (config === void 0) { config = {}; }
  47410. var popup = config.popup || false;
  47411. var initialTab = config.initialTab || 0;
  47412. var parentElement = config.parentElement || null;
  47413. if (!this._inspector) {
  47414. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  47415. } // else nothing to do,; instance is already existing
  47416. };
  47417. DebugLayer.prototype.isVisible = function () {
  47418. if (!this._inspector) {
  47419. return false;
  47420. }
  47421. return true;
  47422. };
  47423. DebugLayer.prototype.hide = function () {
  47424. if (this._inspector) {
  47425. try {
  47426. this._inspector.dispose();
  47427. }
  47428. catch (e) {
  47429. // If the inspector has been removed directly from the inspector tool
  47430. }
  47431. this._inspector = null;
  47432. }
  47433. };
  47434. DebugLayer.prototype.show = function (config) {
  47435. if (config === void 0) { config = {}; }
  47436. if (typeof INSPECTOR == 'undefined') {
  47437. // Load inspector and add it to the DOM
  47438. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  47439. }
  47440. else {
  47441. // Otherwise creates the inspector
  47442. this._createInspector(config);
  47443. }
  47444. };
  47445. // Get protocol used - http or https
  47446. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  47447. return DebugLayer;
  47448. }());
  47449. BABYLON.DebugLayer = DebugLayer;
  47450. })(BABYLON || (BABYLON = {}));
  47451. //# sourceMappingURL=babylon.debugLayer.js.map
  47452. var BABYLON;
  47453. (function (BABYLON) {
  47454. var Debug;
  47455. (function (Debug) {
  47456. var PhysicsViewer = (function () {
  47457. function PhysicsViewer(scene) {
  47458. this._impostors = [];
  47459. this._meshes = [];
  47460. this._numMeshes = 0;
  47461. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47462. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  47463. }
  47464. PhysicsViewer.prototype._updateDebugMeshes = function () {
  47465. var plugin = this._physicsEnginePlugin;
  47466. for (var i = 0; i < this._numMeshes; i++) {
  47467. if (this._impostors[i].isDisposed) {
  47468. this.hideImpostor(this._impostors[i--]);
  47469. }
  47470. else {
  47471. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  47472. }
  47473. }
  47474. };
  47475. PhysicsViewer.prototype.showImpostor = function (impostor) {
  47476. for (var i = 0; i < this._numMeshes; i++) {
  47477. if (this._impostors[i] == impostor) {
  47478. return;
  47479. }
  47480. }
  47481. var debugMesh = this._getDebugMesh(impostor, this._scene);
  47482. if (debugMesh) {
  47483. this._impostors[this._numMeshes] = impostor;
  47484. this._meshes[this._numMeshes] = debugMesh;
  47485. if (this._numMeshes === 0) {
  47486. this._renderFunction = this._updateDebugMeshes.bind(this);
  47487. this._scene.registerBeforeRender(this._renderFunction);
  47488. }
  47489. this._numMeshes++;
  47490. }
  47491. };
  47492. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  47493. var removed = false;
  47494. for (var i = 0; i < this._numMeshes; i++) {
  47495. if (this._impostors[i] == impostor) {
  47496. this._scene.removeMesh(this._meshes[i]);
  47497. this._meshes[i].dispose();
  47498. this._numMeshes--;
  47499. if (this._numMeshes > 0) {
  47500. this._meshes[i] = this._meshes[this._numMeshes];
  47501. this._impostors[i] = this._impostors[this._numMeshes];
  47502. this._meshes[this._numMeshes] = null;
  47503. this._impostors[this._numMeshes] = null;
  47504. }
  47505. else {
  47506. this._meshes[0] = null;
  47507. this._impostors[0] = null;
  47508. }
  47509. removed = true;
  47510. break;
  47511. }
  47512. }
  47513. if (removed && this._numMeshes === 0) {
  47514. this._scene.unregisterBeforeRender(this._renderFunction);
  47515. }
  47516. };
  47517. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  47518. if (!this._debugMaterial) {
  47519. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  47520. this._debugMaterial.wireframe = true;
  47521. }
  47522. return this._debugMaterial;
  47523. };
  47524. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  47525. if (!this._debugBoxMesh) {
  47526. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  47527. this._debugBoxMesh.renderingGroupId = 1;
  47528. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  47529. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  47530. scene.removeMesh(this._debugBoxMesh);
  47531. }
  47532. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  47533. };
  47534. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  47535. if (!this._debugSphereMesh) {
  47536. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  47537. this._debugSphereMesh.renderingGroupId = 1;
  47538. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  47539. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  47540. scene.removeMesh(this._debugSphereMesh);
  47541. }
  47542. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  47543. };
  47544. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  47545. var body = impostor.physicsBody;
  47546. var shape = body.shapes[0];
  47547. var mesh;
  47548. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  47549. mesh = this._getDebugBoxMesh(scene);
  47550. impostor.getBoxSizeToRef(mesh.scaling);
  47551. }
  47552. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  47553. mesh = this._getDebugSphereMesh(scene);
  47554. var radius = impostor.getRadius();
  47555. mesh.scaling.x = radius * 2;
  47556. mesh.scaling.y = radius * 2;
  47557. mesh.scaling.z = radius * 2;
  47558. }
  47559. return mesh;
  47560. };
  47561. PhysicsViewer.prototype.dispose = function () {
  47562. for (var i = 0; i < this._numMeshes; i++) {
  47563. this.hideImpostor(this._impostors[i]);
  47564. }
  47565. if (this._debugBoxMesh) {
  47566. this._debugBoxMesh.dispose();
  47567. }
  47568. if (this._debugSphereMesh) {
  47569. this._debugSphereMesh.dispose();
  47570. }
  47571. if (this._debugMaterial) {
  47572. this._debugMaterial.dispose();
  47573. }
  47574. this._impostors.length = 0;
  47575. this._scene = null;
  47576. this._physicsEnginePlugin = null;
  47577. };
  47578. return PhysicsViewer;
  47579. }());
  47580. Debug.PhysicsViewer = PhysicsViewer;
  47581. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47582. })(BABYLON || (BABYLON = {}));
  47583. //# sourceMappingURL=babylon.physicsViewer.js.map
  47584. var BABYLON;
  47585. (function (BABYLON) {
  47586. var BoundingBoxRenderer = (function () {
  47587. function BoundingBoxRenderer(scene) {
  47588. this.frontColor = new BABYLON.Color3(1, 1, 1);
  47589. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  47590. this.showBackLines = true;
  47591. this.renderList = new BABYLON.SmartArray(32);
  47592. this._vertexBuffers = {};
  47593. this._scene = scene;
  47594. }
  47595. BoundingBoxRenderer.prototype._prepareRessources = function () {
  47596. if (this._colorShader) {
  47597. return;
  47598. }
  47599. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  47600. attributes: [BABYLON.VertexBuffer.PositionKind],
  47601. uniforms: ["world", "viewProjection", "color"]
  47602. });
  47603. var engine = this._scene.getEngine();
  47604. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  47605. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  47606. 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]);
  47607. };
  47608. BoundingBoxRenderer.prototype.reset = function () {
  47609. this.renderList.reset();
  47610. };
  47611. BoundingBoxRenderer.prototype.render = function () {
  47612. if (this.renderList.length === 0) {
  47613. return;
  47614. }
  47615. this._prepareRessources();
  47616. if (!this._colorShader.isReady()) {
  47617. return;
  47618. }
  47619. var engine = this._scene.getEngine();
  47620. engine.setDepthWrite(false);
  47621. this._colorShader._preBind();
  47622. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  47623. var boundingBox = this.renderList.data[boundingBoxIndex];
  47624. var min = boundingBox.minimum;
  47625. var max = boundingBox.maximum;
  47626. var diff = max.subtract(min);
  47627. var median = min.add(diff.scale(0.5));
  47628. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  47629. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  47630. .multiply(boundingBox.getWorldMatrix());
  47631. // VBOs
  47632. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  47633. if (this.showBackLines) {
  47634. // Back
  47635. engine.setDepthFunctionToGreaterOrEqual();
  47636. this._scene.resetCachedMaterial();
  47637. this._colorShader.setColor4("color", this.backColor.toColor4());
  47638. this._colorShader.bind(worldMatrix);
  47639. // Draw order
  47640. engine.draw(false, 0, 24);
  47641. }
  47642. // Front
  47643. engine.setDepthFunctionToLess();
  47644. this._scene.resetCachedMaterial();
  47645. this._colorShader.setColor4("color", this.frontColor.toColor4());
  47646. this._colorShader.bind(worldMatrix);
  47647. // Draw order
  47648. engine.draw(false, 0, 24);
  47649. }
  47650. this._colorShader.unbind();
  47651. engine.setDepthFunctionToLessOrEqual();
  47652. engine.setDepthWrite(true);
  47653. };
  47654. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  47655. this._prepareRessources();
  47656. if (!this._colorShader.isReady()) {
  47657. return;
  47658. }
  47659. var engine = this._scene.getEngine();
  47660. engine.setDepthWrite(false);
  47661. engine.setColorWrite(false);
  47662. this._colorShader._preBind();
  47663. var boundingBox = mesh._boundingInfo.boundingBox;
  47664. var min = boundingBox.minimum;
  47665. var max = boundingBox.maximum;
  47666. var diff = max.subtract(min);
  47667. var median = min.add(diff.scale(0.5));
  47668. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  47669. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  47670. .multiply(boundingBox.getWorldMatrix());
  47671. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  47672. engine.setDepthFunctionToLess();
  47673. this._scene.resetCachedMaterial();
  47674. this._colorShader.bind(worldMatrix);
  47675. engine.draw(false, 0, 24);
  47676. this._colorShader.unbind();
  47677. engine.setDepthFunctionToLessOrEqual();
  47678. engine.setDepthWrite(true);
  47679. engine.setColorWrite(true);
  47680. };
  47681. BoundingBoxRenderer.prototype.dispose = function () {
  47682. if (!this._colorShader) {
  47683. return;
  47684. }
  47685. this.renderList.dispose();
  47686. this._colorShader.dispose();
  47687. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  47688. if (buffer) {
  47689. buffer.dispose();
  47690. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  47691. }
  47692. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47693. };
  47694. return BoundingBoxRenderer;
  47695. }());
  47696. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  47697. })(BABYLON || (BABYLON = {}));
  47698. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  47699. var BABYLON;
  47700. (function (BABYLON) {
  47701. var TextureTools = (function () {
  47702. function TextureTools() {
  47703. }
  47704. /**
  47705. * Uses the GPU to create a copy texture rescaled at a given size
  47706. * @param texture Texture to copy from
  47707. * @param width Desired width
  47708. * @param height Desired height
  47709. * @return Generated texture
  47710. */
  47711. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  47712. if (useBilinearMode === void 0) { useBilinearMode = true; }
  47713. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  47714. var scene = texture.getScene();
  47715. var engine = scene.getEngine();
  47716. rtt.wrapU = texture.wrapU;
  47717. rtt.wrapV = texture.wrapV;
  47718. rtt.uOffset = texture.uOffset;
  47719. rtt.vOffset = texture.vOffset;
  47720. rtt.uScale = texture.uScale;
  47721. rtt.vScale = texture.vScale;
  47722. rtt.uAng = texture.uAng;
  47723. rtt.vAng = texture.vAng;
  47724. rtt.wAng = texture.wAng;
  47725. rtt.coordinatesIndex = texture.coordinatesIndex;
  47726. rtt.level = texture.level;
  47727. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  47728. rtt._texture.isReady = false;
  47729. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47730. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47731. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47732. passPostProcess.getEffect().executeWhenCompiled(function () {
  47733. passPostProcess.onApply = function (effect) {
  47734. effect.setTexture("textureSampler", texture);
  47735. };
  47736. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  47737. engine.unBindFramebuffer(rtt.getInternalTexture());
  47738. rtt.disposeFramebufferObjects();
  47739. passPostProcess.dispose();
  47740. rtt._texture.isReady = true;
  47741. });
  47742. return rtt;
  47743. };
  47744. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  47745. if (!scene._environmentBRDFTexture) {
  47746. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47747. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47748. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47749. scene._environmentBRDFTexture = texture;
  47750. }
  47751. return scene._environmentBRDFTexture;
  47752. };
  47753. 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=";
  47754. return TextureTools;
  47755. }());
  47756. BABYLON.TextureTools = TextureTools;
  47757. })(BABYLON || (BABYLON = {}));
  47758. //# sourceMappingURL=babylon.textureTools.js.map
  47759. var BABYLON;
  47760. (function (BABYLON) {
  47761. var SphericalPolynomial = (function () {
  47762. function SphericalPolynomial() {
  47763. this.x = BABYLON.Vector3.Zero();
  47764. this.y = BABYLON.Vector3.Zero();
  47765. this.z = BABYLON.Vector3.Zero();
  47766. this.xx = BABYLON.Vector3.Zero();
  47767. this.yy = BABYLON.Vector3.Zero();
  47768. this.zz = BABYLON.Vector3.Zero();
  47769. this.xy = BABYLON.Vector3.Zero();
  47770. this.yz = BABYLON.Vector3.Zero();
  47771. this.zx = BABYLON.Vector3.Zero();
  47772. }
  47773. SphericalPolynomial.prototype.addAmbient = function (color) {
  47774. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  47775. this.xx = this.xx.add(colorVector);
  47776. this.yy = this.yy.add(colorVector);
  47777. this.zz = this.zz.add(colorVector);
  47778. };
  47779. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  47780. var result = new SphericalPolynomial();
  47781. result.x = harmonics.L11.scale(1.02333);
  47782. result.y = harmonics.L1_1.scale(1.02333);
  47783. result.z = harmonics.L10.scale(1.02333);
  47784. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  47785. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  47786. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  47787. result.yz = harmonics.L2_1.scale(0.858086);
  47788. result.zx = harmonics.L21.scale(0.858086);
  47789. result.xy = harmonics.L2_2.scale(0.858086);
  47790. result.scale(1.0 / Math.PI);
  47791. return result;
  47792. };
  47793. SphericalPolynomial.prototype.scale = function (scale) {
  47794. this.x = this.x.scale(scale);
  47795. this.y = this.y.scale(scale);
  47796. this.z = this.z.scale(scale);
  47797. this.xx = this.xx.scale(scale);
  47798. this.yy = this.yy.scale(scale);
  47799. this.zz = this.zz.scale(scale);
  47800. this.yz = this.yz.scale(scale);
  47801. this.zx = this.zx.scale(scale);
  47802. this.xy = this.xy.scale(scale);
  47803. };
  47804. return SphericalPolynomial;
  47805. }());
  47806. BABYLON.SphericalPolynomial = SphericalPolynomial;
  47807. var SphericalHarmonics = (function () {
  47808. function SphericalHarmonics() {
  47809. this.L00 = BABYLON.Vector3.Zero();
  47810. this.L1_1 = BABYLON.Vector3.Zero();
  47811. this.L10 = BABYLON.Vector3.Zero();
  47812. this.L11 = BABYLON.Vector3.Zero();
  47813. this.L2_2 = BABYLON.Vector3.Zero();
  47814. this.L2_1 = BABYLON.Vector3.Zero();
  47815. this.L20 = BABYLON.Vector3.Zero();
  47816. this.L21 = BABYLON.Vector3.Zero();
  47817. this.L22 = BABYLON.Vector3.Zero();
  47818. }
  47819. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  47820. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  47821. var c = colorVector.scale(deltaSolidAngle);
  47822. this.L00 = this.L00.add(c.scale(0.282095));
  47823. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  47824. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  47825. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  47826. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  47827. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  47828. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  47829. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  47830. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  47831. };
  47832. SphericalHarmonics.prototype.scale = function (scale) {
  47833. this.L00 = this.L00.scale(scale);
  47834. this.L1_1 = this.L1_1.scale(scale);
  47835. this.L10 = this.L10.scale(scale);
  47836. this.L11 = this.L11.scale(scale);
  47837. this.L2_2 = this.L2_2.scale(scale);
  47838. this.L2_1 = this.L2_1.scale(scale);
  47839. this.L20 = this.L20.scale(scale);
  47840. this.L21 = this.L21.scale(scale);
  47841. this.L22 = this.L22.scale(scale);
  47842. };
  47843. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  47844. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  47845. //
  47846. // E_lm = A_l * L_lm
  47847. //
  47848. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  47849. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  47850. // the scaling factors are given in equation 9.
  47851. // Constant (Band 0)
  47852. this.L00 = this.L00.scale(3.141593);
  47853. // Linear (Band 1)
  47854. this.L1_1 = this.L1_1.scale(2.094395);
  47855. this.L10 = this.L10.scale(2.094395);
  47856. this.L11 = this.L11.scale(2.094395);
  47857. // Quadratic (Band 2)
  47858. this.L2_2 = this.L2_2.scale(0.785398);
  47859. this.L2_1 = this.L2_1.scale(0.785398);
  47860. this.L20 = this.L20.scale(0.785398);
  47861. this.L21 = this.L21.scale(0.785398);
  47862. this.L22 = this.L22.scale(0.785398);
  47863. };
  47864. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  47865. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  47866. // L = (1/pi) * E * rho
  47867. //
  47868. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  47869. this.scale(1.0 / Math.PI);
  47870. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  47871. // (The pixel shader must apply albedo after texture fetches, etc).
  47872. };
  47873. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  47874. var result = new SphericalHarmonics();
  47875. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  47876. result.L1_1 = polynomial.y.scale(0.977204);
  47877. result.L10 = polynomial.z.scale(0.977204);
  47878. result.L11 = polynomial.x.scale(0.977204);
  47879. result.L2_2 = polynomial.xy.scale(1.16538);
  47880. result.L2_1 = polynomial.yz.scale(1.16538);
  47881. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  47882. result.L21 = polynomial.zx.scale(1.16538);
  47883. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  47884. result.scale(Math.PI);
  47885. return result;
  47886. };
  47887. return SphericalHarmonics;
  47888. }());
  47889. BABYLON.SphericalHarmonics = SphericalHarmonics;
  47890. })(BABYLON || (BABYLON = {}));
  47891. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  47892. var BABYLON;
  47893. (function (BABYLON) {
  47894. var Internals;
  47895. (function (Internals) {
  47896. var FileFaceOrientation = (function () {
  47897. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  47898. this.name = name;
  47899. this.worldAxisForNormal = worldAxisForNormal;
  47900. this.worldAxisForFileX = worldAxisForFileX;
  47901. this.worldAxisForFileY = worldAxisForFileY;
  47902. }
  47903. return FileFaceOrientation;
  47904. }());
  47905. ;
  47906. /**
  47907. * Helper class dealing with the extraction of spherical polynomial dataArray
  47908. * from a cube map.
  47909. */
  47910. var CubeMapToSphericalPolynomialTools = (function () {
  47911. function CubeMapToSphericalPolynomialTools() {
  47912. }
  47913. /**
  47914. * Converts a texture to the according Spherical Polynomial data.
  47915. * This extracts the first 3 orders only as they are the only one used in the lighting.
  47916. *
  47917. * @param texture The texture to extract the information from.
  47918. * @return The Spherical Polynomial data.
  47919. */
  47920. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  47921. if (!texture.isCube) {
  47922. // Only supports cube Textures currently.
  47923. return null;
  47924. }
  47925. var size = texture.getSize().width;
  47926. var right = texture.readPixels(0);
  47927. var left = texture.readPixels(1);
  47928. var up;
  47929. var down;
  47930. if (texture.isRenderTarget) {
  47931. up = texture.readPixels(3);
  47932. down = texture.readPixels(2);
  47933. }
  47934. else {
  47935. up = texture.readPixels(2);
  47936. down = texture.readPixels(3);
  47937. }
  47938. var front = texture.readPixels(4);
  47939. var back = texture.readPixels(5);
  47940. var gammaSpace = texture.gammaSpace;
  47941. // Always read as RGBA.
  47942. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  47943. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47944. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47945. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47946. }
  47947. var cubeInfo = {
  47948. size: size,
  47949. right: right,
  47950. left: left,
  47951. up: up,
  47952. down: down,
  47953. front: front,
  47954. back: back,
  47955. format: format,
  47956. type: type,
  47957. gammaSpace: gammaSpace,
  47958. };
  47959. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  47960. };
  47961. /**
  47962. * Converts a cubemap to the according Spherical Polynomial data.
  47963. * This extracts the first 3 orders only as they are the only one used in the lighting.
  47964. *
  47965. * @param cubeInfo The Cube map to extract the information from.
  47966. * @return The Spherical Polynomial data.
  47967. */
  47968. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  47969. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  47970. var totalSolidAngle = 0.0;
  47971. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  47972. var du = 2.0 / cubeInfo.size;
  47973. var dv = du;
  47974. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  47975. var minUV = du * 0.5 - 1.0;
  47976. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  47977. var fileFace = this.FileFaces[faceIndex];
  47978. var dataArray = cubeInfo[fileFace.name];
  47979. var v = minUV;
  47980. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  47981. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  47982. // Because SP is still linear, so summation is fine in that basis.
  47983. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  47984. for (var y = 0; y < cubeInfo.size; y++) {
  47985. var u = minUV;
  47986. for (var x = 0; x < cubeInfo.size; x++) {
  47987. // World direction (not normalised)
  47988. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  47989. worldDirection.normalize();
  47990. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  47991. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  47992. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  47993. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  47994. // Handle Integer types.
  47995. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47996. r /= 255;
  47997. g /= 255;
  47998. b /= 255;
  47999. }
  48000. // Handle Gamma space textures.
  48001. if (cubeInfo.gammaSpace) {
  48002. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  48003. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  48004. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  48005. }
  48006. var color = new BABYLON.Color3(r, g, b);
  48007. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48008. totalSolidAngle += deltaSolidAngle;
  48009. u += du;
  48010. }
  48011. v += dv;
  48012. }
  48013. }
  48014. // Solid angle for entire sphere is 4*pi
  48015. var sphereSolidAngle = 4.0 * Math.PI;
  48016. // Adjust the solid angle to allow for how many faces we processed.
  48017. var facesProcessed = 6.0;
  48018. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  48019. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  48020. // This is needed because the numerical integration over the cube uses a
  48021. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  48022. // and also to compensate for accumulative error due to float precision in the summation.
  48023. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  48024. sphericalHarmonics.scale(correctionFactor);
  48025. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  48026. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  48027. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  48028. };
  48029. CubeMapToSphericalPolynomialTools.FileFaces = [
  48030. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  48031. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  48032. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  48033. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  48034. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  48035. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  48036. ];
  48037. return CubeMapToSphericalPolynomialTools;
  48038. }());
  48039. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  48040. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48041. })(BABYLON || (BABYLON = {}));
  48042. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  48043. var BABYLON;
  48044. (function (BABYLON) {
  48045. var Internals;
  48046. (function (Internals) {
  48047. /**
  48048. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  48049. */
  48050. var PanoramaToCubeMapTools = (function () {
  48051. function PanoramaToCubeMapTools() {
  48052. }
  48053. /**
  48054. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  48055. *
  48056. * @param float32Array The source data.
  48057. * @param inputWidth The width of the input panorama.
  48058. * @param inputhHeight The height of the input panorama.
  48059. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  48060. * @return The cubemap data
  48061. */
  48062. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  48063. if (!float32Array) {
  48064. throw "ConvertPanoramaToCubemap: input cannot be null";
  48065. }
  48066. if (float32Array.length != inputWidth * inputHeight * 3) {
  48067. throw "ConvertPanoramaToCubemap: input size is wrong";
  48068. }
  48069. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  48070. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  48071. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  48072. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  48073. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  48074. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  48075. return {
  48076. front: textureFront,
  48077. back: textureBack,
  48078. left: textureLeft,
  48079. right: textureRight,
  48080. up: textureUp,
  48081. down: textureDown,
  48082. size: size,
  48083. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  48084. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  48085. gammaSpace: false,
  48086. };
  48087. };
  48088. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  48089. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  48090. var textureArray = new Float32Array(buffer);
  48091. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  48092. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  48093. var dy = 1 / texSize;
  48094. var fy = 0;
  48095. for (var y = 0; y < texSize; y++) {
  48096. var xv1 = faceData[0];
  48097. var xv2 = faceData[2];
  48098. for (var x = 0; x < texSize; x++) {
  48099. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  48100. v.normalize();
  48101. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  48102. // 3 channels per pixels
  48103. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  48104. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  48105. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  48106. xv1 = xv1.add(rotDX1);
  48107. xv2 = xv2.add(rotDX2);
  48108. }
  48109. fy += dy;
  48110. }
  48111. return textureArray;
  48112. };
  48113. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  48114. var theta = Math.atan2(vDir.z, vDir.x);
  48115. var phi = Math.acos(vDir.y);
  48116. while (theta < -Math.PI)
  48117. theta += 2 * Math.PI;
  48118. while (theta > Math.PI)
  48119. theta -= 2 * Math.PI;
  48120. var dx = theta / Math.PI;
  48121. var dy = phi / Math.PI;
  48122. // recenter.
  48123. dx = dx * 0.5 + 0.5;
  48124. var px = Math.round(dx * inputWidth);
  48125. if (px < 0)
  48126. px = 0;
  48127. else if (px >= inputWidth)
  48128. px = inputWidth - 1;
  48129. var py = Math.round(dy * inputHeight);
  48130. if (py < 0)
  48131. py = 0;
  48132. else if (py >= inputHeight)
  48133. py = inputHeight - 1;
  48134. var inputY = (inputHeight - py - 1);
  48135. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  48136. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  48137. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  48138. return {
  48139. r: r,
  48140. g: g,
  48141. b: b
  48142. };
  48143. };
  48144. PanoramaToCubeMapTools.FACE_FRONT = [
  48145. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48146. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48147. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48148. new BABYLON.Vector3(1.0, 1.0, -1.0)
  48149. ];
  48150. PanoramaToCubeMapTools.FACE_BACK = [
  48151. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48152. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48153. new BABYLON.Vector3(1.0, 1.0, 1.0),
  48154. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  48155. ];
  48156. PanoramaToCubeMapTools.FACE_RIGHT = [
  48157. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48158. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48159. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48160. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48161. ];
  48162. PanoramaToCubeMapTools.FACE_LEFT = [
  48163. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48164. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48165. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48166. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  48167. ];
  48168. PanoramaToCubeMapTools.FACE_DOWN = [
  48169. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48170. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48171. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48172. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48173. ];
  48174. PanoramaToCubeMapTools.FACE_UP = [
  48175. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48176. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48177. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48178. new BABYLON.Vector3(1.0, -1.0, -1.0)
  48179. ];
  48180. return PanoramaToCubeMapTools;
  48181. }());
  48182. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  48183. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48184. })(BABYLON || (BABYLON = {}));
  48185. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  48186. var BABYLON;
  48187. (function (BABYLON) {
  48188. var Internals;
  48189. (function (Internals) {
  48190. ;
  48191. /**
  48192. * This groups tools to convert HDR texture to native colors array.
  48193. */
  48194. var HDRTools = (function () {
  48195. function HDRTools() {
  48196. }
  48197. HDRTools.Ldexp = function (mantissa, exponent) {
  48198. if (exponent > 1023) {
  48199. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  48200. }
  48201. if (exponent < -1074) {
  48202. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  48203. }
  48204. return mantissa * Math.pow(2, exponent);
  48205. };
  48206. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  48207. if (exponent > 0) {
  48208. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  48209. float32array[index + 0] = red * exponent;
  48210. float32array[index + 1] = green * exponent;
  48211. float32array[index + 2] = blue * exponent;
  48212. }
  48213. else {
  48214. float32array[index + 0] = 0;
  48215. float32array[index + 1] = 0;
  48216. float32array[index + 2] = 0;
  48217. }
  48218. };
  48219. HDRTools.readStringLine = function (uint8array, startIndex) {
  48220. var line = "";
  48221. var character = "";
  48222. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  48223. character = String.fromCharCode(uint8array[i]);
  48224. if (character == "\n") {
  48225. break;
  48226. }
  48227. line += character;
  48228. }
  48229. return line;
  48230. };
  48231. /**
  48232. * Reads header information from an RGBE texture stored in a native array.
  48233. * More information on this format are available here:
  48234. * https://en.wikipedia.org/wiki/RGBE_image_format
  48235. *
  48236. * @param uint8array The binary file stored in native array.
  48237. * @return The header information.
  48238. */
  48239. HDRTools.RGBE_ReadHeader = function (uint8array) {
  48240. var height = 0;
  48241. var width = 0;
  48242. var line = this.readStringLine(uint8array, 0);
  48243. if (line[0] != '#' || line[1] != '?') {
  48244. throw "Bad HDR Format.";
  48245. }
  48246. var endOfHeader = false;
  48247. var findFormat = false;
  48248. var lineIndex = 0;
  48249. do {
  48250. lineIndex += (line.length + 1);
  48251. line = this.readStringLine(uint8array, lineIndex);
  48252. if (line == "FORMAT=32-bit_rle_rgbe") {
  48253. findFormat = true;
  48254. }
  48255. else if (line.length == 0) {
  48256. endOfHeader = true;
  48257. }
  48258. } while (!endOfHeader);
  48259. if (!findFormat) {
  48260. throw "HDR Bad header format, unsupported FORMAT";
  48261. }
  48262. lineIndex += (line.length + 1);
  48263. line = this.readStringLine(uint8array, lineIndex);
  48264. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  48265. var match = sizeRegexp.exec(line);
  48266. // TODO. Support +Y and -X if needed.
  48267. if (match.length < 3) {
  48268. throw "HDR Bad header format, no size";
  48269. }
  48270. width = parseInt(match[2]);
  48271. height = parseInt(match[1]);
  48272. if (width < 8 || width > 0x7fff) {
  48273. throw "HDR Bad header format, unsupported size";
  48274. }
  48275. lineIndex += (line.length + 1);
  48276. return {
  48277. height: height,
  48278. width: width,
  48279. dataPosition: lineIndex
  48280. };
  48281. };
  48282. /**
  48283. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  48284. * This RGBE texture needs to store the information as a panorama.
  48285. *
  48286. * More information on this format are available here:
  48287. * https://en.wikipedia.org/wiki/RGBE_image_format
  48288. *
  48289. * @param buffer The binary file stored in an array buffer.
  48290. * @param size The expected size of the extracted cubemap.
  48291. * @return The Cube Map information.
  48292. */
  48293. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  48294. var uint8array = new Uint8Array(buffer);
  48295. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  48296. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48297. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  48298. return cubeMapData;
  48299. };
  48300. /**
  48301. * Returns the pixels data extracted from an RGBE texture.
  48302. * This pixels will be stored left to right up to down in the R G B order in one array.
  48303. *
  48304. * More information on this format are available here:
  48305. * https://en.wikipedia.org/wiki/RGBE_image_format
  48306. *
  48307. * @param uint8array The binary file stored in an array buffer.
  48308. * @param hdrInfo The header information of the file.
  48309. * @return The pixels data in RGB right to left up to down order.
  48310. */
  48311. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  48312. // Keep for multi format supports.
  48313. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48314. };
  48315. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  48316. var num_scanlines = hdrInfo.height;
  48317. var scanline_width = hdrInfo.width;
  48318. var a, b, c, d, count;
  48319. var dataIndex = hdrInfo.dataPosition;
  48320. var index = 0, endIndex = 0, i = 0;
  48321. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  48322. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  48323. // 3 channels of 4 bytes per pixel in float.
  48324. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  48325. var resultArray = new Float32Array(resultBuffer);
  48326. // read in each successive scanline
  48327. while (num_scanlines > 0) {
  48328. a = uint8array[dataIndex++];
  48329. b = uint8array[dataIndex++];
  48330. c = uint8array[dataIndex++];
  48331. d = uint8array[dataIndex++];
  48332. if (a != 2 || b != 2 || (c & 0x80)) {
  48333. // this file is not run length encoded
  48334. throw "HDR Bad header format, not RLE";
  48335. }
  48336. if (((c << 8) | d) != scanline_width) {
  48337. throw "HDR Bad header format, wrong scan line width";
  48338. }
  48339. index = 0;
  48340. // read each of the four channels for the scanline into the buffer
  48341. for (i = 0; i < 4; i++) {
  48342. endIndex = (i + 1) * scanline_width;
  48343. while (index < endIndex) {
  48344. a = uint8array[dataIndex++];
  48345. b = uint8array[dataIndex++];
  48346. if (a > 128) {
  48347. // a run of the same value
  48348. count = a - 128;
  48349. if ((count == 0) || (count > endIndex - index)) {
  48350. throw "HDR Bad Format, bad scanline data (run)";
  48351. }
  48352. while (count-- > 0) {
  48353. scanLineArray[index++] = b;
  48354. }
  48355. }
  48356. else {
  48357. // a non-run
  48358. count = a;
  48359. if ((count == 0) || (count > endIndex - index)) {
  48360. throw "HDR Bad Format, bad scanline data (non-run)";
  48361. }
  48362. scanLineArray[index++] = b;
  48363. if (--count > 0) {
  48364. for (var j = 0; j < count; j++) {
  48365. scanLineArray[index++] = uint8array[dataIndex++];
  48366. }
  48367. }
  48368. }
  48369. }
  48370. }
  48371. // now convert data from buffer into floats
  48372. for (i = 0; i < scanline_width; i++) {
  48373. a = scanLineArray[i];
  48374. b = scanLineArray[i + scanline_width];
  48375. c = scanLineArray[i + 2 * scanline_width];
  48376. d = scanLineArray[i + 3 * scanline_width];
  48377. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  48378. }
  48379. num_scanlines--;
  48380. }
  48381. return resultArray;
  48382. };
  48383. return HDRTools;
  48384. }());
  48385. Internals.HDRTools = HDRTools;
  48386. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48387. })(BABYLON || (BABYLON = {}));
  48388. //# sourceMappingURL=babylon.hdr.js.map
  48389. var BABYLON;
  48390. (function (BABYLON) {
  48391. /**
  48392. * This represents a texture coming from an HDR input.
  48393. *
  48394. * The only supported format is currently panorama picture stored in RGBE format.
  48395. * Example of such files can be found on HDRLib: http://hdrlib.com/
  48396. */
  48397. var HDRCubeTexture = (function (_super) {
  48398. __extends(HDRCubeTexture, _super);
  48399. /**
  48400. * Instantiates an HDRTexture from the following parameters.
  48401. *
  48402. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  48403. * @param scene The scene the texture will be used in
  48404. * @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.
  48405. * @param noMipmap Forces to not generate the mipmap if true
  48406. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  48407. * @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)
  48408. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  48409. */
  48410. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  48411. if (noMipmap === void 0) { noMipmap = false; }
  48412. if (generateHarmonics === void 0) { generateHarmonics = true; }
  48413. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  48414. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  48415. if (onLoad === void 0) { onLoad = null; }
  48416. if (onError === void 0) { onError = null; }
  48417. var _this = _super.call(this, scene) || this;
  48418. _this._useInGammaSpace = false;
  48419. _this._generateHarmonics = true;
  48420. _this._isBABYLONPreprocessed = false;
  48421. _this._onLoad = null;
  48422. _this._onError = null;
  48423. /**
  48424. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  48425. */
  48426. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  48427. /**
  48428. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  48429. * This is usefull at run time to apply the good shader.
  48430. */
  48431. _this.isPMREM = false;
  48432. _this._isBlocking = true;
  48433. if (!url) {
  48434. return _this;
  48435. }
  48436. _this.name = url;
  48437. _this.url = url;
  48438. _this.hasAlpha = false;
  48439. _this.isCube = true;
  48440. _this._textureMatrix = BABYLON.Matrix.Identity();
  48441. _this._onLoad = onLoad;
  48442. _this._onError = onError;
  48443. _this.gammaSpace = false;
  48444. if (size) {
  48445. _this._isBABYLONPreprocessed = false;
  48446. _this._noMipmap = noMipmap;
  48447. _this._size = size;
  48448. _this._useInGammaSpace = useInGammaSpace;
  48449. _this._usePMREMGenerator = usePMREMGenerator &&
  48450. scene.getEngine().getCaps().textureLOD &&
  48451. _this.getScene().getEngine().getCaps().textureFloat &&
  48452. !_this._useInGammaSpace;
  48453. }
  48454. else {
  48455. _this._isBABYLONPreprocessed = true;
  48456. _this._noMipmap = false;
  48457. _this._useInGammaSpace = false;
  48458. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  48459. _this.getScene().getEngine().getCaps().textureFloat &&
  48460. !_this._useInGammaSpace;
  48461. }
  48462. _this.isPMREM = _this._usePMREMGenerator;
  48463. _this._texture = _this._getFromCache(url, _this._noMipmap);
  48464. if (!_this._texture) {
  48465. if (!scene.useDelayedTextureLoading) {
  48466. _this.loadTexture();
  48467. }
  48468. else {
  48469. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  48470. }
  48471. }
  48472. return _this;
  48473. }
  48474. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  48475. /**
  48476. * Gets wether or not the texture is blocking during loading.
  48477. */
  48478. get: function () {
  48479. return this._isBlocking;
  48480. },
  48481. /**
  48482. * Sets wether or not the texture is blocking during loading.
  48483. */
  48484. set: function (value) {
  48485. this._isBlocking = value;
  48486. },
  48487. enumerable: true,
  48488. configurable: true
  48489. });
  48490. /**
  48491. * Occurs when the file is a preprocessed .babylon.hdr file.
  48492. */
  48493. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  48494. var _this = this;
  48495. var mipLevels = 0;
  48496. var floatArrayView = null;
  48497. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  48498. var mips = [];
  48499. var startIndex = 30;
  48500. for (var level = 0; level < mipLevels; level++) {
  48501. mips.push([]);
  48502. // Fill each pixel of the mip level.
  48503. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  48504. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48505. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  48506. mips[level].push(faceData);
  48507. startIndex += faceSize;
  48508. }
  48509. }
  48510. return mips;
  48511. } : null;
  48512. var callback = function (buffer) {
  48513. // Create Native Array Views
  48514. var intArrayView = new Int32Array(buffer);
  48515. floatArrayView = new Float32Array(buffer);
  48516. // Fill header.
  48517. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  48518. _this._size = intArrayView[1]; // CubeMap max mip face size.
  48519. // Update Texture Information.
  48520. _this._texture.updateSize(_this._size, _this._size);
  48521. // Fill polynomial information.
  48522. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  48523. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  48524. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  48525. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  48526. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  48527. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  48528. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  48529. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  48530. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  48531. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  48532. _this.sphericalPolynomial = sphericalPolynomial;
  48533. // Fill pixel data.
  48534. mipLevels = intArrayView[29]; // Number of mip levels.
  48535. var startIndex = 30;
  48536. var data = [];
  48537. var faceSize = Math.pow(_this._size, 2) * 3;
  48538. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48539. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  48540. startIndex += faceSize;
  48541. }
  48542. var results = [];
  48543. var byteArray = null;
  48544. // Push each faces.
  48545. for (var k = 0; k < 6; k++) {
  48546. var dataFace = null;
  48547. // To be deprecated.
  48548. if (version === 1) {
  48549. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  48550. dataFace = data[j];
  48551. }
  48552. // If special cases.
  48553. if (!mipmapGenerator) {
  48554. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  48555. // 3 channels of 1 bytes per pixel in bytes.
  48556. var byteBuffer = new ArrayBuffer(faceSize);
  48557. byteArray = new Uint8Array(byteBuffer);
  48558. }
  48559. for (var i = 0; i < _this._size * _this._size; i++) {
  48560. // Put in gamma space if requested.
  48561. if (_this._useInGammaSpace) {
  48562. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48563. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48564. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48565. }
  48566. // Convert to int texture for fallback.
  48567. if (byteArray) {
  48568. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48569. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48570. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48571. // May use luminance instead if the result is not accurate.
  48572. var max = Math.max(Math.max(r, g), b);
  48573. if (max > 255) {
  48574. var scale = 255 / max;
  48575. r *= scale;
  48576. g *= scale;
  48577. b *= scale;
  48578. }
  48579. byteArray[(i * 3) + 0] = r;
  48580. byteArray[(i * 3) + 1] = g;
  48581. byteArray[(i * 3) + 2] = b;
  48582. }
  48583. }
  48584. }
  48585. // Fill the array accordingly.
  48586. if (byteArray) {
  48587. results.push(byteArray);
  48588. }
  48589. else {
  48590. results.push(dataFace);
  48591. }
  48592. }
  48593. return results;
  48594. };
  48595. 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);
  48596. };
  48597. /**
  48598. * Occurs when the file is raw .hdr file.
  48599. */
  48600. HDRCubeTexture.prototype.loadHDRTexture = function () {
  48601. var _this = this;
  48602. var callback = function (buffer) {
  48603. // Extract the raw linear data.
  48604. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  48605. // Generate harmonics if needed.
  48606. if (_this._generateHarmonics) {
  48607. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  48608. _this.sphericalPolynomial = sphericalPolynomial;
  48609. }
  48610. var results = [];
  48611. var byteArray = null;
  48612. // Push each faces.
  48613. for (var j = 0; j < 6; j++) {
  48614. // Create uintarray fallback.
  48615. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  48616. // 3 channels of 1 bytes per pixel in bytes.
  48617. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  48618. byteArray = new Uint8Array(byteBuffer);
  48619. }
  48620. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  48621. // If special cases.
  48622. if (_this._useInGammaSpace || byteArray) {
  48623. for (var i = 0; i < _this._size * _this._size; i++) {
  48624. // Put in gamma space if requested.
  48625. if (_this._useInGammaSpace) {
  48626. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48627. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48628. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48629. }
  48630. // Convert to int texture for fallback.
  48631. if (byteArray) {
  48632. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48633. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48634. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48635. // May use luminance instead if the result is not accurate.
  48636. var max = Math.max(Math.max(r, g), b);
  48637. if (max > 255) {
  48638. var scale = 255 / max;
  48639. r *= scale;
  48640. g *= scale;
  48641. b *= scale;
  48642. }
  48643. byteArray[(i * 3) + 0] = r;
  48644. byteArray[(i * 3) + 1] = g;
  48645. byteArray[(i * 3) + 2] = b;
  48646. }
  48647. }
  48648. }
  48649. if (byteArray) {
  48650. results.push(byteArray);
  48651. }
  48652. else {
  48653. results.push(dataFace);
  48654. }
  48655. }
  48656. return results;
  48657. };
  48658. var mipmapGenerator = null;
  48659. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  48660. // if (!this._noMipmap &&
  48661. // this._usePMREMGenerator) {
  48662. // mipmapGenerator = (data: ArrayBufferView[]) => {
  48663. // // Custom setup of the generator matching with the PBR shader values.
  48664. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  48665. // this._size,
  48666. // this._size,
  48667. // 0,
  48668. // 3,
  48669. // this.getScene().getEngine().getCaps().textureFloat,
  48670. // 2048,
  48671. // 0.25,
  48672. // false,
  48673. // true);
  48674. // return generator.filterCubeMap();
  48675. // };
  48676. // }
  48677. 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);
  48678. };
  48679. /**
  48680. * Starts the loading process of the texture.
  48681. */
  48682. HDRCubeTexture.prototype.loadTexture = function () {
  48683. if (this._isBABYLONPreprocessed) {
  48684. this.loadBabylonTexture();
  48685. }
  48686. else {
  48687. this.loadHDRTexture();
  48688. }
  48689. };
  48690. HDRCubeTexture.prototype.clone = function () {
  48691. var size = this._isBABYLONPreprocessed ? null : this._size;
  48692. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  48693. // Base texture
  48694. newTexture.level = this.level;
  48695. newTexture.wrapU = this.wrapU;
  48696. newTexture.wrapV = this.wrapV;
  48697. newTexture.coordinatesIndex = this.coordinatesIndex;
  48698. newTexture.coordinatesMode = this.coordinatesMode;
  48699. return newTexture;
  48700. };
  48701. // Methods
  48702. HDRCubeTexture.prototype.delayLoad = function () {
  48703. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  48704. return;
  48705. }
  48706. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  48707. this._texture = this._getFromCache(this.url, this._noMipmap);
  48708. if (!this._texture) {
  48709. this.loadTexture();
  48710. }
  48711. };
  48712. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  48713. return this._textureMatrix;
  48714. };
  48715. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  48716. this._textureMatrix = value;
  48717. };
  48718. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  48719. var texture = null;
  48720. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  48721. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  48722. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  48723. texture.name = parsedTexture.name;
  48724. texture.hasAlpha = parsedTexture.hasAlpha;
  48725. texture.level = parsedTexture.level;
  48726. texture.coordinatesMode = parsedTexture.coordinatesMode;
  48727. texture.isBlocking = parsedTexture.isBlocking;
  48728. }
  48729. return texture;
  48730. };
  48731. HDRCubeTexture.prototype.serialize = function () {
  48732. if (!this.name) {
  48733. return null;
  48734. }
  48735. var serializationObject = {};
  48736. serializationObject.name = this.name;
  48737. serializationObject.hasAlpha = this.hasAlpha;
  48738. serializationObject.isCube = true;
  48739. serializationObject.level = this.level;
  48740. serializationObject.size = this._size;
  48741. serializationObject.coordinatesMode = this.coordinatesMode;
  48742. serializationObject.useInGammaSpace = this._useInGammaSpace;
  48743. serializationObject.generateHarmonics = this._generateHarmonics;
  48744. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  48745. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  48746. serializationObject.customType = "BABYLON.HDRCubeTexture";
  48747. serializationObject.noMipmap = this._noMipmap;
  48748. serializationObject.isBlocking = this._isBlocking;
  48749. return serializationObject;
  48750. };
  48751. /**
  48752. * Saves as a file the data contained in the texture in a binary format.
  48753. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  48754. * as the spherical used in the lighting.
  48755. * @param url The HDR file url.
  48756. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  48757. * @param onError Method called if any error happens during download.
  48758. * @return The packed binary data.
  48759. */
  48760. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  48761. if (onError === void 0) { onError = null; }
  48762. var callback = function (buffer) {
  48763. var data = new Blob([buffer], { type: 'application/octet-stream' });
  48764. // Returns a URL you can use as a href.
  48765. var objUrl = window.URL.createObjectURL(data);
  48766. // Simulates a link to it and click to dowload.
  48767. var a = document.createElement("a");
  48768. document.body.appendChild(a);
  48769. a.style.display = "none";
  48770. a.href = objUrl;
  48771. a.download = "envmap.babylon.hdr";
  48772. a.click();
  48773. };
  48774. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  48775. };
  48776. /**
  48777. * Serializes the data contained in the texture in a binary format.
  48778. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  48779. * as the spherical used in the lighting.
  48780. * @param url The HDR file url.
  48781. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  48782. * @param onError Method called if any error happens during download.
  48783. * @return The packed binary data.
  48784. */
  48785. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  48786. if (onError === void 0) { onError = null; }
  48787. // Needs the url tho create the texture.
  48788. if (!url) {
  48789. return null;
  48790. }
  48791. // Check Power of two size.
  48792. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  48793. return null;
  48794. }
  48795. // Coming Back in 3.1.
  48796. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  48797. return null;
  48798. };
  48799. HDRCubeTexture._facesMapping = [
  48800. "right",
  48801. "left",
  48802. "up",
  48803. "down",
  48804. "front",
  48805. "back"
  48806. ];
  48807. return HDRCubeTexture;
  48808. }(BABYLON.BaseTexture));
  48809. BABYLON.HDRCubeTexture = HDRCubeTexture;
  48810. })(BABYLON || (BABYLON = {}));
  48811. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  48812. var BABYLON;
  48813. (function (BABYLON) {
  48814. var DefaultLoadingScreen = (function () {
  48815. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  48816. if (_loadingText === void 0) { _loadingText = ""; }
  48817. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  48818. var _this = this;
  48819. this._renderingCanvas = _renderingCanvas;
  48820. this._loadingText = _loadingText;
  48821. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  48822. // Resize
  48823. this._resizeLoadingUI = function () {
  48824. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  48825. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  48826. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  48827. _this._loadingDiv.style.left = canvasRect.left + "px";
  48828. _this._loadingDiv.style.top = canvasRect.top + "px";
  48829. _this._loadingDiv.style.width = canvasRect.width + "px";
  48830. _this._loadingDiv.style.height = canvasRect.height + "px";
  48831. };
  48832. }
  48833. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  48834. if (this._loadingDiv) {
  48835. // Do not add a loading screen if there is already one
  48836. return;
  48837. }
  48838. this._loadingDiv = document.createElement("div");
  48839. this._loadingDiv.id = "babylonjsLoadingDiv";
  48840. this._loadingDiv.style.opacity = "0";
  48841. this._loadingDiv.style.transition = "opacity 1.5s ease";
  48842. // Loading text
  48843. this._loadingTextDiv = document.createElement("div");
  48844. this._loadingTextDiv.style.position = "absolute";
  48845. this._loadingTextDiv.style.left = "0";
  48846. this._loadingTextDiv.style.top = "50%";
  48847. this._loadingTextDiv.style.marginTop = "80px";
  48848. this._loadingTextDiv.style.width = "100%";
  48849. this._loadingTextDiv.style.height = "20px";
  48850. this._loadingTextDiv.style.fontFamily = "Arial";
  48851. this._loadingTextDiv.style.fontSize = "14px";
  48852. this._loadingTextDiv.style.color = "white";
  48853. this._loadingTextDiv.style.textAlign = "center";
  48854. this._loadingTextDiv.innerHTML = "Loading";
  48855. this._loadingDiv.appendChild(this._loadingTextDiv);
  48856. //set the predefined text
  48857. this._loadingTextDiv.innerHTML = this._loadingText;
  48858. // Generating keyframes
  48859. var style = document.createElement('style');
  48860. style.type = 'text/css';
  48861. 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 }";
  48862. style.innerHTML = keyFrames;
  48863. document.getElementsByTagName('head')[0].appendChild(style);
  48864. // Loading img
  48865. var imgBack = new Image();
  48866. 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";
  48867. imgBack.style.position = "absolute";
  48868. imgBack.style.left = "50%";
  48869. imgBack.style.top = "50%";
  48870. imgBack.style.marginLeft = "-60px";
  48871. imgBack.style.marginTop = "-60px";
  48872. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  48873. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  48874. imgBack.style.transformOrigin = "50% 50%";
  48875. imgBack.style.webkitTransformOrigin = "50% 50%";
  48876. this._loadingDiv.appendChild(imgBack);
  48877. this._resizeLoadingUI();
  48878. window.addEventListener("resize", this._resizeLoadingUI);
  48879. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48880. document.body.appendChild(this._loadingDiv);
  48881. this._loadingDiv.style.opacity = "1";
  48882. };
  48883. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  48884. var _this = this;
  48885. if (!this._loadingDiv) {
  48886. return;
  48887. }
  48888. var onTransitionEnd = function () {
  48889. if (!_this._loadingDiv) {
  48890. return;
  48891. }
  48892. document.body.removeChild(_this._loadingDiv);
  48893. window.removeEventListener("resize", _this._resizeLoadingUI);
  48894. _this._loadingDiv = null;
  48895. };
  48896. this._loadingDiv.style.opacity = "0";
  48897. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  48898. };
  48899. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  48900. set: function (text) {
  48901. this._loadingText = text;
  48902. if (this._loadingTextDiv) {
  48903. this._loadingTextDiv.innerHTML = this._loadingText;
  48904. }
  48905. },
  48906. enumerable: true,
  48907. configurable: true
  48908. });
  48909. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  48910. get: function () {
  48911. return this._loadingDivBackgroundColor;
  48912. },
  48913. set: function (color) {
  48914. this._loadingDivBackgroundColor = color;
  48915. if (!this._loadingDiv) {
  48916. return;
  48917. }
  48918. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48919. },
  48920. enumerable: true,
  48921. configurable: true
  48922. });
  48923. return DefaultLoadingScreen;
  48924. }());
  48925. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  48926. })(BABYLON || (BABYLON = {}));
  48927. //# sourceMappingURL=babylon.loadingScreen.js.map
  48928. var BABYLON;
  48929. (function (BABYLON) {
  48930. var SceneLoader = (function () {
  48931. function SceneLoader() {
  48932. }
  48933. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  48934. get: function () {
  48935. return 0;
  48936. },
  48937. enumerable: true,
  48938. configurable: true
  48939. });
  48940. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  48941. get: function () {
  48942. return 1;
  48943. },
  48944. enumerable: true,
  48945. configurable: true
  48946. });
  48947. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  48948. get: function () {
  48949. return 2;
  48950. },
  48951. enumerable: true,
  48952. configurable: true
  48953. });
  48954. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  48955. get: function () {
  48956. return 3;
  48957. },
  48958. enumerable: true,
  48959. configurable: true
  48960. });
  48961. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  48962. get: function () {
  48963. return SceneLoader._ForceFullSceneLoadingForIncremental;
  48964. },
  48965. set: function (value) {
  48966. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  48967. },
  48968. enumerable: true,
  48969. configurable: true
  48970. });
  48971. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  48972. get: function () {
  48973. return SceneLoader._ShowLoadingScreen;
  48974. },
  48975. set: function (value) {
  48976. SceneLoader._ShowLoadingScreen = value;
  48977. },
  48978. enumerable: true,
  48979. configurable: true
  48980. });
  48981. Object.defineProperty(SceneLoader, "loggingLevel", {
  48982. get: function () {
  48983. return SceneLoader._loggingLevel;
  48984. },
  48985. set: function (value) {
  48986. SceneLoader._loggingLevel = value;
  48987. },
  48988. enumerable: true,
  48989. configurable: true
  48990. });
  48991. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  48992. get: function () {
  48993. return SceneLoader._CleanBoneMatrixWeights;
  48994. },
  48995. set: function (value) {
  48996. SceneLoader._CleanBoneMatrixWeights = value;
  48997. },
  48998. enumerable: true,
  48999. configurable: true
  49000. });
  49001. SceneLoader._getDefaultPlugin = function () {
  49002. return SceneLoader._registeredPlugins[".babylon"];
  49003. };
  49004. SceneLoader._getPluginForExtension = function (extension) {
  49005. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  49006. if (registeredPlugin) {
  49007. return registeredPlugin;
  49008. }
  49009. return SceneLoader._getDefaultPlugin();
  49010. };
  49011. SceneLoader._getPluginForDirectLoad = function (data) {
  49012. for (var extension in SceneLoader._registeredPlugins) {
  49013. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  49014. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  49015. return SceneLoader._registeredPlugins[extension];
  49016. }
  49017. }
  49018. return SceneLoader._getDefaultPlugin();
  49019. };
  49020. SceneLoader._getPluginForFilename = function (sceneFilename) {
  49021. if (sceneFilename.name) {
  49022. sceneFilename = sceneFilename.name;
  49023. }
  49024. var dotPosition = sceneFilename.lastIndexOf(".");
  49025. var queryStringPosition = sceneFilename.indexOf("?");
  49026. if (queryStringPosition === -1) {
  49027. queryStringPosition = sceneFilename.length;
  49028. }
  49029. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  49030. return SceneLoader._getPluginForExtension(extension);
  49031. };
  49032. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  49033. SceneLoader._getDirectLoad = function (sceneFilename) {
  49034. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  49035. return sceneFilename.substr(5);
  49036. }
  49037. return null;
  49038. };
  49039. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49040. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  49041. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  49042. var plugin = registeredPlugin.plugin;
  49043. var useArrayBuffer = registeredPlugin.isBinary;
  49044. var database;
  49045. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  49046. var dataCallback = function (data) {
  49047. if (scene.isDisposed) {
  49048. onError("Scene has been disposed");
  49049. return;
  49050. }
  49051. scene.database = database;
  49052. try {
  49053. onSuccess(plugin, data);
  49054. }
  49055. catch (e) {
  49056. onError(null, e);
  49057. }
  49058. };
  49059. var manifestChecked = function (success) {
  49060. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  49061. onError(request.status + " " + request.statusText);
  49062. });
  49063. };
  49064. if (directLoad) {
  49065. dataCallback(directLoad);
  49066. return;
  49067. }
  49068. if (rootUrl.indexOf("file:") === -1) {
  49069. if (scene.getEngine().enableOfflineSupport) {
  49070. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  49071. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  49072. }
  49073. else {
  49074. manifestChecked(true);
  49075. }
  49076. }
  49077. else {
  49078. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  49079. }
  49080. };
  49081. // Public functions
  49082. SceneLoader.GetPluginForExtension = function (extension) {
  49083. return SceneLoader._getPluginForExtension(extension).plugin;
  49084. };
  49085. SceneLoader.RegisterPlugin = function (plugin) {
  49086. if (typeof plugin.extensions === "string") {
  49087. var extension = plugin.extensions;
  49088. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  49089. plugin: plugin,
  49090. isBinary: false
  49091. };
  49092. }
  49093. else {
  49094. var extensions = plugin.extensions;
  49095. Object.keys(extensions).forEach(function (extension) {
  49096. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  49097. plugin: plugin,
  49098. isBinary: extensions[extension].isBinary
  49099. };
  49100. });
  49101. }
  49102. };
  49103. /**
  49104. * Import meshes into a scene
  49105. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  49106. * @param rootUrl a string that defines the root url for scene and resources
  49107. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49108. * @param scene the instance of BABYLON.Scene to append to
  49109. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  49110. * @param onProgress a callback with a progress event for each file being loaded
  49111. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49112. */
  49113. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49114. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  49115. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  49116. return;
  49117. }
  49118. var loadingToken = {};
  49119. scene._addPendingData(loadingToken);
  49120. var errorHandler = function (message, exception) {
  49121. if (onError) {
  49122. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  49123. }
  49124. scene._removePendingData(loadingToken);
  49125. };
  49126. var progressHandler = function (event) {
  49127. if (onProgress) {
  49128. onProgress(event);
  49129. }
  49130. };
  49131. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  49132. if (plugin.importMesh) {
  49133. var syncedPlugin = plugin;
  49134. var meshes = [];
  49135. var particleSystems = [];
  49136. var skeletons = [];
  49137. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  49138. return;
  49139. }
  49140. if (onSuccess) {
  49141. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  49142. onSuccess(meshes, particleSystems, skeletons);
  49143. scene._removePendingData(loadingToken);
  49144. }
  49145. }
  49146. else {
  49147. var asyncedPlugin = plugin;
  49148. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  49149. if (onSuccess) {
  49150. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  49151. onSuccess(meshes, particleSystems, skeletons);
  49152. scene._removePendingData(loadingToken);
  49153. }
  49154. }, progressHandler, errorHandler);
  49155. }
  49156. }, progressHandler, errorHandler);
  49157. };
  49158. /**
  49159. * Load a scene
  49160. * @param rootUrl a string that defines the root url for scene and resources
  49161. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49162. * @param engine is the instance of BABYLON.Engine to use to create the scene
  49163. * @param onSuccess a callback with the scene when import succeeds
  49164. * @param onProgress a callback with a progress event for each file being loaded
  49165. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49166. */
  49167. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  49168. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  49169. };
  49170. /**
  49171. * Append a scene
  49172. * @param rootUrl a string that defines the root url for scene and resources
  49173. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49174. * @param scene is the instance of BABYLON.Scene to append to
  49175. * @param onSuccess a callback with the scene when import succeeds
  49176. * @param onProgress a callback with a progress event for each file being loaded
  49177. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49178. */
  49179. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49180. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  49181. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  49182. return;
  49183. }
  49184. if (SceneLoader.ShowLoadingScreen) {
  49185. scene.getEngine().displayLoadingUI();
  49186. }
  49187. var loadingToken = {};
  49188. scene._addPendingData(loadingToken);
  49189. var errorHandler = function (message, exception) {
  49190. if (onError) {
  49191. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  49192. }
  49193. scene._removePendingData(loadingToken);
  49194. scene.getEngine().hideLoadingUI();
  49195. };
  49196. var progressHandler = function (event) {
  49197. if (onProgress) {
  49198. onProgress(event);
  49199. }
  49200. };
  49201. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  49202. if (plugin.load) {
  49203. var syncedPlugin = plugin;
  49204. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  49205. return;
  49206. }
  49207. if (onSuccess) {
  49208. onSuccess(scene);
  49209. }
  49210. scene.loadingPluginName = plugin.name;
  49211. scene._removePendingData(loadingToken);
  49212. }
  49213. else {
  49214. var asyncedPlugin = plugin;
  49215. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  49216. if (onSuccess) {
  49217. onSuccess(scene);
  49218. }
  49219. scene.loadingPluginName = plugin.name;
  49220. scene._removePendingData(loadingToken);
  49221. }, progressHandler, errorHandler);
  49222. }
  49223. if (SceneLoader.ShowLoadingScreen) {
  49224. scene.executeWhenReady(function () {
  49225. scene.getEngine().hideLoadingUI();
  49226. });
  49227. }
  49228. }, progressHandler, errorHandler);
  49229. };
  49230. // Flags
  49231. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  49232. SceneLoader._ShowLoadingScreen = true;
  49233. SceneLoader._CleanBoneMatrixWeights = false;
  49234. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  49235. // Members
  49236. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  49237. SceneLoader._registeredPlugins = {};
  49238. return SceneLoader;
  49239. }());
  49240. BABYLON.SceneLoader = SceneLoader;
  49241. ;
  49242. })(BABYLON || (BABYLON = {}));
  49243. //# sourceMappingURL=babylon.sceneLoader.js.map
  49244. var BABYLON;
  49245. (function (BABYLON) {
  49246. var Internals;
  49247. (function (Internals) {
  49248. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  49249. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49250. var parsedMaterial = parsedData.materials[index];
  49251. if (parsedMaterial.id === id) {
  49252. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49253. }
  49254. }
  49255. return null;
  49256. };
  49257. var isDescendantOf = function (mesh, names, hierarchyIds) {
  49258. for (var i in names) {
  49259. if (mesh.name === names[i]) {
  49260. hierarchyIds.push(mesh.id);
  49261. return true;
  49262. }
  49263. }
  49264. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  49265. hierarchyIds.push(mesh.id);
  49266. return true;
  49267. }
  49268. return false;
  49269. };
  49270. var logOperation = function (operation, producer) {
  49271. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  49272. };
  49273. BABYLON.SceneLoader.RegisterPlugin({
  49274. name: "babylon.js",
  49275. extensions: ".babylon",
  49276. canDirectLoad: function (data) {
  49277. if (data.indexOf("babylon") !== -1) {
  49278. return true;
  49279. }
  49280. return false;
  49281. },
  49282. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  49283. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49284. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49285. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49286. // and avoid problems with multiple concurrent .babylon loads.
  49287. var log = "importMesh has failed JSON parse";
  49288. try {
  49289. var parsedData = JSON.parse(data);
  49290. log = "";
  49291. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49292. if (!meshesNames) {
  49293. meshesNames = null;
  49294. }
  49295. else if (!Array.isArray(meshesNames)) {
  49296. meshesNames = [meshesNames];
  49297. }
  49298. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49299. var loadedSkeletonsIds = [];
  49300. var loadedMaterialsIds = [];
  49301. var hierarchyIds = [];
  49302. var index;
  49303. var cache;
  49304. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49305. var parsedMesh = parsedData.meshes[index];
  49306. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  49307. if (meshesNames !== null) {
  49308. // Remove found mesh name from list.
  49309. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  49310. }
  49311. //Geometry?
  49312. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  49313. //does the file contain geometries?
  49314. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  49315. //find the correct geometry and add it to the scene
  49316. var found = false;
  49317. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  49318. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  49319. return;
  49320. }
  49321. else {
  49322. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  49323. if (parsedGeometryData.id === parsedMesh.geometryId) {
  49324. switch (geometryType) {
  49325. case "boxes":
  49326. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  49327. break;
  49328. case "spheres":
  49329. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  49330. break;
  49331. case "cylinders":
  49332. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  49333. break;
  49334. case "toruses":
  49335. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  49336. break;
  49337. case "grounds":
  49338. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  49339. break;
  49340. case "planes":
  49341. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  49342. break;
  49343. case "torusKnots":
  49344. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  49345. break;
  49346. case "vertexData":
  49347. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  49348. break;
  49349. }
  49350. found = true;
  49351. }
  49352. });
  49353. }
  49354. });
  49355. if (found === false) {
  49356. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  49357. }
  49358. }
  49359. }
  49360. // Material ?
  49361. if (parsedMesh.materialId) {
  49362. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  49363. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49364. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  49365. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  49366. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  49367. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  49368. var subMatId = parsedMultiMaterial.materials[matIndex];
  49369. loadedMaterialsIds.push(subMatId);
  49370. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  49371. log += "\n\tMaterial " + mat.toString(fullDetails);
  49372. }
  49373. loadedMaterialsIds.push(parsedMultiMaterial.id);
  49374. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49375. materialFound = true;
  49376. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  49377. break;
  49378. }
  49379. }
  49380. }
  49381. if (materialFound === false) {
  49382. loadedMaterialsIds.push(parsedMesh.materialId);
  49383. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  49384. if (!mat) {
  49385. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  49386. }
  49387. else {
  49388. log += "\n\tMaterial " + mat.toString(fullDetails);
  49389. }
  49390. }
  49391. }
  49392. // Skeleton ?
  49393. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49394. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  49395. if (skeletonAlreadyLoaded === false) {
  49396. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  49397. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  49398. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  49399. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49400. skeletons.push(skeleton);
  49401. loadedSkeletonsIds.push(parsedSkeleton.id);
  49402. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  49403. }
  49404. }
  49405. }
  49406. }
  49407. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49408. meshes.push(mesh);
  49409. log += "\n\tMesh " + mesh.toString(fullDetails);
  49410. }
  49411. }
  49412. // Connecting parents
  49413. var currentMesh;
  49414. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49415. currentMesh = scene.meshes[index];
  49416. if (currentMesh._waitingParentId) {
  49417. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  49418. currentMesh._waitingParentId = undefined;
  49419. }
  49420. }
  49421. // freeze and compute world matrix application
  49422. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49423. currentMesh = scene.meshes[index];
  49424. if (currentMesh._waitingFreezeWorldMatrix) {
  49425. currentMesh.freezeWorldMatrix();
  49426. currentMesh._waitingFreezeWorldMatrix = undefined;
  49427. }
  49428. else {
  49429. currentMesh.computeWorldMatrix(true);
  49430. }
  49431. }
  49432. }
  49433. // Particles
  49434. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49435. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49436. var parsedParticleSystem = parsedData.particleSystems[index];
  49437. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  49438. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  49439. }
  49440. }
  49441. }
  49442. return true;
  49443. }
  49444. catch (err) {
  49445. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  49446. log = null;
  49447. throw err;
  49448. }
  49449. finally {
  49450. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49451. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49452. }
  49453. }
  49454. },
  49455. load: function (scene, data, rootUrl) {
  49456. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49457. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49458. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49459. // and avoid problems with multiple concurrent .babylon loads.
  49460. var log = "importScene has failed JSON parse";
  49461. try {
  49462. var parsedData = JSON.parse(data);
  49463. log = "";
  49464. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49465. // Scene
  49466. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  49467. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  49468. }
  49469. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  49470. scene.autoClear = parsedData.autoClear;
  49471. }
  49472. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  49473. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  49474. }
  49475. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  49476. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  49477. }
  49478. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  49479. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  49480. }
  49481. // Fog
  49482. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  49483. scene.fogMode = parsedData.fogMode;
  49484. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  49485. scene.fogStart = parsedData.fogStart;
  49486. scene.fogEnd = parsedData.fogEnd;
  49487. scene.fogDensity = parsedData.fogDensity;
  49488. log += "\tFog mode for scene: ";
  49489. switch (scene.fogMode) {
  49490. // getters not compiling, so using hardcoded
  49491. case 1:
  49492. log += "exp\n";
  49493. break;
  49494. case 2:
  49495. log += "exp2\n";
  49496. break;
  49497. case 3:
  49498. log += "linear\n";
  49499. break;
  49500. }
  49501. }
  49502. //Physics
  49503. if (parsedData.physicsEnabled) {
  49504. var physicsPlugin;
  49505. if (parsedData.physicsEngine === "cannon") {
  49506. physicsPlugin = new BABYLON.CannonJSPlugin();
  49507. }
  49508. else if (parsedData.physicsEngine === "oimo") {
  49509. physicsPlugin = new BABYLON.OimoJSPlugin();
  49510. }
  49511. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  49512. //else - default engine, which is currently oimo
  49513. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  49514. scene.enablePhysics(physicsGravity, physicsPlugin);
  49515. }
  49516. // Metadata
  49517. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  49518. scene.metadata = parsedData.metadata;
  49519. }
  49520. //collisions, if defined. otherwise, default is true
  49521. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  49522. scene.collisionsEnabled = parsedData.collisionsEnabled;
  49523. }
  49524. scene.workerCollisions = !!parsedData.workerCollisions;
  49525. var index;
  49526. var cache;
  49527. // Lights
  49528. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  49529. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  49530. var parsedLight = parsedData.lights[index];
  49531. var light = BABYLON.Light.Parse(parsedLight, scene);
  49532. log += (index === 0 ? "\n\tLights:" : "");
  49533. log += "\n\t\t" + light.toString(fullDetails);
  49534. }
  49535. }
  49536. // Animations
  49537. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  49538. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  49539. var parsedAnimation = parsedData.animations[index];
  49540. var animation = BABYLON.Animation.Parse(parsedAnimation);
  49541. scene.animations.push(animation);
  49542. log += (index === 0 ? "\n\tAnimations:" : "");
  49543. log += "\n\t\t" + animation.toString(fullDetails);
  49544. }
  49545. }
  49546. if (parsedData.autoAnimate) {
  49547. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  49548. }
  49549. // Materials
  49550. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  49551. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49552. var parsedMaterial = parsedData.materials[index];
  49553. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49554. log += (index === 0 ? "\n\tMaterials:" : "");
  49555. log += "\n\t\t" + mat.toString(fullDetails);
  49556. }
  49557. }
  49558. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49559. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  49560. var parsedMultiMaterial = parsedData.multiMaterials[index];
  49561. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49562. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  49563. log += "\n\t\t" + mmat.toString(fullDetails);
  49564. }
  49565. }
  49566. // Morph targets
  49567. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  49568. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  49569. var managerData = _a[_i];
  49570. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  49571. }
  49572. }
  49573. // Skeletons
  49574. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49575. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  49576. var parsedSkeleton = parsedData.skeletons[index];
  49577. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49578. log += (index === 0 ? "\n\tSkeletons:" : "");
  49579. log += "\n\t\t" + skeleton.toString(fullDetails);
  49580. }
  49581. }
  49582. // Geometries
  49583. var geometries = parsedData.geometries;
  49584. if (geometries !== undefined && geometries !== null) {
  49585. // Boxes
  49586. var boxes = geometries.boxes;
  49587. if (boxes !== undefined && boxes !== null) {
  49588. for (index = 0, cache = boxes.length; index < cache; index++) {
  49589. var parsedBox = boxes[index];
  49590. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  49591. }
  49592. }
  49593. // Spheres
  49594. var spheres = geometries.spheres;
  49595. if (spheres !== undefined && spheres !== null) {
  49596. for (index = 0, cache = spheres.length; index < cache; index++) {
  49597. var parsedSphere = spheres[index];
  49598. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  49599. }
  49600. }
  49601. // Cylinders
  49602. var cylinders = geometries.cylinders;
  49603. if (cylinders !== undefined && cylinders !== null) {
  49604. for (index = 0, cache = cylinders.length; index < cache; index++) {
  49605. var parsedCylinder = cylinders[index];
  49606. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  49607. }
  49608. }
  49609. // Toruses
  49610. var toruses = geometries.toruses;
  49611. if (toruses !== undefined && toruses !== null) {
  49612. for (index = 0, cache = toruses.length; index < cache; index++) {
  49613. var parsedTorus = toruses[index];
  49614. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  49615. }
  49616. }
  49617. // Grounds
  49618. var grounds = geometries.grounds;
  49619. if (grounds !== undefined && grounds !== null) {
  49620. for (index = 0, cache = grounds.length; index < cache; index++) {
  49621. var parsedGround = grounds[index];
  49622. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  49623. }
  49624. }
  49625. // Planes
  49626. var planes = geometries.planes;
  49627. if (planes !== undefined && planes !== null) {
  49628. for (index = 0, cache = planes.length; index < cache; index++) {
  49629. var parsedPlane = planes[index];
  49630. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  49631. }
  49632. }
  49633. // TorusKnots
  49634. var torusKnots = geometries.torusKnots;
  49635. if (torusKnots !== undefined && torusKnots !== null) {
  49636. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  49637. var parsedTorusKnot = torusKnots[index];
  49638. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  49639. }
  49640. }
  49641. // VertexData
  49642. var vertexData = geometries.vertexData;
  49643. if (vertexData !== undefined && vertexData !== null) {
  49644. for (index = 0, cache = vertexData.length; index < cache; index++) {
  49645. var parsedVertexData = vertexData[index];
  49646. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  49647. }
  49648. }
  49649. }
  49650. // Meshes
  49651. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49652. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49653. var parsedMesh = parsedData.meshes[index];
  49654. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49655. log += (index === 0 ? "\n\tMeshes:" : "");
  49656. log += "\n\t\t" + mesh.toString(fullDetails);
  49657. }
  49658. }
  49659. // Cameras
  49660. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  49661. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  49662. var parsedCamera = parsedData.cameras[index];
  49663. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  49664. log += (index === 0 ? "\n\tCameras:" : "");
  49665. log += "\n\t\t" + camera.toString(fullDetails);
  49666. }
  49667. }
  49668. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  49669. scene.setActiveCameraByID(parsedData.activeCameraID);
  49670. }
  49671. // Browsing all the graph to connect the dots
  49672. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  49673. var camera = scene.cameras[index];
  49674. if (camera._waitingParentId) {
  49675. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  49676. camera._waitingParentId = undefined;
  49677. }
  49678. }
  49679. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49680. var light = scene.lights[index];
  49681. if (light._waitingParentId) {
  49682. light.parent = scene.getLastEntryByID(light._waitingParentId);
  49683. light._waitingParentId = undefined;
  49684. }
  49685. }
  49686. // Sounds
  49687. var loadedSounds = [];
  49688. var loadedSound;
  49689. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  49690. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  49691. var parsedSound = parsedData.sounds[index];
  49692. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49693. if (!parsedSound.url)
  49694. parsedSound.url = parsedSound.name;
  49695. if (!loadedSounds[parsedSound.url]) {
  49696. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  49697. loadedSounds[parsedSound.url] = loadedSound;
  49698. }
  49699. else {
  49700. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  49701. }
  49702. }
  49703. else {
  49704. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  49705. }
  49706. }
  49707. }
  49708. loadedSounds = [];
  49709. // Connect parents & children and parse actions
  49710. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49711. var mesh = scene.meshes[index];
  49712. if (mesh._waitingParentId) {
  49713. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  49714. mesh._waitingParentId = undefined;
  49715. }
  49716. if (mesh._waitingActions) {
  49717. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  49718. mesh._waitingActions = undefined;
  49719. }
  49720. }
  49721. // freeze world matrix application
  49722. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49723. var currentMesh = scene.meshes[index];
  49724. if (currentMesh._waitingFreezeWorldMatrix) {
  49725. currentMesh.freezeWorldMatrix();
  49726. currentMesh._waitingFreezeWorldMatrix = undefined;
  49727. }
  49728. else {
  49729. currentMesh.computeWorldMatrix(true);
  49730. }
  49731. }
  49732. // Particles Systems
  49733. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49734. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49735. var parsedParticleSystem = parsedData.particleSystems[index];
  49736. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  49737. }
  49738. }
  49739. // Lens flares
  49740. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  49741. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  49742. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  49743. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  49744. }
  49745. }
  49746. // Shadows
  49747. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  49748. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  49749. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  49750. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  49751. }
  49752. }
  49753. // Lights exclusions / inclusions
  49754. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49755. var light = scene.lights[index];
  49756. // Excluded check
  49757. if (light._excludedMeshesIds.length > 0) {
  49758. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  49759. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  49760. if (excludedMesh) {
  49761. light.excludedMeshes.push(excludedMesh);
  49762. }
  49763. }
  49764. light._excludedMeshesIds = [];
  49765. }
  49766. // Included check
  49767. if (light._includedOnlyMeshesIds.length > 0) {
  49768. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  49769. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  49770. if (includedOnlyMesh) {
  49771. light.includedOnlyMeshes.push(includedOnlyMesh);
  49772. }
  49773. }
  49774. light._includedOnlyMeshesIds = [];
  49775. }
  49776. }
  49777. // Actions (scene)
  49778. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  49779. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  49780. }
  49781. // Finish
  49782. return true;
  49783. }
  49784. catch (err) {
  49785. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  49786. log = null;
  49787. throw err;
  49788. }
  49789. finally {
  49790. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49791. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49792. }
  49793. }
  49794. }
  49795. });
  49796. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49797. })(BABYLON || (BABYLON = {}));
  49798. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  49799. var BABYLON;
  49800. (function (BABYLON) {
  49801. var FilesInput = (function () {
  49802. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  49803. this._engine = engine;
  49804. this._currentScene = scene;
  49805. this._sceneLoadedCallback = sceneLoadedCallback;
  49806. this._progressCallback = progressCallback;
  49807. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  49808. this._textureLoadingCallback = textureLoadingCallback;
  49809. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  49810. this._onReloadCallback = onReloadCallback;
  49811. }
  49812. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  49813. var _this = this;
  49814. if (elementToMonitor) {
  49815. this._elementToMonitor = elementToMonitor;
  49816. this._dragEnterHandler = function (e) { _this.drag(e); };
  49817. this._dragOverHandler = function (e) { _this.drag(e); };
  49818. this._dropHandler = function (e) { _this.drop(e); };
  49819. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  49820. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  49821. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  49822. }
  49823. };
  49824. FilesInput.prototype.dispose = function () {
  49825. if (!this._elementToMonitor) {
  49826. return;
  49827. }
  49828. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  49829. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  49830. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  49831. };
  49832. FilesInput.prototype.renderFunction = function () {
  49833. if (this._additionalRenderLoopLogicCallback) {
  49834. this._additionalRenderLoopLogicCallback();
  49835. }
  49836. if (this._currentScene) {
  49837. if (this._textureLoadingCallback) {
  49838. var remaining = this._currentScene.getWaitingItemsCount();
  49839. if (remaining > 0) {
  49840. this._textureLoadingCallback(remaining);
  49841. }
  49842. }
  49843. this._currentScene.render();
  49844. }
  49845. };
  49846. FilesInput.prototype.drag = function (e) {
  49847. e.stopPropagation();
  49848. e.preventDefault();
  49849. };
  49850. FilesInput.prototype.drop = function (eventDrop) {
  49851. eventDrop.stopPropagation();
  49852. eventDrop.preventDefault();
  49853. this.loadFiles(eventDrop);
  49854. };
  49855. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  49856. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  49857. reader.readEntries(function (fileEntries) {
  49858. var remaining = fileEntries.length;
  49859. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  49860. var fileEntry = fileEntries_1[_i];
  49861. if (fileEntry.isFile) {
  49862. fileEntry.file(function (file) {
  49863. file.correctName = relativePath + file.name;
  49864. files.push(file);
  49865. remaining--;
  49866. if (remaining === 0) {
  49867. callback();
  49868. }
  49869. });
  49870. }
  49871. else {
  49872. remaining--;
  49873. if (remaining === 0) {
  49874. callback();
  49875. }
  49876. }
  49877. }
  49878. });
  49879. };
  49880. FilesInput.prototype._processFiles = function (files) {
  49881. for (var i = 0; i < files.length; i++) {
  49882. var name = files[i].correctName.toLowerCase();
  49883. var extension = name.split('.').pop();
  49884. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  49885. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  49886. this._sceneFileToLoad = files[i];
  49887. }
  49888. else {
  49889. FilesInput.FilesToLoad[name] = files[i];
  49890. }
  49891. }
  49892. if (this._onReloadCallback) {
  49893. this._onReloadCallback(this._sceneFileToLoad);
  49894. }
  49895. else {
  49896. this.reload();
  49897. }
  49898. };
  49899. FilesInput.prototype.loadFiles = function (event) {
  49900. var _this = this;
  49901. if (this._startingProcessingFilesCallback)
  49902. this._startingProcessingFilesCallback();
  49903. // Handling data transfer via drag'n'drop
  49904. if (event && event.dataTransfer && event.dataTransfer.files) {
  49905. this._filesToLoad = event.dataTransfer.files;
  49906. }
  49907. // Handling files from input files
  49908. if (event && event.target && event.target.files) {
  49909. this._filesToLoad = event.target.files;
  49910. }
  49911. if (this._filesToLoad && this._filesToLoad.length > 0) {
  49912. var files_1 = [];
  49913. var folders = [];
  49914. var items = event.dataTransfer ? event.dataTransfer.items : null;
  49915. for (var i = 0; i < this._filesToLoad.length; i++) {
  49916. var fileToLoad = this._filesToLoad[i];
  49917. var name_1 = fileToLoad.name.toLowerCase();
  49918. var type = fileToLoad.type;
  49919. var entry = void 0;
  49920. fileToLoad.correctName = name_1;
  49921. if (items) {
  49922. var item = items[i];
  49923. if (item.getAsEntry) {
  49924. entry = item.getAsEntry();
  49925. }
  49926. else if (item.webkitGetAsEntry) {
  49927. entry = item.webkitGetAsEntry();
  49928. }
  49929. }
  49930. if (!entry) {
  49931. files_1.push(fileToLoad);
  49932. }
  49933. else {
  49934. if (entry.isDirectory) {
  49935. folders.push(entry);
  49936. }
  49937. else {
  49938. files_1.push(fileToLoad);
  49939. }
  49940. }
  49941. }
  49942. if (folders.length === 0) {
  49943. this._processFiles(files_1);
  49944. }
  49945. else {
  49946. var remaining = folders.length;
  49947. // Extract folder content
  49948. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  49949. var folder = folders_1[_i];
  49950. this._handleFolderDrop(folder, files_1, function () {
  49951. remaining--;
  49952. if (remaining === 0) {
  49953. _this._processFiles(files_1);
  49954. }
  49955. });
  49956. }
  49957. }
  49958. }
  49959. };
  49960. FilesInput.prototype.reload = function () {
  49961. var _this = this;
  49962. // If a ".babylon" file has been provided
  49963. if (this._sceneFileToLoad) {
  49964. if (this._currentScene) {
  49965. if (BABYLON.Tools.errorsCount > 0) {
  49966. BABYLON.Tools.ClearLogCache();
  49967. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  49968. }
  49969. this._engine.stopRenderLoop();
  49970. this._currentScene.dispose();
  49971. }
  49972. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  49973. _this._currentScene = newScene;
  49974. if (_this._sceneLoadedCallback) {
  49975. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  49976. }
  49977. // Wait for textures and shaders to be ready
  49978. _this._currentScene.executeWhenReady(function () {
  49979. _this._engine.runRenderLoop(function () {
  49980. _this.renderFunction();
  49981. });
  49982. });
  49983. }, function (progress) {
  49984. if (_this._progressCallback) {
  49985. _this._progressCallback(progress);
  49986. }
  49987. });
  49988. }
  49989. else {
  49990. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  49991. }
  49992. };
  49993. FilesInput.FilesToLoad = new Array();
  49994. return FilesInput;
  49995. }());
  49996. BABYLON.FilesInput = FilesInput;
  49997. })(BABYLON || (BABYLON = {}));
  49998. //# sourceMappingURL=babylon.filesInput.js.map
  49999. var BABYLON;
  50000. (function (BABYLON) {
  50001. var FramingBehavior = (function () {
  50002. function FramingBehavior() {
  50003. this._mode = FramingBehavior.FitFrustumSidesMode;
  50004. this._radiusScale = 1.0;
  50005. this._positionScale = 0.5;
  50006. this._defaultElevation = 0.3;
  50007. this._elevationReturnTime = 1500;
  50008. this._elevationReturnWaitTime = 1000;
  50009. this._zoomStopsAnimation = false;
  50010. this._framingTime = 1500;
  50011. this._isPointerDown = false;
  50012. this._lastFrameTime = null;
  50013. this._lastInteractionTime = -Infinity;
  50014. // Framing control
  50015. this._animatables = new Array();
  50016. this._betaIsAnimating = false;
  50017. this._lastFrameRadius = 0;
  50018. }
  50019. Object.defineProperty(FramingBehavior.prototype, "name", {
  50020. get: function () {
  50021. return "Framing";
  50022. },
  50023. enumerable: true,
  50024. configurable: true
  50025. });
  50026. Object.defineProperty(FramingBehavior.prototype, "mode", {
  50027. /**
  50028. * Gets current mode used by the behavior.
  50029. */
  50030. get: function () {
  50031. return this._mode;
  50032. },
  50033. /**
  50034. * Sets the current mode used by the behavior
  50035. */
  50036. set: function (mode) {
  50037. this._mode = mode;
  50038. },
  50039. enumerable: true,
  50040. configurable: true
  50041. });
  50042. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  50043. /**
  50044. * Gets the scale applied to the radius
  50045. */
  50046. get: function () {
  50047. return this._radiusScale;
  50048. },
  50049. /**
  50050. * Sets the scale applied to the radius (1 by default)
  50051. */
  50052. set: function (radius) {
  50053. this._radiusScale = radius;
  50054. },
  50055. enumerable: true,
  50056. configurable: true
  50057. });
  50058. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  50059. /**
  50060. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  50061. */
  50062. get: function () {
  50063. return this._positionScale;
  50064. },
  50065. /**
  50066. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  50067. */
  50068. set: function (scale) {
  50069. this._positionScale = scale;
  50070. },
  50071. enumerable: true,
  50072. configurable: true
  50073. });
  50074. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  50075. /**
  50076. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  50077. * behaviour is triggered, in radians.
  50078. */
  50079. get: function () {
  50080. return this._defaultElevation;
  50081. },
  50082. /**
  50083. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  50084. * behaviour is triggered, in radians.
  50085. */
  50086. set: function (elevation) {
  50087. this._defaultElevation = elevation;
  50088. },
  50089. enumerable: true,
  50090. configurable: true
  50091. });
  50092. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  50093. /**
  50094. * Gets the time (in milliseconds) taken to return to the default beta position.
  50095. * Negative value indicates camera should not return to default.
  50096. */
  50097. get: function () {
  50098. return this._elevationReturnTime;
  50099. },
  50100. /**
  50101. * Sets the time (in milliseconds) taken to return to the default beta position.
  50102. * Negative value indicates camera should not return to default.
  50103. */
  50104. set: function (speed) {
  50105. this._elevationReturnTime = speed;
  50106. },
  50107. enumerable: true,
  50108. configurable: true
  50109. });
  50110. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  50111. /**
  50112. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  50113. */
  50114. get: function () {
  50115. return this._elevationReturnWaitTime;
  50116. },
  50117. /**
  50118. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  50119. */
  50120. set: function (time) {
  50121. this._elevationReturnWaitTime = time;
  50122. },
  50123. enumerable: true,
  50124. configurable: true
  50125. });
  50126. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  50127. /**
  50128. * Gets the flag that indicates if user zooming should stop animation.
  50129. */
  50130. get: function () {
  50131. return this._zoomStopsAnimation;
  50132. },
  50133. /**
  50134. * Sets the flag that indicates if user zooming should stop animation.
  50135. */
  50136. set: function (flag) {
  50137. this._zoomStopsAnimation = flag;
  50138. },
  50139. enumerable: true,
  50140. configurable: true
  50141. });
  50142. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  50143. /**
  50144. * Gets the transition time when framing the mesh, in milliseconds
  50145. */
  50146. get: function () {
  50147. return this._framingTime;
  50148. },
  50149. /**
  50150. * Sets the transition time when framing the mesh, in milliseconds
  50151. */
  50152. set: function (time) {
  50153. this._framingTime = time;
  50154. },
  50155. enumerable: true,
  50156. configurable: true
  50157. });
  50158. FramingBehavior.prototype.attach = function (camera) {
  50159. var _this = this;
  50160. this._attachedCamera = camera;
  50161. var scene = this._attachedCamera.getScene();
  50162. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  50163. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  50164. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50165. _this._isPointerDown = true;
  50166. return;
  50167. }
  50168. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  50169. _this._isPointerDown = false;
  50170. }
  50171. });
  50172. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  50173. if (mesh) {
  50174. _this.zoomOnMesh(mesh);
  50175. }
  50176. });
  50177. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50178. // Stop the animation if there is user interaction and the animation should stop for this interaction
  50179. _this._applyUserInteraction();
  50180. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  50181. // back to the default position after a given timeout
  50182. _this._maintainCameraAboveGround();
  50183. });
  50184. };
  50185. FramingBehavior.prototype.detach = function () {
  50186. var scene = this._attachedCamera.getScene();
  50187. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  50188. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50189. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50190. this._attachedCamera = null;
  50191. };
  50192. /**
  50193. * Targets the given mesh and updates zoom level accordingly.
  50194. * @param mesh The mesh to target.
  50195. * @param radius Optional. If a cached radius position already exists, overrides default.
  50196. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  50197. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  50198. */
  50199. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ) {
  50200. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  50201. mesh.computeWorldMatrix(true);
  50202. var boundingBox = mesh.getBoundingInfo().boundingBox;
  50203. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ);
  50204. };
  50205. /**
  50206. * Targets the given mesh and updates zoom level accordingly.
  50207. * @param mesh The mesh to target.
  50208. * @param radius Optional. If a cached radius position already exists, overrides default.
  50209. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  50210. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  50211. */
  50212. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ) {
  50213. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  50214. var zoomTarget;
  50215. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  50216. var bottom = minimumWorld.y;
  50217. var top = maximumWorld.y;
  50218. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  50219. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  50220. if (focusOnOriginXZ) {
  50221. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  50222. }
  50223. else {
  50224. var centerWorld = minimumWorld.add(radiusWorld);
  50225. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  50226. }
  50227. if (!this._vectorTransition) {
  50228. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  50229. }
  50230. this._betaIsAnimating = true;
  50231. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  50232. // sets the radius and lower radius bounds
  50233. // Small delta ensures camera is not always at lower zoom limit.
  50234. var delta = 0.1;
  50235. var radius = 0;
  50236. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  50237. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  50238. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  50239. radius = position;
  50240. }
  50241. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  50242. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  50243. if (this._attachedCamera.lowerRadiusLimit === null) {
  50244. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  50245. }
  50246. }
  50247. // transition to new radius
  50248. if (!this._radiusTransition) {
  50249. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  50250. }
  50251. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime));
  50252. };
  50253. /**
  50254. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  50255. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  50256. * frustum width.
  50257. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  50258. * to fully enclose the mesh in the viewing frustum.
  50259. */
  50260. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  50261. var size = maximumWorld.subtract(minimumWorld);
  50262. var boxVectorGlobalDiagonal = size.length();
  50263. var frustumSlope = this._getFrustumSlope();
  50264. // Formula for setting distance
  50265. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  50266. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  50267. // Horizon distance
  50268. var radius = radiusWithoutFraming * this._radiusScale;
  50269. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  50270. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  50271. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  50272. var camera = this._attachedCamera;
  50273. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  50274. // Don't exceed the requested limit
  50275. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  50276. }
  50277. // Don't exceed the upper radius limit
  50278. if (camera.upperRadiusLimit) {
  50279. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  50280. }
  50281. return distance;
  50282. };
  50283. /**
  50284. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  50285. * is automatically returned to its default position (expected to be above ground plane).
  50286. */
  50287. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  50288. var _this = this;
  50289. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  50290. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  50291. var limitBeta = Math.PI * 0.5;
  50292. // Bring the camera back up if below the ground plane
  50293. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  50294. this._betaIsAnimating = true;
  50295. //Transition to new position
  50296. this.stopAllAnimations();
  50297. if (!this._betaTransition) {
  50298. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  50299. }
  50300. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  50301. _this._clearAnimationLocks();
  50302. _this.stopAllAnimations();
  50303. }));
  50304. }
  50305. };
  50306. /**
  50307. * Returns the frustum slope based on the canvas ratio and camera FOV
  50308. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  50309. */
  50310. FramingBehavior.prototype._getFrustumSlope = function () {
  50311. // Calculate the viewport ratio
  50312. // Aspect Ratio is Height/Width.
  50313. var camera = this._attachedCamera;
  50314. var engine = camera.getScene().getEngine();
  50315. var aspectRatio = engine.getAspectRatio(camera);
  50316. // Camera FOV is the vertical field of view (top-bottom) in radians.
  50317. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  50318. var frustumSlopeY = Math.tan(camera.fov / 2);
  50319. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  50320. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  50321. // along the forward vector.
  50322. var frustumSlopeX = frustumSlopeY * aspectRatio;
  50323. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  50324. };
  50325. /**
  50326. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  50327. */
  50328. FramingBehavior.prototype._clearAnimationLocks = function () {
  50329. this._betaIsAnimating = false;
  50330. };
  50331. /**
  50332. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  50333. */
  50334. FramingBehavior.prototype._applyUserInteraction = function () {
  50335. if (this.isUserIsMoving) {
  50336. this._lastInteractionTime = BABYLON.Tools.Now;
  50337. this.stopAllAnimations();
  50338. this._clearAnimationLocks();
  50339. }
  50340. };
  50341. /**
  50342. * Stops and removes all animations that have been applied to the camera
  50343. */
  50344. FramingBehavior.prototype.stopAllAnimations = function () {
  50345. this._attachedCamera.animations = [];
  50346. while (this._animatables.length) {
  50347. if (this._animatables[0]) {
  50348. this._animatables[0].onAnimationEnd = null;
  50349. this._animatables[0].stop();
  50350. }
  50351. this._animatables.shift();
  50352. }
  50353. };
  50354. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  50355. /**
  50356. * Gets a value indicating if the user is moving the camera
  50357. */
  50358. get: function () {
  50359. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  50360. this._attachedCamera.inertialBetaOffset !== 0 ||
  50361. this._attachedCamera.inertialRadiusOffset !== 0 ||
  50362. this._attachedCamera.inertialPanningX !== 0 ||
  50363. this._attachedCamera.inertialPanningY !== 0 ||
  50364. this._isPointerDown;
  50365. },
  50366. enumerable: true,
  50367. configurable: true
  50368. });
  50369. /**
  50370. * The easing function used by animations
  50371. */
  50372. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  50373. /**
  50374. * The easing mode used by animations
  50375. */
  50376. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  50377. // Statics
  50378. /**
  50379. * The camera can move all the way towards the mesh.
  50380. */
  50381. FramingBehavior.IgnoreBoundsSizeMode = 0;
  50382. /**
  50383. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  50384. */
  50385. FramingBehavior.FitFrustumSidesMode = 1;
  50386. return FramingBehavior;
  50387. }());
  50388. BABYLON.FramingBehavior = FramingBehavior;
  50389. })(BABYLON || (BABYLON = {}));
  50390. //# sourceMappingURL=babylon.framingBehavior.js.map
  50391. var BABYLON;
  50392. (function (BABYLON) {
  50393. /**
  50394. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  50395. */
  50396. var BouncingBehavior = (function () {
  50397. function BouncingBehavior() {
  50398. /**
  50399. * The duration of the animation, in milliseconds
  50400. */
  50401. this.transitionDuration = 450;
  50402. /**
  50403. * Length of the distance animated by the transition when lower radius is reached
  50404. */
  50405. this.lowerRadiusTransitionRange = 2;
  50406. /**
  50407. * Length of the distance animated by the transition when upper radius is reached
  50408. */
  50409. this.upperRadiusTransitionRange = -2;
  50410. this._autoTransitionRange = false;
  50411. // Animations
  50412. this._radiusIsAnimating = false;
  50413. this._radiusBounceTransition = null;
  50414. this._animatables = new Array();
  50415. }
  50416. Object.defineProperty(BouncingBehavior.prototype, "name", {
  50417. get: function () {
  50418. return "Bouncing";
  50419. },
  50420. enumerable: true,
  50421. configurable: true
  50422. });
  50423. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  50424. /**
  50425. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  50426. */
  50427. get: function () {
  50428. return this._autoTransitionRange;
  50429. },
  50430. /**
  50431. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  50432. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  50433. */
  50434. set: function (value) {
  50435. var _this = this;
  50436. if (this._autoTransitionRange === value) {
  50437. return;
  50438. }
  50439. this._autoTransitionRange = value;
  50440. var camera = this._attachedCamera;
  50441. if (value) {
  50442. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  50443. if (!mesh) {
  50444. return;
  50445. }
  50446. mesh.computeWorldMatrix(true);
  50447. var diagonal = mesh.getBoundingInfo().diagonalLength;
  50448. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  50449. _this.upperRadiusTransitionRange = diagonal * 0.05;
  50450. });
  50451. }
  50452. else if (this._onMeshTargetChangedObserver) {
  50453. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50454. }
  50455. },
  50456. enumerable: true,
  50457. configurable: true
  50458. });
  50459. BouncingBehavior.prototype.attach = function (camera) {
  50460. var _this = this;
  50461. this._attachedCamera = camera;
  50462. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50463. // Add the bounce animation to the lower radius limit
  50464. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  50465. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  50466. }
  50467. // Add the bounce animation to the upper radius limit
  50468. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  50469. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  50470. }
  50471. });
  50472. };
  50473. BouncingBehavior.prototype.detach = function () {
  50474. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50475. if (this._onMeshTargetChangedObserver) {
  50476. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50477. }
  50478. this._attachedCamera = null;
  50479. };
  50480. /**
  50481. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  50482. * @param radiusLimit The limit to check against.
  50483. * @return Bool to indicate if at limit.
  50484. */
  50485. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  50486. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  50487. return true;
  50488. }
  50489. return false;
  50490. };
  50491. /**
  50492. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  50493. * @param radiusDelta The delta by which to animate to. Can be negative.
  50494. */
  50495. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  50496. var _this = this;
  50497. if (!this._radiusBounceTransition) {
  50498. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  50499. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  50500. }
  50501. // Prevent zoom until bounce has completed
  50502. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  50503. this._attachedCamera.wheelPrecision = Infinity;
  50504. this._attachedCamera.inertialRadiusOffset = 0;
  50505. // Animate to the radius limit
  50506. this.stopAllAnimations();
  50507. this._radiusIsAnimating = true;
  50508. 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(); }));
  50509. };
  50510. /**
  50511. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  50512. */
  50513. BouncingBehavior.prototype._clearAnimationLocks = function () {
  50514. this._radiusIsAnimating = false;
  50515. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  50516. };
  50517. /**
  50518. * Stops and removes all animations that have been applied to the camera
  50519. */
  50520. BouncingBehavior.prototype.stopAllAnimations = function () {
  50521. this._attachedCamera.animations = [];
  50522. while (this._animatables.length) {
  50523. this._animatables[0].onAnimationEnd = null;
  50524. this._animatables[0].stop();
  50525. this._animatables.shift();
  50526. }
  50527. };
  50528. /**
  50529. * The easing function used by animations
  50530. */
  50531. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  50532. /**
  50533. * The easing mode used by animations
  50534. */
  50535. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  50536. return BouncingBehavior;
  50537. }());
  50538. BABYLON.BouncingBehavior = BouncingBehavior;
  50539. })(BABYLON || (BABYLON = {}));
  50540. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  50541. var BABYLON;
  50542. (function (BABYLON) {
  50543. var AutoRotationBehavior = (function () {
  50544. function AutoRotationBehavior() {
  50545. this._zoomStopsAnimation = false;
  50546. this._idleRotationSpeed = 0.05;
  50547. this._idleRotationWaitTime = 2000;
  50548. this._idleRotationSpinupTime = 2000;
  50549. this._isPointerDown = false;
  50550. this._lastFrameTime = null;
  50551. this._lastInteractionTime = -Infinity;
  50552. this._cameraRotationSpeed = 0;
  50553. this._lastFrameRadius = 0;
  50554. }
  50555. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  50556. get: function () {
  50557. return "AutoRotation";
  50558. },
  50559. enumerable: true,
  50560. configurable: true
  50561. });
  50562. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  50563. /**
  50564. * Gets the flag that indicates if user zooming should stop animation.
  50565. */
  50566. get: function () {
  50567. return this._zoomStopsAnimation;
  50568. },
  50569. /**
  50570. * Sets the flag that indicates if user zooming should stop animation.
  50571. */
  50572. set: function (flag) {
  50573. this._zoomStopsAnimation = flag;
  50574. },
  50575. enumerable: true,
  50576. configurable: true
  50577. });
  50578. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  50579. /**
  50580. * Gets the default speed at which the camera rotates around the model.
  50581. */
  50582. get: function () {
  50583. return this._idleRotationSpeed;
  50584. },
  50585. /**
  50586. * Sets the default speed at which the camera rotates around the model.
  50587. */
  50588. set: function (speed) {
  50589. this._idleRotationSpeed = speed;
  50590. },
  50591. enumerable: true,
  50592. configurable: true
  50593. });
  50594. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  50595. /**
  50596. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  50597. */
  50598. get: function () {
  50599. return this._idleRotationWaitTime;
  50600. },
  50601. /**
  50602. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  50603. */
  50604. set: function (time) {
  50605. this._idleRotationWaitTime = time;
  50606. },
  50607. enumerable: true,
  50608. configurable: true
  50609. });
  50610. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  50611. /**
  50612. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50613. */
  50614. get: function () {
  50615. return this._idleRotationSpinupTime;
  50616. },
  50617. /**
  50618. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50619. */
  50620. set: function (time) {
  50621. this._idleRotationSpinupTime = time;
  50622. },
  50623. enumerable: true,
  50624. configurable: true
  50625. });
  50626. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  50627. /**
  50628. * Gets a value indicating if the camera is currently rotating because of this behavior
  50629. */
  50630. get: function () {
  50631. return Math.abs(this._cameraRotationSpeed) > 0;
  50632. },
  50633. enumerable: true,
  50634. configurable: true
  50635. });
  50636. AutoRotationBehavior.prototype.attach = function (camera) {
  50637. var _this = this;
  50638. this._attachedCamera = camera;
  50639. var scene = this._attachedCamera.getScene();
  50640. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  50641. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50642. _this._isPointerDown = true;
  50643. return;
  50644. }
  50645. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  50646. _this._isPointerDown = false;
  50647. }
  50648. });
  50649. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50650. var now = BABYLON.Tools.Now;
  50651. var dt = 0;
  50652. if (_this._lastFrameTime != null) {
  50653. dt = now - _this._lastFrameTime;
  50654. }
  50655. _this._lastFrameTime = now;
  50656. // Stop the animation if there is user interaction and the animation should stop for this interaction
  50657. _this._applyUserInteraction();
  50658. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  50659. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  50660. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  50661. // Step camera rotation by rotation speed
  50662. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  50663. });
  50664. };
  50665. AutoRotationBehavior.prototype.detach = function () {
  50666. var scene = this._attachedCamera.getScene();
  50667. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  50668. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50669. this._attachedCamera = null;
  50670. };
  50671. /**
  50672. * Returns true if user is scrolling.
  50673. * @return true if user is scrolling.
  50674. */
  50675. AutoRotationBehavior.prototype._userIsZooming = function () {
  50676. return this._attachedCamera.inertialRadiusOffset !== 0;
  50677. };
  50678. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  50679. var zoomHasHitLimit = false;
  50680. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  50681. zoomHasHitLimit = true;
  50682. }
  50683. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  50684. this._lastFrameRadius = this._attachedCamera.radius;
  50685. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  50686. };
  50687. /**
  50688. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  50689. */
  50690. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  50691. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  50692. this._lastInteractionTime = BABYLON.Tools.Now;
  50693. }
  50694. };
  50695. // Tools
  50696. AutoRotationBehavior.prototype._userIsMoving = function () {
  50697. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  50698. this._attachedCamera.inertialBetaOffset !== 0 ||
  50699. this._attachedCamera.inertialRadiusOffset !== 0 ||
  50700. this._attachedCamera.inertialPanningX !== 0 ||
  50701. this._attachedCamera.inertialPanningY !== 0 ||
  50702. this._isPointerDown;
  50703. };
  50704. return AutoRotationBehavior;
  50705. }());
  50706. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  50707. })(BABYLON || (BABYLON = {}));
  50708. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  50709. var BABYLON;
  50710. (function (BABYLON) {
  50711. var MorphTarget = (function () {
  50712. function MorphTarget(name, influence) {
  50713. if (influence === void 0) { influence = 0; }
  50714. this.name = name;
  50715. this.animations = new Array();
  50716. this.onInfluenceChanged = new BABYLON.Observable();
  50717. this.influence = influence;
  50718. }
  50719. Object.defineProperty(MorphTarget.prototype, "influence", {
  50720. get: function () {
  50721. return this._influence;
  50722. },
  50723. set: function (influence) {
  50724. if (this._influence === influence) {
  50725. return;
  50726. }
  50727. var previous = this._influence;
  50728. this._influence = influence;
  50729. if (this.onInfluenceChanged.hasObservers) {
  50730. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  50731. }
  50732. },
  50733. enumerable: true,
  50734. configurable: true
  50735. });
  50736. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  50737. get: function () {
  50738. return this._normals !== undefined;
  50739. },
  50740. enumerable: true,
  50741. configurable: true
  50742. });
  50743. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  50744. get: function () {
  50745. return this._tangents !== undefined;
  50746. },
  50747. enumerable: true,
  50748. configurable: true
  50749. });
  50750. MorphTarget.prototype.setPositions = function (data) {
  50751. this._positions = new Float32Array(data);
  50752. };
  50753. MorphTarget.prototype.getPositions = function () {
  50754. return this._positions;
  50755. };
  50756. MorphTarget.prototype.setNormals = function (data) {
  50757. this._normals = new Float32Array(data);
  50758. };
  50759. MorphTarget.prototype.getNormals = function () {
  50760. return this._normals;
  50761. };
  50762. MorphTarget.prototype.setTangents = function (data) {
  50763. this._tangents = new Float32Array(data);
  50764. };
  50765. MorphTarget.prototype.getTangents = function () {
  50766. return this._tangents;
  50767. };
  50768. /**
  50769. * Serializes the current target into a Serialization object.
  50770. * Returns the serialized object.
  50771. */
  50772. MorphTarget.prototype.serialize = function () {
  50773. var serializationObject = {};
  50774. serializationObject.name = this.name;
  50775. serializationObject.influence = this.influence;
  50776. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  50777. if (this.hasNormals) {
  50778. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  50779. }
  50780. if (this.hasTangents) {
  50781. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  50782. }
  50783. return serializationObject;
  50784. };
  50785. // Statics
  50786. MorphTarget.Parse = function (serializationObject) {
  50787. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  50788. result.setPositions(serializationObject.positions);
  50789. if (serializationObject.normals) {
  50790. result.setNormals(serializationObject.normals);
  50791. }
  50792. if (serializationObject.tangents) {
  50793. result.setTangents(serializationObject.tangents);
  50794. }
  50795. return result;
  50796. };
  50797. MorphTarget.FromMesh = function (mesh, name, influence) {
  50798. if (!name) {
  50799. name = mesh.name;
  50800. }
  50801. var result = new MorphTarget(name, influence);
  50802. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  50803. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50804. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  50805. }
  50806. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  50807. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  50808. }
  50809. return result;
  50810. };
  50811. return MorphTarget;
  50812. }());
  50813. BABYLON.MorphTarget = MorphTarget;
  50814. })(BABYLON || (BABYLON = {}));
  50815. //# sourceMappingURL=babylon.morphTarget.js.map
  50816. var BABYLON;
  50817. (function (BABYLON) {
  50818. var MorphTargetManager = (function () {
  50819. function MorphTargetManager(scene) {
  50820. this._targets = new Array();
  50821. this._targetObservable = new Array();
  50822. this._activeTargets = new BABYLON.SmartArray(16);
  50823. this._supportsNormals = false;
  50824. this._supportsTangents = false;
  50825. this._vertexCount = 0;
  50826. this._uniqueId = 0;
  50827. this._tempInfluences = new Array();
  50828. if (!scene) {
  50829. scene = BABYLON.Engine.LastCreatedScene;
  50830. }
  50831. this._scene = scene;
  50832. this._scene.morphTargetManagers.push(this);
  50833. this._uniqueId = scene.getUniqueId();
  50834. }
  50835. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  50836. get: function () {
  50837. return this._uniqueId;
  50838. },
  50839. enumerable: true,
  50840. configurable: true
  50841. });
  50842. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  50843. get: function () {
  50844. return this._vertexCount;
  50845. },
  50846. enumerable: true,
  50847. configurable: true
  50848. });
  50849. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  50850. get: function () {
  50851. return this._supportsNormals;
  50852. },
  50853. enumerable: true,
  50854. configurable: true
  50855. });
  50856. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  50857. get: function () {
  50858. return this._supportsTangents;
  50859. },
  50860. enumerable: true,
  50861. configurable: true
  50862. });
  50863. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  50864. get: function () {
  50865. return this._targets.length;
  50866. },
  50867. enumerable: true,
  50868. configurable: true
  50869. });
  50870. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  50871. get: function () {
  50872. return this._activeTargets.length;
  50873. },
  50874. enumerable: true,
  50875. configurable: true
  50876. });
  50877. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  50878. get: function () {
  50879. return this._influences;
  50880. },
  50881. enumerable: true,
  50882. configurable: true
  50883. });
  50884. MorphTargetManager.prototype.getActiveTarget = function (index) {
  50885. return this._activeTargets.data[index];
  50886. };
  50887. MorphTargetManager.prototype.getTarget = function (index) {
  50888. return this._targets[index];
  50889. };
  50890. MorphTargetManager.prototype.addTarget = function (target) {
  50891. var _this = this;
  50892. if (this._vertexCount) {
  50893. if (this._vertexCount !== target.getPositions().length / 3) {
  50894. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  50895. return;
  50896. }
  50897. }
  50898. this._targets.push(target);
  50899. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  50900. _this._syncActiveTargets(needUpdate);
  50901. }));
  50902. this._syncActiveTargets(true);
  50903. };
  50904. MorphTargetManager.prototype.removeTarget = function (target) {
  50905. var index = this._targets.indexOf(target);
  50906. if (index >= 0) {
  50907. this._targets.splice(index, 1);
  50908. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  50909. this._vertexCount = 0;
  50910. this._syncActiveTargets(true);
  50911. }
  50912. };
  50913. /**
  50914. * Serializes the current manager into a Serialization object.
  50915. * Returns the serialized object.
  50916. */
  50917. MorphTargetManager.prototype.serialize = function () {
  50918. var serializationObject = {};
  50919. serializationObject.id = this.uniqueId;
  50920. serializationObject.targets = [];
  50921. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  50922. var target = _a[_i];
  50923. serializationObject.targets.push(target.serialize());
  50924. }
  50925. return serializationObject;
  50926. };
  50927. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  50928. this._syncActiveTargets(needUpdate);
  50929. };
  50930. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  50931. var influenceCount = 0;
  50932. this._activeTargets.reset();
  50933. this._supportsNormals = true;
  50934. this._supportsTangents = true;
  50935. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  50936. var target = _a[_i];
  50937. if (target.influence > 0) {
  50938. this._activeTargets.push(target);
  50939. this._tempInfluences[influenceCount++] = target.influence;
  50940. this._supportsNormals = this._supportsNormals && target.hasNormals;
  50941. this._supportsTangents = this._supportsTangents && target.hasTangents;
  50942. if (this._vertexCount === 0) {
  50943. this._vertexCount = target.getPositions().length / 3;
  50944. }
  50945. }
  50946. }
  50947. if (!this._influences || this._influences.length !== influenceCount) {
  50948. this._influences = new Float32Array(influenceCount);
  50949. }
  50950. for (var index = 0; index < influenceCount; index++) {
  50951. this._influences[index] = this._tempInfluences[index];
  50952. }
  50953. if (needUpdate) {
  50954. // Flag meshes as dirty to resync with the active targets
  50955. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  50956. var mesh = _c[_b];
  50957. if (mesh.morphTargetManager === this) {
  50958. mesh._syncGeometryWithMorphTargetManager();
  50959. }
  50960. }
  50961. }
  50962. };
  50963. // Statics
  50964. MorphTargetManager.Parse = function (serializationObject, scene) {
  50965. var result = new MorphTargetManager(scene);
  50966. result._uniqueId = serializationObject.id;
  50967. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  50968. var targetData = _a[_i];
  50969. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  50970. }
  50971. return result;
  50972. };
  50973. return MorphTargetManager;
  50974. }());
  50975. BABYLON.MorphTargetManager = MorphTargetManager;
  50976. })(BABYLON || (BABYLON = {}));
  50977. //# sourceMappingURL=babylon.morphTargetManager.js.map
  50978. 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}"};
  50979. 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};"};
  50980. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  50981. var BABYLON;
  50982. (function (BABYLON) {
  50983. var GridMaterialDefines = (function (_super) {
  50984. __extends(GridMaterialDefines, _super);
  50985. function GridMaterialDefines() {
  50986. var _this = _super.call(this) || this;
  50987. _this.TRANSPARENT = false;
  50988. _this.FOG = false;
  50989. _this.PREMULTIPLYALPHA = false;
  50990. _this.rebuild();
  50991. return _this;
  50992. }
  50993. return GridMaterialDefines;
  50994. }(BABYLON.MaterialDefines));
  50995. /**
  50996. * The grid materials allows you to wrap any shape with a grid.
  50997. * Colors are customizable.
  50998. */
  50999. var GridMaterial = (function (_super) {
  51000. __extends(GridMaterial, _super);
  51001. /**
  51002. * constructor
  51003. * @param name The name given to the material in order to identify it afterwards.
  51004. * @param scene The scene the material is used in.
  51005. */
  51006. function GridMaterial(name, scene) {
  51007. var _this = _super.call(this, name, scene) || this;
  51008. /**
  51009. * Main color of the grid (e.g. between lines)
  51010. */
  51011. _this.mainColor = BABYLON.Color3.Black();
  51012. /**
  51013. * Color of the grid lines.
  51014. */
  51015. _this.lineColor = BABYLON.Color3.Teal();
  51016. /**
  51017. * The scale of the grid compared to unit.
  51018. */
  51019. _this.gridRatio = 1.0;
  51020. /**
  51021. * The frequency of thicker lines.
  51022. */
  51023. _this.majorUnitFrequency = 10;
  51024. /**
  51025. * The visibility of minor units in the grid.
  51026. */
  51027. _this.minorUnitVisibility = 0.33;
  51028. /**
  51029. * The grid opacity outside of the lines.
  51030. */
  51031. _this.opacity = 1.0;
  51032. /**
  51033. * Determine RBG output is premultiplied by alpha value.
  51034. */
  51035. _this.preMultiplyAlpha = false;
  51036. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  51037. return _this;
  51038. }
  51039. /**
  51040. * Returns wehter or not the grid requires alpha blending.
  51041. */
  51042. GridMaterial.prototype.needAlphaBlending = function () {
  51043. return this.opacity < 1.0;
  51044. };
  51045. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  51046. if (this.isFrozen) {
  51047. if (this._wasPreviouslyReady && subMesh.effect) {
  51048. return true;
  51049. }
  51050. }
  51051. if (!subMesh._materialDefines) {
  51052. subMesh._materialDefines = new GridMaterialDefines();
  51053. }
  51054. var defines = subMesh._materialDefines;
  51055. var scene = this.getScene();
  51056. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  51057. if (this._renderId === scene.getRenderId()) {
  51058. return true;
  51059. }
  51060. }
  51061. var engine = scene.getEngine();
  51062. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  51063. defines.TRANSPARENT = !defines.TRANSPARENT;
  51064. defines.markAsUnprocessed();
  51065. }
  51066. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  51067. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  51068. defines.markAsUnprocessed();
  51069. }
  51070. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  51071. // Get correct effect
  51072. if (defines.isDirty) {
  51073. defines.markAsProcessed();
  51074. scene.resetCachedMaterial();
  51075. // Attributes
  51076. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  51077. // Defines
  51078. var join = defines.toString();
  51079. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  51080. }
  51081. if (!subMesh.effect.isReady()) {
  51082. return false;
  51083. }
  51084. this._renderId = scene.getRenderId();
  51085. this._wasPreviouslyReady = true;
  51086. return true;
  51087. };
  51088. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  51089. var scene = this.getScene();
  51090. var defines = subMesh._materialDefines;
  51091. if (!defines) {
  51092. return;
  51093. }
  51094. var effect = subMesh.effect;
  51095. this._activeEffect = effect;
  51096. // Matrices
  51097. this.bindOnlyWorldMatrix(world);
  51098. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  51099. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  51100. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  51101. // Uniforms
  51102. if (this._mustRebind(scene, effect)) {
  51103. this._activeEffect.setColor3("mainColor", this.mainColor);
  51104. this._activeEffect.setColor3("lineColor", this.lineColor);
  51105. this._gridControl.x = this.gridRatio;
  51106. this._gridControl.y = Math.round(this.majorUnitFrequency);
  51107. this._gridControl.z = this.minorUnitVisibility;
  51108. this._gridControl.w = this.opacity;
  51109. this._activeEffect.setVector4("gridControl", this._gridControl);
  51110. }
  51111. // Fog
  51112. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  51113. this._afterBind(mesh, this._activeEffect);
  51114. };
  51115. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  51116. _super.prototype.dispose.call(this, forceDisposeEffect);
  51117. };
  51118. GridMaterial.prototype.clone = function (name) {
  51119. var _this = this;
  51120. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  51121. };
  51122. GridMaterial.prototype.serialize = function () {
  51123. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51124. serializationObject.customType = "BABYLON.GridMaterial";
  51125. return serializationObject;
  51126. };
  51127. GridMaterial.prototype.getClassName = function () {
  51128. return "GridMaterial";
  51129. };
  51130. GridMaterial.Parse = function (source, scene, rootUrl) {
  51131. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  51132. };
  51133. __decorate([
  51134. BABYLON.serializeAsColor3()
  51135. ], GridMaterial.prototype, "mainColor", void 0);
  51136. __decorate([
  51137. BABYLON.serializeAsColor3()
  51138. ], GridMaterial.prototype, "lineColor", void 0);
  51139. __decorate([
  51140. BABYLON.serialize()
  51141. ], GridMaterial.prototype, "gridRatio", void 0);
  51142. __decorate([
  51143. BABYLON.serialize()
  51144. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  51145. __decorate([
  51146. BABYLON.serialize()
  51147. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  51148. __decorate([
  51149. BABYLON.serialize()
  51150. ], GridMaterial.prototype, "opacity", void 0);
  51151. __decorate([
  51152. BABYLON.serialize()
  51153. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  51154. return GridMaterial;
  51155. }(BABYLON.PushMaterial));
  51156. BABYLON.GridMaterial = GridMaterial;
  51157. })(BABYLON || (BABYLON = {}));
  51158. //# sourceMappingURL=babylon.gridmaterial.js.map
  51159. 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}";
  51160. 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}";
  51161. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  51162. var BABYLON;
  51163. (function (BABYLON) {
  51164. var GLTFLoaderCoordinateSystemMode;
  51165. (function (GLTFLoaderCoordinateSystemMode) {
  51166. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  51167. // 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.
  51168. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  51169. // The glTF right-handed data is not transformed in any form and is loaded directly.
  51170. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  51171. // Sets the useRightHandedSystem flag on the scene.
  51172. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  51173. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  51174. var GLTFFileLoader = (function () {
  51175. function GLTFFileLoader() {
  51176. // V2 options
  51177. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  51178. this.name = "gltf";
  51179. this.extensions = {
  51180. ".gltf": { isBinary: false },
  51181. ".glb": { isBinary: true }
  51182. };
  51183. }
  51184. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  51185. var loaderData = GLTFFileLoader._parse(data, onError);
  51186. if (!loaderData) {
  51187. return;
  51188. }
  51189. var loader = this._getLoader(loaderData, onError);
  51190. if (!loader) {
  51191. return;
  51192. }
  51193. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51194. };
  51195. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  51196. var loaderData = GLTFFileLoader._parse(data, onError);
  51197. if (!loaderData) {
  51198. return;
  51199. }
  51200. var loader = this._getLoader(loaderData, onError);
  51201. if (!loader) {
  51202. return;
  51203. }
  51204. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51205. };
  51206. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  51207. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  51208. };
  51209. GLTFFileLoader._parse = function (data, onError) {
  51210. if (data instanceof ArrayBuffer) {
  51211. return GLTFFileLoader._parseBinary(data, onError);
  51212. }
  51213. try {
  51214. return {
  51215. json: JSON.parse(data),
  51216. bin: null
  51217. };
  51218. }
  51219. catch (e) {
  51220. onError(e.message);
  51221. return null;
  51222. }
  51223. };
  51224. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  51225. var loaderVersion = { major: 2, minor: 0 };
  51226. var asset = loaderData.json.asset || {};
  51227. var version = GLTFFileLoader._parseVersion(asset.version);
  51228. if (!version) {
  51229. onError("Invalid version: " + asset.version);
  51230. return null;
  51231. }
  51232. if (asset.minVersion !== undefined) {
  51233. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  51234. if (!minVersion) {
  51235. onError("Invalid minimum version: " + asset.minVersion);
  51236. return null;
  51237. }
  51238. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  51239. onError("Incompatible minimum version: " + asset.minVersion);
  51240. return null;
  51241. }
  51242. }
  51243. var createLoaders = {
  51244. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  51245. 2: GLTFFileLoader.CreateGLTFLoaderV2
  51246. };
  51247. var createLoader = createLoaders[version.major];
  51248. if (!createLoader) {
  51249. onError("Unsupported version: " + asset.version);
  51250. return null;
  51251. }
  51252. return createLoader(this);
  51253. };
  51254. GLTFFileLoader._parseBinary = function (data, onError) {
  51255. var Binary = {
  51256. Magic: 0x46546C67
  51257. };
  51258. var binaryReader = new BinaryReader(data);
  51259. var magic = binaryReader.readUint32();
  51260. if (magic !== Binary.Magic) {
  51261. onError("Unexpected magic: " + magic);
  51262. return null;
  51263. }
  51264. var version = binaryReader.readUint32();
  51265. switch (version) {
  51266. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  51267. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  51268. }
  51269. onError("Unsupported version: " + version);
  51270. return null;
  51271. };
  51272. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  51273. var ContentFormat = {
  51274. JSON: 0
  51275. };
  51276. var length = binaryReader.readUint32();
  51277. if (length != binaryReader.getLength()) {
  51278. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  51279. return null;
  51280. }
  51281. var contentLength = binaryReader.readUint32();
  51282. var contentFormat = binaryReader.readUint32();
  51283. var content;
  51284. switch (contentFormat) {
  51285. case ContentFormat.JSON:
  51286. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  51287. break;
  51288. default:
  51289. onError("Unexpected content format: " + contentFormat);
  51290. return null;
  51291. }
  51292. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  51293. var body = binaryReader.readUint8Array(bytesRemaining);
  51294. return {
  51295. json: content,
  51296. bin: body
  51297. };
  51298. };
  51299. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  51300. var ChunkFormat = {
  51301. JSON: 0x4E4F534A,
  51302. BIN: 0x004E4942
  51303. };
  51304. var length = binaryReader.readUint32();
  51305. if (length !== binaryReader.getLength()) {
  51306. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  51307. return null;
  51308. }
  51309. // JSON chunk
  51310. var chunkLength = binaryReader.readUint32();
  51311. var chunkFormat = binaryReader.readUint32();
  51312. if (chunkFormat !== ChunkFormat.JSON) {
  51313. onError("First chunk format is not JSON");
  51314. return null;
  51315. }
  51316. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  51317. // Look for BIN chunk
  51318. var bin = null;
  51319. while (binaryReader.getPosition() < binaryReader.getLength()) {
  51320. chunkLength = binaryReader.readUint32();
  51321. chunkFormat = binaryReader.readUint32();
  51322. switch (chunkFormat) {
  51323. case ChunkFormat.JSON:
  51324. onError("Unexpected JSON chunk");
  51325. return null;
  51326. case ChunkFormat.BIN:
  51327. bin = binaryReader.readUint8Array(chunkLength);
  51328. break;
  51329. default:
  51330. // ignore unrecognized chunkFormat
  51331. binaryReader.skipBytes(chunkLength);
  51332. break;
  51333. }
  51334. }
  51335. return {
  51336. json: json,
  51337. bin: bin
  51338. };
  51339. };
  51340. GLTFFileLoader._parseVersion = function (version) {
  51341. if (!version) {
  51342. return null;
  51343. }
  51344. var parts = version.split(".");
  51345. if (parts.length != 2) {
  51346. return null;
  51347. }
  51348. var major = +parts[0];
  51349. if (isNaN(major)) {
  51350. return null;
  51351. }
  51352. var minor = +parts[1];
  51353. if (isNaN(minor)) {
  51354. return null;
  51355. }
  51356. return {
  51357. major: major,
  51358. minor: minor
  51359. };
  51360. };
  51361. GLTFFileLoader._compareVersion = function (a, b) {
  51362. if (a.major > b.major)
  51363. return 1;
  51364. if (a.major < b.major)
  51365. return -1;
  51366. if (a.minor > b.minor)
  51367. return 1;
  51368. if (a.minor < b.minor)
  51369. return -1;
  51370. return 0;
  51371. };
  51372. GLTFFileLoader._decodeBufferToText = function (view) {
  51373. var result = "";
  51374. var length = view.byteLength;
  51375. for (var i = 0; i < length; ++i) {
  51376. result += String.fromCharCode(view[i]);
  51377. }
  51378. return result;
  51379. };
  51380. // V1 options
  51381. GLTFFileLoader.HomogeneousCoordinates = false;
  51382. GLTFFileLoader.IncrementalLoading = true;
  51383. return GLTFFileLoader;
  51384. }());
  51385. BABYLON.GLTFFileLoader = GLTFFileLoader;
  51386. var BinaryReader = (function () {
  51387. function BinaryReader(arrayBuffer) {
  51388. this._arrayBuffer = arrayBuffer;
  51389. this._dataView = new DataView(arrayBuffer);
  51390. this._byteOffset = 0;
  51391. }
  51392. BinaryReader.prototype.getPosition = function () {
  51393. return this._byteOffset;
  51394. };
  51395. BinaryReader.prototype.getLength = function () {
  51396. return this._arrayBuffer.byteLength;
  51397. };
  51398. BinaryReader.prototype.readUint32 = function () {
  51399. var value = this._dataView.getUint32(this._byteOffset, true);
  51400. this._byteOffset += 4;
  51401. return value;
  51402. };
  51403. BinaryReader.prototype.readUint8Array = function (length) {
  51404. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  51405. this._byteOffset += length;
  51406. return value;
  51407. };
  51408. BinaryReader.prototype.skipBytes = function (length) {
  51409. this._byteOffset += length;
  51410. };
  51411. return BinaryReader;
  51412. }());
  51413. if (BABYLON.SceneLoader) {
  51414. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  51415. }
  51416. })(BABYLON || (BABYLON = {}));
  51417. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  51418. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  51419. var BABYLON;
  51420. (function (BABYLON) {
  51421. var GLTF1;
  51422. (function (GLTF1) {
  51423. /**
  51424. * Enums
  51425. */
  51426. var EComponentType;
  51427. (function (EComponentType) {
  51428. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  51429. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  51430. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  51431. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  51432. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  51433. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  51434. var EShaderType;
  51435. (function (EShaderType) {
  51436. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  51437. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  51438. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  51439. var EParameterType;
  51440. (function (EParameterType) {
  51441. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  51442. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  51443. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  51444. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  51445. EParameterType[EParameterType["INT"] = 5124] = "INT";
  51446. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  51447. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  51448. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  51449. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  51450. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  51451. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  51452. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  51453. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  51454. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  51455. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  51456. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  51457. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  51458. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  51459. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  51460. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  51461. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  51462. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  51463. var ETextureWrapMode;
  51464. (function (ETextureWrapMode) {
  51465. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  51466. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  51467. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  51468. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  51469. var ETextureFilterType;
  51470. (function (ETextureFilterType) {
  51471. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  51472. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  51473. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  51474. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  51475. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  51476. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  51477. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  51478. var ETextureFormat;
  51479. (function (ETextureFormat) {
  51480. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  51481. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  51482. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  51483. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  51484. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  51485. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  51486. var ECullingType;
  51487. (function (ECullingType) {
  51488. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  51489. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  51490. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  51491. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  51492. var EBlendingFunction;
  51493. (function (EBlendingFunction) {
  51494. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  51495. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  51496. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  51497. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  51498. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  51499. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  51500. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  51501. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  51502. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  51503. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  51504. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  51505. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  51506. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  51507. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  51508. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  51509. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  51510. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  51511. })(BABYLON || (BABYLON = {}));
  51512. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  51513. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  51514. var BABYLON;
  51515. (function (BABYLON) {
  51516. var GLTF1;
  51517. (function (GLTF1) {
  51518. /**
  51519. * Tokenizer. Used for shaders compatibility
  51520. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  51521. */
  51522. var ETokenType;
  51523. (function (ETokenType) {
  51524. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  51525. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  51526. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  51527. })(ETokenType || (ETokenType = {}));
  51528. var Tokenizer = (function () {
  51529. function Tokenizer(toParse) {
  51530. this._pos = 0;
  51531. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  51532. this._toParse = toParse;
  51533. this._maxPos = toParse.length;
  51534. }
  51535. Tokenizer.prototype.getNextToken = function () {
  51536. if (this.isEnd())
  51537. return ETokenType.END_OF_INPUT;
  51538. this.currentString = this.read();
  51539. this.currentToken = ETokenType.UNKNOWN;
  51540. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  51541. this.currentToken = ETokenType.IDENTIFIER;
  51542. this.currentIdentifier = this.currentString;
  51543. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  51544. this.currentIdentifier += this.currentString;
  51545. this.forward();
  51546. }
  51547. }
  51548. return this.currentToken;
  51549. };
  51550. Tokenizer.prototype.peek = function () {
  51551. return this._toParse[this._pos];
  51552. };
  51553. Tokenizer.prototype.read = function () {
  51554. return this._toParse[this._pos++];
  51555. };
  51556. Tokenizer.prototype.forward = function () {
  51557. this._pos++;
  51558. };
  51559. Tokenizer.prototype.isEnd = function () {
  51560. return this._pos >= this._maxPos;
  51561. };
  51562. return Tokenizer;
  51563. }());
  51564. /**
  51565. * Values
  51566. */
  51567. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  51568. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  51569. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  51570. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  51571. /**
  51572. * Parse
  51573. */
  51574. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  51575. for (var buf in parsedBuffers) {
  51576. var parsedBuffer = parsedBuffers[buf];
  51577. gltfRuntime.buffers[buf] = parsedBuffer;
  51578. gltfRuntime.buffersCount++;
  51579. }
  51580. };
  51581. var parseShaders = function (parsedShaders, gltfRuntime) {
  51582. for (var sha in parsedShaders) {
  51583. var parsedShader = parsedShaders[sha];
  51584. gltfRuntime.shaders[sha] = parsedShader;
  51585. gltfRuntime.shaderscount++;
  51586. }
  51587. };
  51588. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  51589. for (var object in parsedObjects) {
  51590. var parsedObject = parsedObjects[object];
  51591. gltfRuntime[runtimeProperty][object] = parsedObject;
  51592. }
  51593. };
  51594. /**
  51595. * Utils
  51596. */
  51597. var normalizeUVs = function (buffer) {
  51598. if (!buffer) {
  51599. return;
  51600. }
  51601. for (var i = 0; i < buffer.length / 2; i++) {
  51602. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  51603. }
  51604. };
  51605. var replaceInString = function (str, searchValue, replaceValue) {
  51606. while (str.indexOf(searchValue) !== -1) {
  51607. str = str.replace(searchValue, replaceValue);
  51608. }
  51609. return str;
  51610. };
  51611. var getAttribute = function (attributeParameter) {
  51612. if (attributeParameter.semantic === "NORMAL") {
  51613. return "normal";
  51614. }
  51615. else if (attributeParameter.semantic === "POSITION") {
  51616. return "position";
  51617. }
  51618. else if (attributeParameter.semantic === "JOINT") {
  51619. return "matricesIndices";
  51620. }
  51621. else if (attributeParameter.semantic === "WEIGHT") {
  51622. return "matricesWeights";
  51623. }
  51624. else if (attributeParameter.semantic === "COLOR") {
  51625. return "color";
  51626. }
  51627. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  51628. var channel = Number(attributeParameter.semantic.split("_")[1]);
  51629. return "uv" + (channel === 0 ? "" : channel + 1);
  51630. }
  51631. };
  51632. /**
  51633. * Returns the animation path (glTF -> Babylon)
  51634. */
  51635. var getAnimationPath = function (path) {
  51636. var index = glTFAnimationPaths.indexOf(path);
  51637. if (index !== -1) {
  51638. return babylonAnimationPaths[index];
  51639. }
  51640. return path;
  51641. };
  51642. /**
  51643. * Loads and creates animations
  51644. */
  51645. var loadAnimations = function (gltfRuntime) {
  51646. for (var anim in gltfRuntime.animations) {
  51647. var animation = gltfRuntime.animations[anim];
  51648. var lastAnimation = null;
  51649. for (var i = 0; i < animation.channels.length; i++) {
  51650. // Get parameters and load buffers
  51651. var channel = animation.channels[i];
  51652. var sampler = animation.samplers[channel.sampler];
  51653. if (!sampler) {
  51654. continue;
  51655. }
  51656. var inputData = null;
  51657. var outputData = null;
  51658. if (animation.parameters) {
  51659. inputData = animation.parameters[sampler.input];
  51660. outputData = animation.parameters[sampler.output];
  51661. }
  51662. else {
  51663. inputData = sampler.input;
  51664. outputData = sampler.output;
  51665. }
  51666. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  51667. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  51668. var targetID = channel.target.id;
  51669. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  51670. if (targetNode === null) {
  51671. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  51672. }
  51673. if (targetNode === null) {
  51674. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  51675. continue;
  51676. }
  51677. var isBone = targetNode instanceof BABYLON.Bone;
  51678. // Get target path (position, rotation or scaling)
  51679. var targetPath = channel.target.path;
  51680. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  51681. if (targetPathIndex !== -1) {
  51682. targetPath = babylonAnimationPaths[targetPathIndex];
  51683. }
  51684. // Determine animation type
  51685. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  51686. if (!isBone) {
  51687. if (targetPath === "rotationQuaternion") {
  51688. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  51689. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  51690. }
  51691. else {
  51692. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  51693. }
  51694. }
  51695. // Create animation and key frames
  51696. var babylonAnimation = null;
  51697. var keys = [];
  51698. var arrayOffset = 0;
  51699. var modifyKey = false;
  51700. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  51701. babylonAnimation = lastAnimation;
  51702. modifyKey = true;
  51703. }
  51704. if (!modifyKey) {
  51705. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51706. }
  51707. // For each frame
  51708. for (var j = 0; j < bufferInput.length; j++) {
  51709. var value = null;
  51710. if (targetPath === "rotationQuaternion") {
  51711. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  51712. arrayOffset += 4;
  51713. }
  51714. else {
  51715. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  51716. arrayOffset += 3;
  51717. }
  51718. if (isBone) {
  51719. var bone = targetNode;
  51720. var translation = BABYLON.Vector3.Zero();
  51721. var rotationQuaternion = new BABYLON.Quaternion();
  51722. var scaling = BABYLON.Vector3.Zero();
  51723. // Warning on decompose
  51724. var mat = bone.getBaseMatrix();
  51725. if (modifyKey) {
  51726. mat = lastAnimation.getKeys()[j].value;
  51727. }
  51728. mat.decompose(scaling, rotationQuaternion, translation);
  51729. if (targetPath === "position") {
  51730. translation = value;
  51731. }
  51732. else if (targetPath === "rotationQuaternion") {
  51733. rotationQuaternion = value;
  51734. }
  51735. else {
  51736. scaling = value;
  51737. }
  51738. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  51739. }
  51740. if (!modifyKey) {
  51741. keys.push({
  51742. frame: bufferInput[j],
  51743. value: value
  51744. });
  51745. }
  51746. else {
  51747. lastAnimation.getKeys()[j].value = value;
  51748. }
  51749. }
  51750. // Finish
  51751. if (!modifyKey) {
  51752. babylonAnimation.setKeys(keys);
  51753. targetNode.animations.push(babylonAnimation);
  51754. }
  51755. lastAnimation = babylonAnimation;
  51756. gltfRuntime.scene.stopAnimation(targetNode);
  51757. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  51758. }
  51759. }
  51760. };
  51761. /**
  51762. * Returns the bones transformation matrix
  51763. */
  51764. var configureBoneTransformation = function (node) {
  51765. var mat = null;
  51766. if (node.translation || node.rotation || node.scale) {
  51767. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  51768. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  51769. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  51770. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  51771. }
  51772. else {
  51773. mat = BABYLON.Matrix.FromArray(node.matrix);
  51774. }
  51775. return mat;
  51776. };
  51777. /**
  51778. * Returns the parent bone
  51779. */
  51780. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  51781. // Try to find
  51782. for (var i = 0; i < newSkeleton.bones.length; i++) {
  51783. if (newSkeleton.bones[i].name === jointName) {
  51784. return newSkeleton.bones[i];
  51785. }
  51786. }
  51787. // Not found, search in gltf nodes
  51788. var nodes = gltfRuntime.nodes;
  51789. for (var nde in nodes) {
  51790. var node = nodes[nde];
  51791. if (!node.jointName) {
  51792. continue;
  51793. }
  51794. var children = node.children;
  51795. for (var i = 0; i < children.length; i++) {
  51796. var child = gltfRuntime.nodes[children[i]];
  51797. if (!child.jointName) {
  51798. continue;
  51799. }
  51800. if (child.jointName === jointName) {
  51801. var mat = configureBoneTransformation(node);
  51802. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  51803. bone.id = nde;
  51804. return bone;
  51805. }
  51806. }
  51807. }
  51808. return null;
  51809. };
  51810. /**
  51811. * Returns the appropriate root node
  51812. */
  51813. var getNodeToRoot = function (nodesToRoot, id) {
  51814. for (var i = 0; i < nodesToRoot.length; i++) {
  51815. var nodeToRoot = nodesToRoot[i];
  51816. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  51817. var child = nodeToRoot.node.children[j];
  51818. if (child === id) {
  51819. return nodeToRoot.bone;
  51820. }
  51821. }
  51822. }
  51823. return null;
  51824. };
  51825. /**
  51826. * Returns the node with the joint name
  51827. */
  51828. var getJointNode = function (gltfRuntime, jointName) {
  51829. var nodes = gltfRuntime.nodes;
  51830. var node = nodes[jointName];
  51831. if (node) {
  51832. return {
  51833. node: node,
  51834. id: jointName
  51835. };
  51836. }
  51837. for (var nde in nodes) {
  51838. node = nodes[nde];
  51839. if (node.jointName === jointName) {
  51840. return {
  51841. node: node,
  51842. id: nde
  51843. };
  51844. }
  51845. }
  51846. return null;
  51847. };
  51848. /**
  51849. * Checks if a nodes is in joints
  51850. */
  51851. var nodeIsInJoints = function (skins, id) {
  51852. for (var i = 0; i < skins.jointNames.length; i++) {
  51853. if (skins.jointNames[i] === id) {
  51854. return true;
  51855. }
  51856. }
  51857. return false;
  51858. };
  51859. /**
  51860. * Fills the nodes to root for bones and builds hierarchy
  51861. */
  51862. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  51863. // Creates nodes for root
  51864. for (var nde in gltfRuntime.nodes) {
  51865. var node = gltfRuntime.nodes[nde];
  51866. var id = nde;
  51867. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  51868. continue;
  51869. }
  51870. // Create node to root bone
  51871. var mat = configureBoneTransformation(node);
  51872. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  51873. bone.id = id;
  51874. nodesToRoot.push({ bone: bone, node: node, id: id });
  51875. }
  51876. // Parenting
  51877. for (var i = 0; i < nodesToRoot.length; i++) {
  51878. var nodeToRoot = nodesToRoot[i];
  51879. var children = nodeToRoot.node.children;
  51880. for (var j = 0; j < children.length; j++) {
  51881. var child = null;
  51882. for (var k = 0; k < nodesToRoot.length; k++) {
  51883. if (nodesToRoot[k].id === children[j]) {
  51884. child = nodesToRoot[k];
  51885. break;
  51886. }
  51887. }
  51888. if (child) {
  51889. child.bone._parent = nodeToRoot.bone;
  51890. nodeToRoot.bone.children.push(child.bone);
  51891. }
  51892. }
  51893. }
  51894. };
  51895. var printMat = function (m) {
  51896. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  51897. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  51898. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  51899. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  51900. };
  51901. /**
  51902. * Imports a skeleton
  51903. */
  51904. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  51905. if (!newSkeleton) {
  51906. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  51907. }
  51908. if (!skins.babylonSkeleton) {
  51909. return newSkeleton;
  51910. }
  51911. // Matrices
  51912. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  51913. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  51914. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  51915. // Find the root bones
  51916. var nodesToRoot = [];
  51917. var nodesToRootToAdd = [];
  51918. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  51919. newSkeleton.bones = [];
  51920. // Joints
  51921. for (var i = 0; i < skins.jointNames.length; i++) {
  51922. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  51923. var node = jointNode.node;
  51924. if (!node) {
  51925. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  51926. continue;
  51927. }
  51928. var id = jointNode.id;
  51929. // Optimize, if the bone already exists...
  51930. var existingBone = gltfRuntime.scene.getBoneByID(id);
  51931. if (existingBone) {
  51932. newSkeleton.bones.push(existingBone);
  51933. continue;
  51934. }
  51935. // Search for parent bone
  51936. var foundBone = false;
  51937. var parentBone = null;
  51938. for (var j = 0; j < i; j++) {
  51939. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  51940. if (!joint) {
  51941. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  51942. continue;
  51943. }
  51944. var children = joint.children;
  51945. if (!children) {
  51946. continue;
  51947. }
  51948. foundBone = false;
  51949. for (var k = 0; k < children.length; k++) {
  51950. if (children[k] === id) {
  51951. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  51952. foundBone = true;
  51953. break;
  51954. }
  51955. }
  51956. if (foundBone) {
  51957. break;
  51958. }
  51959. }
  51960. // Create bone
  51961. var mat = configureBoneTransformation(node);
  51962. if (!parentBone && nodesToRoot.length > 0) {
  51963. parentBone = getNodeToRoot(nodesToRoot, id);
  51964. if (parentBone) {
  51965. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  51966. nodesToRootToAdd.push(parentBone);
  51967. }
  51968. }
  51969. }
  51970. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  51971. bone.id = id;
  51972. }
  51973. // Polish
  51974. var bones = newSkeleton.bones;
  51975. newSkeleton.bones = [];
  51976. for (var i = 0; i < skins.jointNames.length; i++) {
  51977. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  51978. if (!jointNode) {
  51979. continue;
  51980. }
  51981. for (var j = 0; j < bones.length; j++) {
  51982. if (bones[j].id === jointNode.id) {
  51983. newSkeleton.bones.push(bones[j]);
  51984. break;
  51985. }
  51986. }
  51987. }
  51988. newSkeleton.prepare();
  51989. // Finish
  51990. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  51991. newSkeleton.bones.push(nodesToRootToAdd[i]);
  51992. }
  51993. return newSkeleton;
  51994. };
  51995. /**
  51996. * Imports a mesh and its geometries
  51997. */
  51998. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  51999. if (!newMesh) {
  52000. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  52001. newMesh.id = id;
  52002. }
  52003. if (!node.babylonNode) {
  52004. return newMesh;
  52005. }
  52006. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  52007. if (!newMesh.material) {
  52008. newMesh.material = multiMat;
  52009. }
  52010. var vertexData = new BABYLON.VertexData();
  52011. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  52012. var verticesStarts = [];
  52013. var verticesCounts = [];
  52014. var indexStarts = [];
  52015. var indexCounts = [];
  52016. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  52017. var meshID = meshes[meshIndex];
  52018. var mesh = gltfRuntime.meshes[meshID];
  52019. if (!mesh) {
  52020. continue;
  52021. }
  52022. // Positions, normals and UVs
  52023. for (var i = 0; i < mesh.primitives.length; i++) {
  52024. // Temporary vertex data
  52025. var tempVertexData = new BABYLON.VertexData();
  52026. var primitive = mesh.primitives[i];
  52027. if (primitive.mode !== 4) {
  52028. // continue;
  52029. }
  52030. var attributes = primitive.attributes;
  52031. var accessor = null;
  52032. var buffer = null;
  52033. // Set positions, normal and uvs
  52034. for (var semantic in attributes) {
  52035. // Link accessor and buffer view
  52036. accessor = gltfRuntime.accessors[attributes[semantic]];
  52037. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52038. if (semantic === "NORMAL") {
  52039. tempVertexData.normals = new Float32Array(buffer.length);
  52040. tempVertexData.normals.set(buffer);
  52041. }
  52042. else if (semantic === "POSITION") {
  52043. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  52044. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  52045. for (var j = 0; j < buffer.length; j += 4) {
  52046. tempVertexData.positions[j] = buffer[j];
  52047. tempVertexData.positions[j + 1] = buffer[j + 1];
  52048. tempVertexData.positions[j + 2] = buffer[j + 2];
  52049. }
  52050. }
  52051. else {
  52052. tempVertexData.positions = new Float32Array(buffer.length);
  52053. tempVertexData.positions.set(buffer);
  52054. }
  52055. verticesCounts.push(tempVertexData.positions.length);
  52056. }
  52057. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  52058. var channel = Number(semantic.split("_")[1]);
  52059. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  52060. var uvs = new Float32Array(buffer.length);
  52061. uvs.set(buffer);
  52062. normalizeUVs(uvs);
  52063. tempVertexData.set(uvs, uvKind);
  52064. }
  52065. else if (semantic === "JOINT") {
  52066. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  52067. tempVertexData.matricesIndices.set(buffer);
  52068. }
  52069. else if (semantic === "WEIGHT") {
  52070. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  52071. tempVertexData.matricesWeights.set(buffer);
  52072. }
  52073. else if (semantic === "COLOR") {
  52074. tempVertexData.colors = new Float32Array(buffer.length);
  52075. tempVertexData.colors.set(buffer);
  52076. }
  52077. }
  52078. // Indices
  52079. accessor = gltfRuntime.accessors[primitive.indices];
  52080. if (accessor) {
  52081. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52082. tempVertexData.indices = new Int32Array(buffer.length);
  52083. tempVertexData.indices.set(buffer);
  52084. indexCounts.push(tempVertexData.indices.length);
  52085. }
  52086. else {
  52087. // Set indices on the fly
  52088. var indices = [];
  52089. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  52090. indices.push(j);
  52091. }
  52092. tempVertexData.indices = new Int32Array(indices);
  52093. indexCounts.push(tempVertexData.indices.length);
  52094. }
  52095. vertexData.merge(tempVertexData);
  52096. tempVertexData = undefined;
  52097. // Sub material
  52098. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  52099. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  52100. // Update vertices start and index start
  52101. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  52102. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  52103. }
  52104. }
  52105. // Apply geometry
  52106. geometry.setAllVerticesData(vertexData, false);
  52107. newMesh.computeWorldMatrix(true);
  52108. // Apply submeshes
  52109. newMesh.subMeshes = [];
  52110. var index = 0;
  52111. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  52112. var meshID = meshes[meshIndex];
  52113. var mesh = gltfRuntime.meshes[meshID];
  52114. if (!mesh) {
  52115. continue;
  52116. }
  52117. for (var i = 0; i < mesh.primitives.length; i++) {
  52118. if (mesh.primitives[i].mode !== 4) {
  52119. //continue;
  52120. }
  52121. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  52122. index++;
  52123. }
  52124. }
  52125. // Finish
  52126. return newMesh;
  52127. };
  52128. /**
  52129. * Configure node transformation from position, rotation and scaling
  52130. */
  52131. var configureNode = function (newNode, position, rotation, scaling) {
  52132. if (newNode.position) {
  52133. newNode.position = position;
  52134. }
  52135. if (newNode.rotationQuaternion || newNode.rotation) {
  52136. newNode.rotationQuaternion = rotation;
  52137. }
  52138. if (newNode.scaling) {
  52139. newNode.scaling = scaling;
  52140. }
  52141. };
  52142. /**
  52143. * Configures node from transformation matrix
  52144. */
  52145. var configureNodeFromMatrix = function (newNode, node, parent) {
  52146. if (node.matrix) {
  52147. var position = new BABYLON.Vector3(0, 0, 0);
  52148. var rotation = new BABYLON.Quaternion();
  52149. var scaling = new BABYLON.Vector3(0, 0, 0);
  52150. var mat = BABYLON.Matrix.FromArray(node.matrix);
  52151. mat.decompose(scaling, rotation, position);
  52152. configureNode(newNode, position, rotation, scaling);
  52153. }
  52154. else {
  52155. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  52156. }
  52157. newNode.computeWorldMatrix(true);
  52158. };
  52159. /**
  52160. * Imports a node
  52161. */
  52162. var importNode = function (gltfRuntime, node, id, parent) {
  52163. var lastNode = null;
  52164. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  52165. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  52166. return null;
  52167. }
  52168. }
  52169. // Meshes
  52170. if (node.skin) {
  52171. if (node.meshes) {
  52172. var skin = gltfRuntime.skins[node.skin];
  52173. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  52174. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  52175. if (newMesh.skeleton === null) {
  52176. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  52177. if (!skin.babylonSkeleton) {
  52178. skin.babylonSkeleton = newMesh.skeleton;
  52179. }
  52180. }
  52181. lastNode = newMesh;
  52182. }
  52183. }
  52184. else if (node.meshes) {
  52185. /**
  52186. * Improve meshes property
  52187. */
  52188. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  52189. lastNode = newMesh;
  52190. }
  52191. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  52192. var light = gltfRuntime.lights[node.light];
  52193. if (light) {
  52194. if (light.type === "ambient") {
  52195. var ambienLight = light[light.type];
  52196. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52197. hemiLight.name = node.name;
  52198. if (ambienLight.color) {
  52199. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  52200. }
  52201. lastNode = hemiLight;
  52202. }
  52203. else if (light.type === "directional") {
  52204. var directionalLight = light[light.type];
  52205. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52206. dirLight.name = node.name;
  52207. if (directionalLight.color) {
  52208. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  52209. }
  52210. lastNode = dirLight;
  52211. }
  52212. else if (light.type === "point") {
  52213. var pointLight = light[light.type];
  52214. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52215. ptLight.name = node.name;
  52216. if (pointLight.color) {
  52217. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  52218. }
  52219. lastNode = ptLight;
  52220. }
  52221. else if (light.type === "spot") {
  52222. var spotLight = light[light.type];
  52223. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  52224. spLight.name = node.name;
  52225. if (spotLight.color) {
  52226. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  52227. }
  52228. if (spotLight.fallOfAngle) {
  52229. spLight.angle = spotLight.fallOfAngle;
  52230. }
  52231. if (spotLight.fallOffExponent) {
  52232. spLight.exponent = spotLight.fallOffExponent;
  52233. }
  52234. lastNode = spLight;
  52235. }
  52236. }
  52237. }
  52238. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  52239. var camera = gltfRuntime.cameras[node.camera];
  52240. if (camera) {
  52241. if (camera.type === "orthographic") {
  52242. var orthographicCamera = camera[camera.type];
  52243. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52244. orthoCamera.name = node.name;
  52245. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  52246. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  52247. lastNode = orthoCamera;
  52248. }
  52249. else if (camera.type === "perspective") {
  52250. var perspectiveCamera = camera[camera.type];
  52251. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52252. persCamera.name = node.name;
  52253. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  52254. if (!perspectiveCamera.aspectRatio) {
  52255. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  52256. }
  52257. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  52258. persCamera.maxZ = perspectiveCamera.zfar;
  52259. persCamera.minZ = perspectiveCamera.znear;
  52260. }
  52261. lastNode = persCamera;
  52262. }
  52263. }
  52264. }
  52265. // Empty node
  52266. if (!node.jointName) {
  52267. if (node.babylonNode) {
  52268. return node.babylonNode;
  52269. }
  52270. else if (lastNode === null) {
  52271. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  52272. node.babylonNode = dummy;
  52273. lastNode = dummy;
  52274. }
  52275. }
  52276. if (lastNode !== null) {
  52277. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  52278. configureNodeFromMatrix(lastNode, node, parent);
  52279. }
  52280. else {
  52281. var translation = node.translation || [0, 0, 0];
  52282. var rotation = node.rotation || [0, 0, 0, 1];
  52283. var scale = node.scale || [1, 1, 1];
  52284. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  52285. }
  52286. lastNode.updateCache(true);
  52287. node.babylonNode = lastNode;
  52288. }
  52289. return lastNode;
  52290. };
  52291. /**
  52292. * Traverses nodes and creates them
  52293. */
  52294. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  52295. var node = gltfRuntime.nodes[id];
  52296. var newNode = null;
  52297. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  52298. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  52299. meshIncluded = true;
  52300. }
  52301. else {
  52302. meshIncluded = false;
  52303. }
  52304. }
  52305. else {
  52306. meshIncluded = true;
  52307. }
  52308. if (!node.jointName && meshIncluded) {
  52309. newNode = importNode(gltfRuntime, node, id, parent);
  52310. if (newNode !== null) {
  52311. newNode.id = id;
  52312. newNode.parent = parent;
  52313. }
  52314. }
  52315. if (node.children) {
  52316. for (var i = 0; i < node.children.length; i++) {
  52317. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  52318. }
  52319. }
  52320. };
  52321. /**
  52322. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  52323. */
  52324. var postLoad = function (gltfRuntime) {
  52325. // Nodes
  52326. var currentScene = gltfRuntime.currentScene;
  52327. if (currentScene) {
  52328. for (var i = 0; i < currentScene.nodes.length; i++) {
  52329. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52330. }
  52331. }
  52332. else {
  52333. for (var thing in gltfRuntime.scenes) {
  52334. currentScene = gltfRuntime.scenes[thing];
  52335. for (var i = 0; i < currentScene.nodes.length; i++) {
  52336. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52337. }
  52338. }
  52339. }
  52340. // Set animations
  52341. loadAnimations(gltfRuntime);
  52342. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  52343. var skeleton = gltfRuntime.scene.skeletons[i];
  52344. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  52345. }
  52346. };
  52347. /**
  52348. * onBind shaderrs callback to set uniforms and matrices
  52349. */
  52350. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  52351. var materialValues = material.values || technique.parameters;
  52352. for (var unif in unTreatedUniforms) {
  52353. var uniform = unTreatedUniforms[unif];
  52354. var type = uniform.type;
  52355. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  52356. if (uniform.semantic && !uniform.source && !uniform.node) {
  52357. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  52358. }
  52359. else if (uniform.semantic && (uniform.source || uniform.node)) {
  52360. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  52361. if (source === null) {
  52362. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  52363. }
  52364. if (source === null) {
  52365. continue;
  52366. }
  52367. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  52368. }
  52369. }
  52370. else {
  52371. var value = materialValues[technique.uniforms[unif]];
  52372. if (!value) {
  52373. continue;
  52374. }
  52375. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  52376. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  52377. if (texture === null || texture === undefined) {
  52378. continue;
  52379. }
  52380. shaderMaterial.getEffect().setTexture(unif, texture);
  52381. }
  52382. else {
  52383. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  52384. }
  52385. }
  52386. }
  52387. onSuccess(shaderMaterial);
  52388. };
  52389. /**
  52390. * Prepare uniforms to send the only one time
  52391. * Loads the appropriate textures
  52392. */
  52393. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  52394. var materialValues = material.values || technique.parameters;
  52395. var techniqueUniforms = technique.uniforms;
  52396. /**
  52397. * Prepare values here (not matrices)
  52398. */
  52399. for (var unif in unTreatedUniforms) {
  52400. var uniform = unTreatedUniforms[unif];
  52401. var type = uniform.type;
  52402. var value = materialValues[techniqueUniforms[unif]];
  52403. if (value === undefined) {
  52404. // In case the value is the same for all materials
  52405. value = uniform.value;
  52406. }
  52407. if (!value) {
  52408. continue;
  52409. }
  52410. var onLoadTexture = function (uniformName) {
  52411. return function (texture) {
  52412. if (uniform.value) {
  52413. // Static uniform
  52414. shaderMaterial.setTexture(uniformName, texture);
  52415. delete unTreatedUniforms[uniformName];
  52416. }
  52417. };
  52418. };
  52419. // Texture (sampler2D)
  52420. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  52421. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  52422. }
  52423. else {
  52424. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  52425. // Static uniform
  52426. delete unTreatedUniforms[unif];
  52427. }
  52428. }
  52429. }
  52430. };
  52431. /**
  52432. * Shader compilation failed
  52433. */
  52434. var onShaderCompileError = function (program, shaderMaterial, onError) {
  52435. return function (effect, error) {
  52436. shaderMaterial.dispose(true);
  52437. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  52438. };
  52439. };
  52440. /**
  52441. * Shader compilation success
  52442. */
  52443. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  52444. return function (_) {
  52445. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  52446. shaderMaterial.onBind = function (mesh) {
  52447. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  52448. };
  52449. };
  52450. };
  52451. /**
  52452. * Returns the appropriate uniform if already handled by babylon
  52453. */
  52454. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  52455. for (var unif in technique.uniforms) {
  52456. var uniform = technique.uniforms[unif];
  52457. var uniformParameter = technique.parameters[uniform];
  52458. if (tokenizer.currentIdentifier === unif) {
  52459. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  52460. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  52461. if (transformIndex !== -1) {
  52462. delete unTreatedUniforms[unif];
  52463. return babylonTransforms[transformIndex];
  52464. }
  52465. }
  52466. }
  52467. }
  52468. return tokenizer.currentIdentifier;
  52469. };
  52470. /**
  52471. * All shaders loaded. Create materials one by one
  52472. */
  52473. var importMaterials = function (gltfRuntime) {
  52474. // Create materials
  52475. for (var mat in gltfRuntime.materials) {
  52476. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  52477. }
  52478. };
  52479. /**
  52480. * Implementation of the base glTF spec
  52481. */
  52482. var GLTFLoaderBase = (function () {
  52483. function GLTFLoaderBase() {
  52484. }
  52485. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  52486. var gltfRuntime = {
  52487. extensions: {},
  52488. accessors: {},
  52489. buffers: {},
  52490. bufferViews: {},
  52491. meshes: {},
  52492. lights: {},
  52493. cameras: {},
  52494. nodes: {},
  52495. images: {},
  52496. textures: {},
  52497. shaders: {},
  52498. programs: {},
  52499. samplers: {},
  52500. techniques: {},
  52501. materials: {},
  52502. animations: {},
  52503. skins: {},
  52504. extensionsUsed: [],
  52505. scenes: {},
  52506. buffersCount: 0,
  52507. shaderscount: 0,
  52508. scene: scene,
  52509. rootUrl: rootUrl,
  52510. loadedBufferCount: 0,
  52511. loadedBufferViews: {},
  52512. loadedShaderCount: 0,
  52513. importOnlyMeshes: false,
  52514. dummyNodes: []
  52515. };
  52516. // Parse
  52517. if (parsedData.extensions) {
  52518. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  52519. }
  52520. if (parsedData.extensionsUsed) {
  52521. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  52522. }
  52523. if (parsedData.buffers) {
  52524. parseBuffers(parsedData.buffers, gltfRuntime);
  52525. }
  52526. if (parsedData.bufferViews) {
  52527. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  52528. }
  52529. if (parsedData.accessors) {
  52530. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  52531. }
  52532. if (parsedData.meshes) {
  52533. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  52534. }
  52535. if (parsedData.lights) {
  52536. parseObject(parsedData.lights, "lights", gltfRuntime);
  52537. }
  52538. if (parsedData.cameras) {
  52539. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  52540. }
  52541. if (parsedData.nodes) {
  52542. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  52543. }
  52544. if (parsedData.images) {
  52545. parseObject(parsedData.images, "images", gltfRuntime);
  52546. }
  52547. if (parsedData.textures) {
  52548. parseObject(parsedData.textures, "textures", gltfRuntime);
  52549. }
  52550. if (parsedData.shaders) {
  52551. parseShaders(parsedData.shaders, gltfRuntime);
  52552. }
  52553. if (parsedData.programs) {
  52554. parseObject(parsedData.programs, "programs", gltfRuntime);
  52555. }
  52556. if (parsedData.samplers) {
  52557. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  52558. }
  52559. if (parsedData.techniques) {
  52560. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  52561. }
  52562. if (parsedData.materials) {
  52563. parseObject(parsedData.materials, "materials", gltfRuntime);
  52564. }
  52565. if (parsedData.animations) {
  52566. parseObject(parsedData.animations, "animations", gltfRuntime);
  52567. }
  52568. if (parsedData.skins) {
  52569. parseObject(parsedData.skins, "skins", gltfRuntime);
  52570. }
  52571. if (parsedData.scenes) {
  52572. gltfRuntime.scenes = parsedData.scenes;
  52573. }
  52574. if (parsedData.scene && parsedData.scenes) {
  52575. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  52576. }
  52577. return gltfRuntime;
  52578. };
  52579. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  52580. var buffer = gltfRuntime.buffers[id];
  52581. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  52582. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  52583. }
  52584. else {
  52585. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  52586. onError(request.status + " " + request.statusText);
  52587. });
  52588. }
  52589. };
  52590. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  52591. var texture = gltfRuntime.textures[id];
  52592. if (!texture || !texture.source) {
  52593. onError(null);
  52594. return;
  52595. }
  52596. if (texture.babylonTexture) {
  52597. onSuccess(null);
  52598. return;
  52599. }
  52600. var source = gltfRuntime.images[texture.source];
  52601. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  52602. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  52603. }
  52604. else {
  52605. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  52606. onError(request.status + " " + request.statusText);
  52607. });
  52608. }
  52609. };
  52610. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  52611. var texture = gltfRuntime.textures[id];
  52612. if (texture.babylonTexture) {
  52613. onSuccess(texture.babylonTexture);
  52614. return;
  52615. }
  52616. var sampler = gltfRuntime.samplers[texture.sampler];
  52617. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  52618. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  52619. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  52620. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  52621. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  52622. var blob = new Blob([buffer]);
  52623. var blobURL = URL.createObjectURL(blob);
  52624. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  52625. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  52626. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  52627. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  52628. newTexture.name = id;
  52629. texture.babylonTexture = newTexture;
  52630. onSuccess(newTexture);
  52631. };
  52632. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  52633. var shader = gltfRuntime.shaders[id];
  52634. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  52635. var shaderString = atob(shader.uri.split(",")[1]);
  52636. onSuccess(shaderString);
  52637. }
  52638. else {
  52639. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  52640. onError(request.status + " " + request.statusText);
  52641. });
  52642. }
  52643. };
  52644. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  52645. var material = gltfRuntime.materials[id];
  52646. var technique = gltfRuntime.techniques[material.technique];
  52647. if (!technique) {
  52648. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  52649. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  52650. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  52651. onSuccess(defaultMaterial);
  52652. return;
  52653. }
  52654. var program = gltfRuntime.programs[technique.program];
  52655. var states = technique.states;
  52656. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  52657. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  52658. var newVertexShader = "";
  52659. var newPixelShader = "";
  52660. var vertexTokenizer = new Tokenizer(vertexShader);
  52661. var pixelTokenizer = new Tokenizer(pixelShader);
  52662. var unTreatedUniforms = {};
  52663. var uniforms = [];
  52664. var attributes = [];
  52665. var samplers = [];
  52666. // Fill uniform, sampler2D and attributes
  52667. for (var unif in technique.uniforms) {
  52668. var uniform = technique.uniforms[unif];
  52669. var uniformParameter = technique.parameters[uniform];
  52670. unTreatedUniforms[unif] = uniformParameter;
  52671. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  52672. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  52673. if (transformIndex !== -1) {
  52674. uniforms.push(babylonTransforms[transformIndex]);
  52675. delete unTreatedUniforms[unif];
  52676. }
  52677. else {
  52678. uniforms.push(unif);
  52679. }
  52680. }
  52681. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  52682. samplers.push(unif);
  52683. }
  52684. else {
  52685. uniforms.push(unif);
  52686. }
  52687. }
  52688. for (var attr in technique.attributes) {
  52689. var attribute = technique.attributes[attr];
  52690. var attributeParameter = technique.parameters[attribute];
  52691. if (attributeParameter.semantic) {
  52692. attributes.push(getAttribute(attributeParameter));
  52693. }
  52694. }
  52695. // Configure vertex shader
  52696. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  52697. var tokenType = vertexTokenizer.currentToken;
  52698. if (tokenType !== ETokenType.IDENTIFIER) {
  52699. newVertexShader += vertexTokenizer.currentString;
  52700. continue;
  52701. }
  52702. var foundAttribute = false;
  52703. for (var attr in technique.attributes) {
  52704. var attribute = technique.attributes[attr];
  52705. var attributeParameter = technique.parameters[attribute];
  52706. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  52707. newVertexShader += getAttribute(attributeParameter);
  52708. foundAttribute = true;
  52709. break;
  52710. }
  52711. }
  52712. if (foundAttribute) {
  52713. continue;
  52714. }
  52715. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  52716. }
  52717. // Configure pixel shader
  52718. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  52719. var tokenType = pixelTokenizer.currentToken;
  52720. if (tokenType !== ETokenType.IDENTIFIER) {
  52721. newPixelShader += pixelTokenizer.currentString;
  52722. continue;
  52723. }
  52724. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  52725. }
  52726. // Create shader material
  52727. var shaderPath = {
  52728. vertex: program.vertexShader + id,
  52729. fragment: program.fragmentShader + id
  52730. };
  52731. var options = {
  52732. attributes: attributes,
  52733. uniforms: uniforms,
  52734. samplers: samplers,
  52735. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  52736. };
  52737. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  52738. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  52739. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  52740. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  52741. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  52742. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  52743. if (states && states.functions) {
  52744. var functions = states.functions;
  52745. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  52746. shaderMaterial.backFaceCulling = false;
  52747. }
  52748. var blendFunc = functions.blendFuncSeparate;
  52749. if (blendFunc) {
  52750. 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) {
  52751. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  52752. }
  52753. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52754. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  52755. }
  52756. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52757. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  52758. }
  52759. 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) {
  52760. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  52761. }
  52762. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52763. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  52764. }
  52765. 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) {
  52766. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  52767. }
  52768. }
  52769. }
  52770. };
  52771. return GLTFLoaderBase;
  52772. }());
  52773. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  52774. /**
  52775. * glTF V1 Loader
  52776. */
  52777. var GLTFLoader = (function () {
  52778. function GLTFLoader() {
  52779. }
  52780. GLTFLoader.RegisterExtension = function (extension) {
  52781. if (GLTFLoader.Extensions[extension.name]) {
  52782. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  52783. return;
  52784. }
  52785. GLTFLoader.Extensions[extension.name] = extension;
  52786. };
  52787. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  52788. var _this = this;
  52789. scene.useRightHandedSystem = true;
  52790. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  52791. gltfRuntime.importOnlyMeshes = true;
  52792. if (meshesNames === "") {
  52793. gltfRuntime.importMeshesNames = [];
  52794. }
  52795. else if (typeof meshesNames === "string") {
  52796. gltfRuntime.importMeshesNames = [meshesNames];
  52797. }
  52798. else if (meshesNames && !(meshesNames instanceof Array)) {
  52799. gltfRuntime.importMeshesNames = [meshesNames];
  52800. }
  52801. else {
  52802. gltfRuntime.importMeshesNames = [];
  52803. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  52804. }
  52805. // Create nodes
  52806. _this._createNodes(gltfRuntime);
  52807. var meshes = [];
  52808. var skeletons = [];
  52809. // Fill arrays of meshes and skeletons
  52810. for (var nde in gltfRuntime.nodes) {
  52811. var node = gltfRuntime.nodes[nde];
  52812. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  52813. meshes.push(node.babylonNode);
  52814. }
  52815. }
  52816. for (var skl in gltfRuntime.skins) {
  52817. var skin = gltfRuntime.skins[skl];
  52818. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  52819. skeletons.push(skin.babylonSkeleton);
  52820. }
  52821. }
  52822. // Load buffers, shaders, materials, etc.
  52823. _this._loadBuffersAsync(gltfRuntime, function () {
  52824. _this._loadShadersAsync(gltfRuntime, function () {
  52825. importMaterials(gltfRuntime);
  52826. postLoad(gltfRuntime);
  52827. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  52828. onSuccess(meshes, null, skeletons);
  52829. }
  52830. });
  52831. }, onProgress);
  52832. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  52833. onSuccess(meshes, null, skeletons);
  52834. }
  52835. }, onError);
  52836. return true;
  52837. };
  52838. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  52839. var _this = this;
  52840. scene.useRightHandedSystem = true;
  52841. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  52842. // Load runtime extensios
  52843. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  52844. // Create nodes
  52845. _this._createNodes(gltfRuntime);
  52846. // Load buffers, shaders, materials, etc.
  52847. _this._loadBuffersAsync(gltfRuntime, function () {
  52848. _this._loadShadersAsync(gltfRuntime, function () {
  52849. importMaterials(gltfRuntime);
  52850. postLoad(gltfRuntime);
  52851. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  52852. onSuccess();
  52853. }
  52854. });
  52855. });
  52856. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  52857. onSuccess();
  52858. }
  52859. }, onError);
  52860. }, onError);
  52861. };
  52862. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  52863. var hasShaders = false;
  52864. var processShader = function (sha, shader) {
  52865. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  52866. gltfRuntime.loadedShaderCount++;
  52867. if (shaderString) {
  52868. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  52869. }
  52870. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  52871. onload();
  52872. }
  52873. }, function () {
  52874. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  52875. });
  52876. };
  52877. for (var sha in gltfRuntime.shaders) {
  52878. hasShaders = true;
  52879. var shader = gltfRuntime.shaders[sha];
  52880. if (shader) {
  52881. processShader.bind(this, sha, shader)();
  52882. }
  52883. else {
  52884. BABYLON.Tools.Error("No shader named: " + sha);
  52885. }
  52886. }
  52887. if (!hasShaders) {
  52888. onload();
  52889. }
  52890. };
  52891. ;
  52892. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  52893. var hasBuffers = false;
  52894. var processBuffer = function (buf, buffer) {
  52895. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  52896. gltfRuntime.loadedBufferCount++;
  52897. if (bufferView) {
  52898. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  52899. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  52900. }
  52901. gltfRuntime.loadedBufferViews[buf] = bufferView;
  52902. }
  52903. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  52904. onLoad();
  52905. }
  52906. }, function () {
  52907. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  52908. });
  52909. };
  52910. for (var buf in gltfRuntime.buffers) {
  52911. hasBuffers = true;
  52912. var buffer = gltfRuntime.buffers[buf];
  52913. if (buffer) {
  52914. processBuffer.bind(this, buf, buffer)();
  52915. }
  52916. else {
  52917. BABYLON.Tools.Error("No buffer named: " + buf);
  52918. }
  52919. }
  52920. if (!hasBuffers) {
  52921. onLoad();
  52922. }
  52923. };
  52924. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  52925. var currentScene = gltfRuntime.currentScene;
  52926. if (currentScene) {
  52927. // Only one scene even if multiple scenes are defined
  52928. for (var i = 0; i < currentScene.nodes.length; i++) {
  52929. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52930. }
  52931. }
  52932. else {
  52933. // Load all scenes
  52934. for (var thing in gltfRuntime.scenes) {
  52935. currentScene = gltfRuntime.scenes[thing];
  52936. for (var i = 0; i < currentScene.nodes.length; i++) {
  52937. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52938. }
  52939. }
  52940. }
  52941. };
  52942. GLTFLoader.Extensions = {};
  52943. return GLTFLoader;
  52944. }());
  52945. GLTF1.GLTFLoader = GLTFLoader;
  52946. ;
  52947. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  52948. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  52949. })(BABYLON || (BABYLON = {}));
  52950. //# sourceMappingURL=babylon.glTFLoader.js.map
  52951. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  52952. var BABYLON;
  52953. (function (BABYLON) {
  52954. var GLTF1;
  52955. (function (GLTF1) {
  52956. /**
  52957. * Utils functions for GLTF
  52958. */
  52959. var GLTFUtils = (function () {
  52960. function GLTFUtils() {
  52961. }
  52962. /**
  52963. * Sets the given "parameter" matrix
  52964. * @param scene: the {BABYLON.Scene} object
  52965. * @param source: the source node where to pick the matrix
  52966. * @param parameter: the GLTF technique parameter
  52967. * @param uniformName: the name of the shader's uniform
  52968. * @param shaderMaterial: the shader material
  52969. */
  52970. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  52971. var mat = null;
  52972. if (parameter.semantic === "MODEL") {
  52973. mat = source.getWorldMatrix();
  52974. }
  52975. else if (parameter.semantic === "PROJECTION") {
  52976. mat = scene.getProjectionMatrix();
  52977. }
  52978. else if (parameter.semantic === "VIEW") {
  52979. mat = scene.getViewMatrix();
  52980. }
  52981. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  52982. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  52983. }
  52984. else if (parameter.semantic === "MODELVIEW") {
  52985. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  52986. }
  52987. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  52988. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  52989. }
  52990. else if (parameter.semantic === "MODELINVERSE") {
  52991. mat = source.getWorldMatrix().invert();
  52992. }
  52993. else if (parameter.semantic === "VIEWINVERSE") {
  52994. mat = scene.getViewMatrix().invert();
  52995. }
  52996. else if (parameter.semantic === "PROJECTIONINVERSE") {
  52997. mat = scene.getProjectionMatrix().invert();
  52998. }
  52999. else if (parameter.semantic === "MODELVIEWINVERSE") {
  53000. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  53001. }
  53002. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  53003. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  53004. }
  53005. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  53006. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  53007. }
  53008. else {
  53009. debugger;
  53010. }
  53011. switch (parameter.type) {
  53012. case GLTF1.EParameterType.FLOAT_MAT2:
  53013. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  53014. break;
  53015. case GLTF1.EParameterType.FLOAT_MAT3:
  53016. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  53017. break;
  53018. case GLTF1.EParameterType.FLOAT_MAT4:
  53019. shaderMaterial.setMatrix(uniformName, mat);
  53020. break;
  53021. default: break;
  53022. }
  53023. };
  53024. /**
  53025. * Sets the given "parameter" matrix
  53026. * @param shaderMaterial: the shader material
  53027. * @param uniform: the name of the shader's uniform
  53028. * @param value: the value of the uniform
  53029. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  53030. */
  53031. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  53032. switch (type) {
  53033. case GLTF1.EParameterType.FLOAT:
  53034. shaderMaterial.setFloat(uniform, value);
  53035. return true;
  53036. case GLTF1.EParameterType.FLOAT_VEC2:
  53037. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  53038. return true;
  53039. case GLTF1.EParameterType.FLOAT_VEC3:
  53040. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  53041. return true;
  53042. case GLTF1.EParameterType.FLOAT_VEC4:
  53043. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  53044. return true;
  53045. default: return false;
  53046. }
  53047. };
  53048. /**
  53049. * If the uri is a base64 string
  53050. * @param uri: the uri to test
  53051. */
  53052. GLTFUtils.IsBase64 = function (uri) {
  53053. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  53054. };
  53055. /**
  53056. * Decode the base64 uri
  53057. * @param uri: the uri to decode
  53058. */
  53059. GLTFUtils.DecodeBase64 = function (uri) {
  53060. var decodedString = atob(uri.split(",")[1]);
  53061. var bufferLength = decodedString.length;
  53062. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  53063. for (var i = 0; i < bufferLength; i++) {
  53064. bufferView[i] = decodedString.charCodeAt(i);
  53065. }
  53066. return bufferView.buffer;
  53067. };
  53068. /**
  53069. * Returns the wrap mode of the texture
  53070. * @param mode: the mode value
  53071. */
  53072. GLTFUtils.GetWrapMode = function (mode) {
  53073. switch (mode) {
  53074. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  53075. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  53076. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  53077. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  53078. }
  53079. };
  53080. /**
  53081. * Returns the byte stride giving an accessor
  53082. * @param accessor: the GLTF accessor objet
  53083. */
  53084. GLTFUtils.GetByteStrideFromType = function (accessor) {
  53085. // Needs this function since "byteStride" isn't requiered in glTF format
  53086. var type = accessor.type;
  53087. switch (type) {
  53088. case "VEC2": return 2;
  53089. case "VEC3": return 3;
  53090. case "VEC4": return 4;
  53091. case "MAT2": return 4;
  53092. case "MAT3": return 9;
  53093. case "MAT4": return 16;
  53094. default: return 1;
  53095. }
  53096. };
  53097. /**
  53098. * Returns the texture filter mode giving a mode value
  53099. * @param mode: the filter mode value
  53100. */
  53101. GLTFUtils.GetTextureFilterMode = function (mode) {
  53102. switch (mode) {
  53103. case GLTF1.ETextureFilterType.LINEAR:
  53104. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  53105. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  53106. case GLTF1.ETextureFilterType.NEAREST:
  53107. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  53108. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  53109. }
  53110. };
  53111. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  53112. var byteOffset = bufferView.byteOffset + byteOffset;
  53113. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  53114. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  53115. throw new Error("Buffer access is out of range");
  53116. }
  53117. var buffer = loadedBufferView.buffer;
  53118. byteOffset += loadedBufferView.byteOffset;
  53119. switch (componentType) {
  53120. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  53121. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  53122. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  53123. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  53124. default: return new Float32Array(buffer, byteOffset, byteLength);
  53125. }
  53126. };
  53127. /**
  53128. * Returns a buffer from its accessor
  53129. * @param gltfRuntime: the GLTF runtime
  53130. * @param accessor: the GLTF accessor
  53131. */
  53132. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  53133. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  53134. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  53135. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  53136. };
  53137. /**
  53138. * Decodes a buffer view into a string
  53139. * @param view: the buffer view
  53140. */
  53141. GLTFUtils.DecodeBufferToText = function (view) {
  53142. var result = "";
  53143. var length = view.byteLength;
  53144. for (var i = 0; i < length; ++i) {
  53145. result += String.fromCharCode(view[i]);
  53146. }
  53147. return result;
  53148. };
  53149. /**
  53150. * Returns the default material of gltf. Related to
  53151. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  53152. * @param scene: the Babylon.js scene
  53153. */
  53154. GLTFUtils.GetDefaultMaterial = function (scene) {
  53155. if (!GLTFUtils._DefaultMaterial) {
  53156. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  53157. "precision highp float;",
  53158. "",
  53159. "uniform mat4 worldView;",
  53160. "uniform mat4 projection;",
  53161. "",
  53162. "attribute vec3 position;",
  53163. "",
  53164. "void main(void)",
  53165. "{",
  53166. " gl_Position = projection * worldView * vec4(position, 1.0);",
  53167. "}"
  53168. ].join("\n");
  53169. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  53170. "precision highp float;",
  53171. "",
  53172. "uniform vec4 u_emission;",
  53173. "",
  53174. "void main(void)",
  53175. "{",
  53176. " gl_FragColor = u_emission;",
  53177. "}"
  53178. ].join("\n");
  53179. var shaderPath = {
  53180. vertex: "GLTFDefaultMaterial",
  53181. fragment: "GLTFDefaultMaterial"
  53182. };
  53183. var options = {
  53184. attributes: ["position"],
  53185. uniforms: ["worldView", "projection", "u_emission"],
  53186. samplers: [],
  53187. needAlphaBlending: false
  53188. };
  53189. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  53190. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  53191. }
  53192. return GLTFUtils._DefaultMaterial;
  53193. };
  53194. // The GLTF default material
  53195. GLTFUtils._DefaultMaterial = null;
  53196. return GLTFUtils;
  53197. }());
  53198. GLTF1.GLTFUtils = GLTFUtils;
  53199. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53200. })(BABYLON || (BABYLON = {}));
  53201. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  53202. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53203. var BABYLON;
  53204. (function (BABYLON) {
  53205. var GLTF1;
  53206. (function (GLTF1) {
  53207. var GLTFLoaderExtension = (function () {
  53208. function GLTFLoaderExtension(name) {
  53209. this._name = name;
  53210. }
  53211. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  53212. get: function () {
  53213. return this._name;
  53214. },
  53215. enumerable: true,
  53216. configurable: true
  53217. });
  53218. /**
  53219. * Defines an override for loading the runtime
  53220. * Return true to stop further extensions from loading the runtime
  53221. */
  53222. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53223. return false;
  53224. };
  53225. /**
  53226. * Defines an onverride for creating gltf runtime
  53227. * Return true to stop further extensions from creating the runtime
  53228. */
  53229. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53230. return false;
  53231. };
  53232. /**
  53233. * Defines an override for loading buffers
  53234. * Return true to stop further extensions from loading this buffer
  53235. */
  53236. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  53237. return false;
  53238. };
  53239. /**
  53240. * Defines an override for loading texture buffers
  53241. * Return true to stop further extensions from loading this texture data
  53242. */
  53243. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53244. return false;
  53245. };
  53246. /**
  53247. * Defines an override for creating textures
  53248. * Return true to stop further extensions from loading this texture
  53249. */
  53250. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  53251. return false;
  53252. };
  53253. /**
  53254. * Defines an override for loading shader strings
  53255. * Return true to stop further extensions from loading this shader data
  53256. */
  53257. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53258. return false;
  53259. };
  53260. /**
  53261. * Defines an override for loading materials
  53262. * Return true to stop further extensions from loading this material
  53263. */
  53264. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53265. return false;
  53266. };
  53267. // ---------
  53268. // Utilities
  53269. // ---------
  53270. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53271. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53272. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  53273. }, function () {
  53274. setTimeout(function () {
  53275. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  53276. });
  53277. });
  53278. };
  53279. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53280. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53281. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  53282. }, function () {
  53283. setTimeout(function () {
  53284. onSuccess();
  53285. });
  53286. });
  53287. };
  53288. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  53289. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53290. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  53291. }, function () {
  53292. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  53293. });
  53294. };
  53295. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  53296. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  53297. };
  53298. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53299. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53300. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  53301. }, function () {
  53302. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  53303. });
  53304. };
  53305. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53306. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53307. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  53308. }, function () {
  53309. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  53310. });
  53311. };
  53312. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53313. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53314. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  53315. }, function () {
  53316. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  53317. });
  53318. };
  53319. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  53320. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53321. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  53322. }, function () {
  53323. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  53324. });
  53325. };
  53326. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  53327. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  53328. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  53329. if (func(loaderExtension)) {
  53330. return;
  53331. }
  53332. }
  53333. defaultFunc();
  53334. };
  53335. return GLTFLoaderExtension;
  53336. }());
  53337. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  53338. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53339. })(BABYLON || (BABYLON = {}));
  53340. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  53341. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53342. var BABYLON;
  53343. (function (BABYLON) {
  53344. var GLTF1;
  53345. (function (GLTF1) {
  53346. var BinaryExtensionBufferName = "binary_glTF";
  53347. var EContentFormat;
  53348. (function (EContentFormat) {
  53349. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  53350. })(EContentFormat || (EContentFormat = {}));
  53351. ;
  53352. ;
  53353. ;
  53354. var GLTFBinaryExtension = (function (_super) {
  53355. __extends(GLTFBinaryExtension, _super);
  53356. function GLTFBinaryExtension() {
  53357. return _super.call(this, "KHR_binary_glTF") || this;
  53358. }
  53359. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53360. var extensionsUsed = data.json.extensionsUsed;
  53361. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  53362. return false;
  53363. }
  53364. this._bin = data.bin;
  53365. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  53366. return true;
  53367. };
  53368. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53369. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  53370. return false;
  53371. }
  53372. if (id !== BinaryExtensionBufferName) {
  53373. return false;
  53374. }
  53375. onSuccess(this._bin);
  53376. return true;
  53377. };
  53378. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53379. var texture = gltfRuntime.textures[id];
  53380. var source = gltfRuntime.images[texture.source];
  53381. if (!source.extensions || !(this.name in source.extensions)) {
  53382. return false;
  53383. }
  53384. var sourceExt = source.extensions[this.name];
  53385. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  53386. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  53387. onSuccess(buffer);
  53388. return true;
  53389. };
  53390. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53391. var shader = gltfRuntime.shaders[id];
  53392. if (!shader.extensions || !(this.name in shader.extensions)) {
  53393. return false;
  53394. }
  53395. var binaryExtensionShader = shader.extensions[this.name];
  53396. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  53397. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  53398. setTimeout(function () {
  53399. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  53400. onSuccess(shaderString);
  53401. });
  53402. return true;
  53403. };
  53404. return GLTFBinaryExtension;
  53405. }(GLTF1.GLTFLoaderExtension));
  53406. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  53407. var BinaryReader = (function () {
  53408. function BinaryReader(arrayBuffer) {
  53409. this._arrayBuffer = arrayBuffer;
  53410. this._dataView = new DataView(arrayBuffer);
  53411. this._byteOffset = 0;
  53412. }
  53413. BinaryReader.prototype.getUint32 = function () {
  53414. var value = this._dataView.getUint32(this._byteOffset, true);
  53415. this._byteOffset += 4;
  53416. return value;
  53417. };
  53418. BinaryReader.prototype.getUint8Array = function (length) {
  53419. if (!length) {
  53420. length = this._arrayBuffer.byteLength - this._byteOffset;
  53421. }
  53422. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  53423. this._byteOffset += length;
  53424. return value;
  53425. };
  53426. return BinaryReader;
  53427. }());
  53428. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  53429. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53430. })(BABYLON || (BABYLON = {}));
  53431. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  53432. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53433. var BABYLON;
  53434. (function (BABYLON) {
  53435. var GLTF1;
  53436. (function (GLTF1) {
  53437. ;
  53438. ;
  53439. ;
  53440. var GLTFMaterialsCommonExtension = (function (_super) {
  53441. __extends(GLTFMaterialsCommonExtension, _super);
  53442. function GLTFMaterialsCommonExtension() {
  53443. return _super.call(this, "KHR_materials_common") || this;
  53444. }
  53445. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53446. if (!gltfRuntime.extensions)
  53447. return false;
  53448. var extension = gltfRuntime.extensions[this.name];
  53449. if (!extension)
  53450. return false;
  53451. // Create lights
  53452. var lights = extension.lights;
  53453. if (lights) {
  53454. for (var thing in lights) {
  53455. var light = lights[thing];
  53456. switch (light.type) {
  53457. case "ambient":
  53458. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  53459. var ambient = light.ambient;
  53460. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  53461. break;
  53462. case "point":
  53463. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  53464. var point = light.point;
  53465. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  53466. break;
  53467. case "directional":
  53468. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  53469. var directional = light.directional;
  53470. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  53471. break;
  53472. case "spot":
  53473. var spot = light.spot;
  53474. 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);
  53475. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  53476. break;
  53477. default:
  53478. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  53479. break;
  53480. }
  53481. }
  53482. }
  53483. return false;
  53484. };
  53485. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53486. var material = gltfRuntime.materials[id];
  53487. if (!material || !material.extensions)
  53488. return false;
  53489. var extension = material.extensions[this.name];
  53490. if (!extension)
  53491. return false;
  53492. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  53493. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  53494. if (extension.technique === "CONSTANT") {
  53495. standardMaterial.disableLighting = true;
  53496. }
  53497. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  53498. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  53499. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  53500. // Ambient
  53501. if (typeof extension.values.ambient === "string") {
  53502. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  53503. }
  53504. else {
  53505. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  53506. }
  53507. // Diffuse
  53508. if (typeof extension.values.diffuse === "string") {
  53509. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  53510. }
  53511. else {
  53512. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  53513. }
  53514. // Emission
  53515. if (typeof extension.values.emission === "string") {
  53516. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  53517. }
  53518. else {
  53519. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  53520. }
  53521. // Specular
  53522. if (typeof extension.values.specular === "string") {
  53523. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  53524. }
  53525. else {
  53526. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  53527. }
  53528. return true;
  53529. };
  53530. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  53531. // Create buffer from texture url
  53532. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  53533. // Create texture from buffer
  53534. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  53535. }, onError);
  53536. };
  53537. return GLTFMaterialsCommonExtension;
  53538. }(GLTF1.GLTFLoaderExtension));
  53539. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  53540. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  53541. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53542. })(BABYLON || (BABYLON = {}));
  53543. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  53544. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53545. var BABYLON;
  53546. (function (BABYLON) {
  53547. var GLTF2;
  53548. (function (GLTF2) {
  53549. /**
  53550. * Enums
  53551. */
  53552. var EComponentType;
  53553. (function (EComponentType) {
  53554. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  53555. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  53556. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  53557. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  53558. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  53559. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  53560. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  53561. var EMeshPrimitiveMode;
  53562. (function (EMeshPrimitiveMode) {
  53563. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  53564. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  53565. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  53566. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  53567. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  53568. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  53569. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  53570. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  53571. var ETextureMagFilter;
  53572. (function (ETextureMagFilter) {
  53573. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  53574. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  53575. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  53576. var ETextureMinFilter;
  53577. (function (ETextureMinFilter) {
  53578. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  53579. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  53580. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  53581. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  53582. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  53583. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  53584. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  53585. var ETextureWrapMode;
  53586. (function (ETextureWrapMode) {
  53587. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  53588. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  53589. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  53590. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  53591. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  53592. })(BABYLON || (BABYLON = {}));
  53593. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  53594. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53595. var BABYLON;
  53596. (function (BABYLON) {
  53597. var GLTF2;
  53598. (function (GLTF2) {
  53599. var GLTFLoader = (function () {
  53600. function GLTFLoader(parent) {
  53601. this._renderReady = false;
  53602. this._disposed = false;
  53603. this._objectURLs = new Array();
  53604. this._blockPendingTracking = false;
  53605. // Observable with boolean indicating success or error.
  53606. this._renderReadyObservable = new BABYLON.Observable();
  53607. // Count of pending work that needs to complete before the asset is rendered.
  53608. this._renderPendingCount = 0;
  53609. // Count of pending work that needs to complete before the loader is cleared.
  53610. this._loaderPendingCount = 0;
  53611. this._parent = parent;
  53612. }
  53613. GLTFLoader.RegisterExtension = function (extension) {
  53614. if (GLTFLoader.Extensions[extension.name]) {
  53615. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  53616. return;
  53617. }
  53618. GLTFLoader.Extensions[extension.name] = extension;
  53619. // Keep the order of registration so that extensions registered first are called first.
  53620. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  53621. };
  53622. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  53623. get: function () {
  53624. return this._gltf;
  53625. },
  53626. enumerable: true,
  53627. configurable: true
  53628. });
  53629. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  53630. get: function () {
  53631. return this._babylonScene;
  53632. },
  53633. enumerable: true,
  53634. configurable: true
  53635. });
  53636. GLTFLoader.prototype.executeWhenRenderReady = function (func) {
  53637. if (this._renderReady) {
  53638. func();
  53639. }
  53640. else {
  53641. this._renderReadyObservable.add(func);
  53642. }
  53643. };
  53644. GLTFLoader.prototype.dispose = function () {
  53645. if (this._disposed) {
  53646. return;
  53647. }
  53648. this._disposed = true;
  53649. // Revoke object urls created during load
  53650. this._objectURLs.forEach(function (url) { return URL.revokeObjectURL(url); });
  53651. this._objectURLs.length = 0;
  53652. this._gltf = undefined;
  53653. this._babylonScene = undefined;
  53654. this._rootUrl = undefined;
  53655. this._defaultMaterial = undefined;
  53656. this._successCallback = undefined;
  53657. this._errorCallback = undefined;
  53658. this._renderReady = false;
  53659. this._renderReadyObservable.clear();
  53660. this._renderPendingCount = 0;
  53661. this._loaderPendingCount = 0;
  53662. };
  53663. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53664. var _this = this;
  53665. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  53666. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  53667. }, onProgress, onError);
  53668. };
  53669. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  53670. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  53671. };
  53672. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53673. this._loadData(data);
  53674. this._babylonScene = scene;
  53675. this._rootUrl = rootUrl;
  53676. this._successCallback = onSuccess;
  53677. this._progressCallback = onProgress;
  53678. this._errorCallback = onError;
  53679. this.addPendingData(this);
  53680. this._loadScene(nodeNames);
  53681. this._loadAnimations();
  53682. this.removePendingData(this);
  53683. };
  53684. GLTFLoader.prototype._onError = function (message) {
  53685. this._errorCallback(message);
  53686. this.dispose();
  53687. };
  53688. GLTFLoader.prototype._onProgress = function (event) {
  53689. this._progressCallback(event);
  53690. };
  53691. GLTFLoader.prototype._onRenderReady = function () {
  53692. switch (this._parent.coordinateSystemMode) {
  53693. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  53694. if (!this._babylonScene.useRightHandedSystem) {
  53695. this._addRightHandToLeftHandRootTransform();
  53696. }
  53697. break;
  53698. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  53699. // do nothing
  53700. break;
  53701. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  53702. this._babylonScene.useRightHandedSystem = true;
  53703. break;
  53704. default:
  53705. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  53706. break;
  53707. }
  53708. this._showMeshes();
  53709. this._startAnimations();
  53710. this._successCallback();
  53711. this._renderReadyObservable.notifyObservers(this);
  53712. };
  53713. GLTFLoader.prototype._onLoaderComplete = function () {
  53714. if (this._parent.onComplete) {
  53715. this._parent.onComplete();
  53716. }
  53717. };
  53718. GLTFLoader.prototype._onLoaderFirstLODComplete = function () {
  53719. if (this._parent.onFirstLODComplete) {
  53720. this._parent.onFirstLODComplete();
  53721. }
  53722. };
  53723. GLTFLoader.prototype._loadData = function (data) {
  53724. this._gltf = data.json;
  53725. var binaryBuffer;
  53726. var buffers = this._gltf.buffers;
  53727. if (buffers.length > 0 && buffers[0].uri === undefined) {
  53728. binaryBuffer = buffers[0];
  53729. }
  53730. if (data.bin) {
  53731. if (binaryBuffer) {
  53732. if (binaryBuffer.byteLength != data.bin.byteLength) {
  53733. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  53734. }
  53735. }
  53736. else {
  53737. BABYLON.Tools.Warn("Unexpected BIN chunk");
  53738. }
  53739. binaryBuffer.loadedData = data.bin;
  53740. }
  53741. };
  53742. GLTFLoader.prototype._addRightHandToLeftHandRootTransform = function () {
  53743. var rootMesh = new BABYLON.Mesh("root", this._babylonScene);
  53744. rootMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  53745. rootMesh.rotation.y = Math.PI;
  53746. var nodes = this._gltf.nodes;
  53747. for (var i = 0; i < nodes.length; i++) {
  53748. var mesh = nodes[i].babylonMesh;
  53749. if (mesh && !mesh.parent) {
  53750. mesh.parent = rootMesh;
  53751. }
  53752. }
  53753. };
  53754. GLTFLoader.prototype._getMeshes = function () {
  53755. var meshes = [];
  53756. var nodes = this._gltf.nodes;
  53757. if (nodes) {
  53758. nodes.forEach(function (node) {
  53759. if (node.babylonMesh) {
  53760. meshes.push(node.babylonMesh);
  53761. }
  53762. });
  53763. }
  53764. return meshes;
  53765. };
  53766. GLTFLoader.prototype._getSkeletons = function () {
  53767. var skeletons = [];
  53768. var skins = this._gltf.skins;
  53769. if (skins) {
  53770. skins.forEach(function (skin) {
  53771. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  53772. skeletons.push(skin.babylonSkeleton);
  53773. }
  53774. });
  53775. }
  53776. return skeletons;
  53777. };
  53778. GLTFLoader.prototype._getAnimationTargets = function () {
  53779. var targets = [];
  53780. var animations = this._gltf.animations;
  53781. if (animations) {
  53782. animations.forEach(function (animation) {
  53783. targets.push.apply(targets, animation.targets);
  53784. });
  53785. }
  53786. return targets;
  53787. };
  53788. GLTFLoader.prototype._showMeshes = function () {
  53789. this._getMeshes().forEach(function (mesh) { return mesh.isVisible = true; });
  53790. };
  53791. GLTFLoader.prototype._startAnimations = function () {
  53792. var _this = this;
  53793. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  53794. };
  53795. GLTFLoader.prototype._loadScene = function (nodeNames) {
  53796. var _this = this;
  53797. var scene = this._gltf.scenes[this._gltf.scene || 0];
  53798. var nodeIndices = scene.nodes;
  53799. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  53800. node.index = index;
  53801. node.parent = parentNode;
  53802. return true;
  53803. });
  53804. var materials = this._gltf.materials;
  53805. if (materials) {
  53806. materials.forEach(function (material, index) { return material.index = index; });
  53807. }
  53808. if (nodeNames) {
  53809. if (!(nodeNames instanceof Array)) {
  53810. nodeNames = [nodeNames];
  53811. }
  53812. var filteredNodeIndices = new Array();
  53813. this._traverseNodes(nodeIndices, function (node) {
  53814. if (nodeNames.indexOf(node.name) === -1) {
  53815. return true;
  53816. }
  53817. filteredNodeIndices.push(node.index);
  53818. return false;
  53819. });
  53820. nodeIndices = filteredNodeIndices;
  53821. }
  53822. this._traverseNodes(nodeIndices, function (node) { return _this._loadSkin(node); });
  53823. this._traverseNodes(nodeIndices, function (node) { return _this._loadMesh(node); });
  53824. };
  53825. GLTFLoader.prototype._loadSkin = function (node) {
  53826. var _this = this;
  53827. if (node.skin !== undefined) {
  53828. var skin = this._gltf.skins[node.skin];
  53829. var skeletonId = "skeleton" + node.skin;
  53830. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  53831. skin.index = node.skin;
  53832. for (var i = 0; i < skin.joints.length; i++) {
  53833. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  53834. }
  53835. if (skin.skeleton === undefined) {
  53836. // TODO: handle when skeleton is not defined
  53837. throw new Error("Not implemented");
  53838. }
  53839. if (skin.inverseBindMatrices === undefined) {
  53840. // TODO: handle when inverse bind matrices are not defined
  53841. throw new Error("Not implemented");
  53842. }
  53843. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  53844. this._loadAccessorAsync(accessor, function (data) {
  53845. _this._traverseNode(skin.skeleton, function (node, index, parent) { return _this._updateBone(node, parent, skin, data); });
  53846. });
  53847. }
  53848. return true;
  53849. };
  53850. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  53851. var jointIndex = skin.joints.indexOf(node.index);
  53852. if (jointIndex === -1) {
  53853. this._createBone(node, skin);
  53854. }
  53855. var babylonBone = node.babylonSkinToBones[skin.index];
  53856. // TODO: explain the math
  53857. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  53858. matrix.invertToRef(matrix);
  53859. if (parentNode) {
  53860. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  53861. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  53862. }
  53863. babylonBone.updateMatrix(matrix);
  53864. return true;
  53865. };
  53866. GLTFLoader.prototype._createBone = function (node, skin) {
  53867. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  53868. node.babylonSkinToBones = node.babylonSkinToBones || {};
  53869. node.babylonSkinToBones[skin.index] = babylonBone;
  53870. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  53871. node.babylonAnimationTargets.push(babylonBone);
  53872. return babylonBone;
  53873. };
  53874. GLTFLoader.prototype._loadMesh = function (node) {
  53875. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  53876. babylonMesh.isVisible = false;
  53877. this._loadTransform(node, babylonMesh);
  53878. if (node.mesh !== undefined) {
  53879. var mesh = this._gltf.meshes[node.mesh];
  53880. this._loadMeshData(node, mesh, babylonMesh);
  53881. }
  53882. babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  53883. node.babylonMesh = babylonMesh;
  53884. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  53885. node.babylonAnimationTargets.push(node.babylonMesh);
  53886. if (node.skin !== undefined) {
  53887. var skin = this._gltf.skins[node.skin];
  53888. babylonMesh.skeleton = skin.babylonSkeleton;
  53889. }
  53890. if (node.camera !== undefined) {
  53891. // TODO: handle cameras
  53892. }
  53893. return true;
  53894. };
  53895. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  53896. var _this = this;
  53897. babylonMesh.name = mesh.name || babylonMesh.name;
  53898. var babylonMultiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  53899. babylonMesh.material = babylonMultiMaterial;
  53900. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  53901. var vertexData = new BABYLON.VertexData();
  53902. vertexData.positions = [];
  53903. vertexData.indices = [];
  53904. var subMeshInfos = [];
  53905. var loadedPrimitives = 0;
  53906. var totalPrimitives = mesh.primitives.length;
  53907. var _loop_1 = function (i) {
  53908. var primitive = mesh.primitives[i];
  53909. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  53910. // TODO: handle other primitive modes
  53911. throw new Error("Not implemented");
  53912. }
  53913. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  53914. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  53915. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  53916. subMeshInfos.push({
  53917. materialIndex: i,
  53918. verticesStart: vertexData.positions.length,
  53919. verticesCount: subVertexData.positions.length,
  53920. indicesStart: vertexData.indices.length,
  53921. indicesCount: subVertexData.indices.length,
  53922. loadMaterial: function () {
  53923. if (primitive.material === undefined) {
  53924. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  53925. }
  53926. else {
  53927. var material = _this._gltf.materials[primitive.material];
  53928. _this.loadMaterial(material, function (babylonMaterial, isNew) {
  53929. if (isNew && _this._parent.onMaterialLoaded) {
  53930. _this._parent.onMaterialLoaded(babylonMaterial);
  53931. }
  53932. if (_this._parent.onBeforeMaterialReadyAsync) {
  53933. _this.addLoaderPendingData(material);
  53934. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  53935. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  53936. _this.removeLoaderPendingData(material);
  53937. });
  53938. }
  53939. else {
  53940. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  53941. }
  53942. });
  53943. }
  53944. }
  53945. });
  53946. vertexData.merge(subVertexData);
  53947. if (++loadedPrimitives === totalPrimitives) {
  53948. geometry.setAllVerticesData(vertexData, false);
  53949. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  53950. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  53951. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  53952. babylonMesh.subMeshes = [];
  53953. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh); });
  53954. }
  53955. });
  53956. };
  53957. var this_1 = this;
  53958. for (var i = 0; i < totalPrimitives; i++) {
  53959. _loop_1(i);
  53960. }
  53961. };
  53962. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  53963. var _this = this;
  53964. var attributes = primitive.attributes;
  53965. if (!attributes) {
  53966. this._onError("Primitive has no attributes");
  53967. return;
  53968. }
  53969. var vertexData = new BABYLON.VertexData();
  53970. var loadedAttributes = 0;
  53971. var totalAttributes = Object.keys(attributes).length;
  53972. var _loop_2 = function (semantic) {
  53973. accessor = this_2._gltf.accessors[attributes[semantic]];
  53974. this_2._loadAccessorAsync(accessor, function (data) {
  53975. switch (semantic) {
  53976. case "NORMAL":
  53977. vertexData.normals = data;
  53978. break;
  53979. case "POSITION":
  53980. vertexData.positions = data;
  53981. break;
  53982. case "TANGENT":
  53983. vertexData.tangents = data;
  53984. break;
  53985. case "TEXCOORD_0":
  53986. vertexData.uvs = data;
  53987. break;
  53988. case "TEXCOORD_1":
  53989. vertexData.uvs2 = data;
  53990. break;
  53991. case "JOINTS_0":
  53992. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  53993. break;
  53994. case "WEIGHTS_0":
  53995. vertexData.matricesWeights = data;
  53996. break;
  53997. case "COLOR_0":
  53998. vertexData.colors = data;
  53999. break;
  54000. default:
  54001. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  54002. break;
  54003. }
  54004. if (++loadedAttributes === totalAttributes) {
  54005. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  54006. if (indicesAccessor) {
  54007. _this._loadAccessorAsync(indicesAccessor, function (data) {
  54008. vertexData.indices = data;
  54009. onSuccess(vertexData);
  54010. });
  54011. }
  54012. else {
  54013. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  54014. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  54015. onSuccess(vertexData);
  54016. }
  54017. }
  54018. });
  54019. };
  54020. var this_2 = this, accessor;
  54021. for (var semantic in attributes) {
  54022. _loop_2(semantic);
  54023. }
  54024. };
  54025. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  54026. var targets = primitive.targets;
  54027. if (!targets) {
  54028. return;
  54029. }
  54030. if (!babylonMesh.morphTargetManager) {
  54031. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  54032. }
  54033. for (var index = 0; index < targets.length; index++) {
  54034. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  54035. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  54036. }
  54037. };
  54038. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  54039. var targets = primitive.targets;
  54040. if (!targets) {
  54041. return;
  54042. }
  54043. var _loop_3 = function () {
  54044. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  54045. attributes = targets[index];
  54046. var _loop_4 = function (semantic) {
  54047. accessor = this_3._gltf.accessors[attributes[semantic]];
  54048. this_3._loadAccessorAsync(accessor, function (data) {
  54049. if (accessor.name) {
  54050. babylonMorphTarget.name = accessor.name;
  54051. }
  54052. // glTF stores morph target information as deltas while babylon.js expects the final data.
  54053. // As a result we have to add the original data to the delta to calculate the final data.
  54054. var values = data;
  54055. switch (semantic) {
  54056. case "NORMAL":
  54057. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  54058. babylonMorphTarget.setNormals(values);
  54059. break;
  54060. case "POSITION":
  54061. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  54062. babylonMorphTarget.setPositions(values);
  54063. break;
  54064. case "TANGENT":
  54065. // Tangent data for morph targets is stored as xyz delta.
  54066. // The vertexData.tangent is stored as xyzw.
  54067. // So we need to skip every fourth vertexData.tangent.
  54068. for (var i = 0, j = 0; i < values.length; i++, j++) {
  54069. values[i] += vertexData.tangents[j];
  54070. if ((i + 1) % 3 == 0) {
  54071. j++;
  54072. }
  54073. }
  54074. babylonMorphTarget.setTangents(values);
  54075. break;
  54076. default:
  54077. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  54078. break;
  54079. }
  54080. });
  54081. };
  54082. for (var semantic in attributes) {
  54083. _loop_4(semantic);
  54084. }
  54085. };
  54086. var this_3 = this, attributes, accessor;
  54087. for (var index = 0; index < targets.length; index++) {
  54088. _loop_3();
  54089. }
  54090. };
  54091. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  54092. var position = BABYLON.Vector3.Zero();
  54093. var rotation = BABYLON.Quaternion.Identity();
  54094. var scaling = BABYLON.Vector3.One();
  54095. if (node.matrix) {
  54096. var mat = BABYLON.Matrix.FromArray(node.matrix);
  54097. mat.decompose(scaling, rotation, position);
  54098. }
  54099. else {
  54100. if (node.translation)
  54101. position = BABYLON.Vector3.FromArray(node.translation);
  54102. if (node.rotation)
  54103. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  54104. if (node.scale)
  54105. scaling = BABYLON.Vector3.FromArray(node.scale);
  54106. }
  54107. babylonMesh.position = position;
  54108. babylonMesh.rotationQuaternion = rotation;
  54109. babylonMesh.scaling = scaling;
  54110. };
  54111. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  54112. if (parentNode === void 0) { parentNode = null; }
  54113. for (var i = 0; i < indices.length; i++) {
  54114. this._traverseNode(indices[i], action, parentNode);
  54115. }
  54116. };
  54117. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  54118. if (parentNode === void 0) { parentNode = null; }
  54119. var node = this._gltf.nodes[index];
  54120. if (!action(node, index, parentNode)) {
  54121. return;
  54122. }
  54123. if (node.children) {
  54124. for (var i = 0; i < node.children.length; i++) {
  54125. this._traverseNode(node.children[i], action, node);
  54126. }
  54127. }
  54128. };
  54129. GLTFLoader.prototype._loadAnimations = function () {
  54130. var animations = this._gltf.animations;
  54131. if (!animations || animations.length === 0) {
  54132. return;
  54133. }
  54134. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  54135. var animation = animations[animationIndex];
  54136. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  54137. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  54138. }
  54139. }
  54140. };
  54141. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  54142. var channel = animation.channels[channelIndex];
  54143. var samplerIndex = channel.sampler;
  54144. var sampler = animation.samplers[samplerIndex];
  54145. var targetNode = this._gltf.nodes[channel.target.node];
  54146. if (!targetNode) {
  54147. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  54148. return;
  54149. }
  54150. var targetPath = {
  54151. "translation": "position",
  54152. "rotation": "rotationQuaternion",
  54153. "scale": "scaling",
  54154. "weights": "influence"
  54155. }[channel.target.path];
  54156. if (!targetPath) {
  54157. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  54158. return;
  54159. }
  54160. var animationType = {
  54161. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  54162. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  54163. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  54164. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  54165. }[targetPath];
  54166. var inputData;
  54167. var outputData;
  54168. var checkSuccess = function () {
  54169. if (!inputData || !outputData) {
  54170. return;
  54171. }
  54172. var outputBufferOffset = 0;
  54173. var getNextOutputValue = {
  54174. "position": function () {
  54175. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  54176. outputBufferOffset += 3;
  54177. return value;
  54178. },
  54179. "rotationQuaternion": function () {
  54180. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  54181. outputBufferOffset += 4;
  54182. return value;
  54183. },
  54184. "scaling": function () {
  54185. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  54186. outputBufferOffset += 3;
  54187. return value;
  54188. },
  54189. "influence": function () {
  54190. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  54191. var value = new Array(numTargets);
  54192. for (var i = 0; i < numTargets; i++) {
  54193. value[i] = outputData[outputBufferOffset++];
  54194. }
  54195. return value;
  54196. },
  54197. }[targetPath];
  54198. var getNextKey = {
  54199. "LINEAR": function (frameIndex) { return ({
  54200. frame: inputData[frameIndex],
  54201. value: getNextOutputValue()
  54202. }); },
  54203. "CUBICSPLINE": function (frameIndex) { return ({
  54204. frame: inputData[frameIndex],
  54205. inTangent: getNextOutputValue(),
  54206. value: getNextOutputValue(),
  54207. outTangent: getNextOutputValue()
  54208. }); },
  54209. }[sampler.interpolation];
  54210. var keys = new Array(inputData.length);
  54211. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  54212. keys[frameIndex] = getNextKey(frameIndex);
  54213. }
  54214. animation.targets = animation.targets || [];
  54215. if (targetPath === "influence") {
  54216. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  54217. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  54218. var morphTarget = morphTargetManager.getTarget(targetIndex);
  54219. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  54220. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  54221. babylonAnimation.setKeys(keys.map(function (key) { return ({
  54222. frame: key.frame,
  54223. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  54224. value: key.value[targetIndex],
  54225. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  54226. }); }));
  54227. morphTarget.animations.push(babylonAnimation);
  54228. animation.targets.push(morphTarget);
  54229. }
  54230. }
  54231. else {
  54232. var animationName = animation.name || "anim" + animationIndex;
  54233. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  54234. babylonAnimation.setKeys(keys);
  54235. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  54236. var target = targetNode.babylonAnimationTargets[i];
  54237. target.animations.push(babylonAnimation.clone());
  54238. animation.targets.push(target);
  54239. }
  54240. }
  54241. };
  54242. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  54243. inputData = data;
  54244. checkSuccess();
  54245. });
  54246. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  54247. outputData = data;
  54248. checkSuccess();
  54249. });
  54250. };
  54251. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  54252. var _this = this;
  54253. var buffer = this._gltf.buffers[index];
  54254. this.addPendingData(buffer);
  54255. if (buffer.loadedData) {
  54256. setTimeout(function () {
  54257. onSuccess(buffer.loadedData);
  54258. _this.removePendingData(buffer);
  54259. });
  54260. }
  54261. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  54262. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  54263. buffer.loadedData = new Uint8Array(data);
  54264. setTimeout(function () {
  54265. onSuccess(buffer.loadedData);
  54266. _this.removePendingData(buffer);
  54267. });
  54268. }
  54269. else if (buffer.loadedObservable) {
  54270. buffer.loadedObservable.add(function (buffer) {
  54271. onSuccess(buffer.loadedData);
  54272. _this.removePendingData(buffer);
  54273. });
  54274. }
  54275. else {
  54276. buffer.loadedObservable = new BABYLON.Observable();
  54277. buffer.loadedObservable.add(function (buffer) {
  54278. onSuccess(buffer.loadedData);
  54279. _this.removePendingData(buffer);
  54280. });
  54281. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  54282. buffer.loadedData = new Uint8Array(data);
  54283. buffer.loadedObservable.notifyObservers(buffer);
  54284. buffer.loadedObservable = null;
  54285. }, function (event) {
  54286. if (!_this._disposed) {
  54287. _this._onProgress(event);
  54288. }
  54289. }, this._babylonScene.database, true, function (request) {
  54290. if (!_this._disposed) {
  54291. _this._onError("Failed to load file '" + buffer.uri + "': " + request.status + " " + request.statusText);
  54292. _this.removePendingData(buffer);
  54293. }
  54294. });
  54295. }
  54296. };
  54297. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, componentType, onSuccess) {
  54298. var _this = this;
  54299. byteOffset += (bufferView.byteOffset || 0);
  54300. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  54301. if (byteOffset + byteLength > bufferData.byteLength) {
  54302. _this._onError("Buffer access is out of range");
  54303. return;
  54304. }
  54305. var buffer = bufferData.buffer;
  54306. byteOffset += bufferData.byteOffset;
  54307. var bufferViewData;
  54308. switch (componentType) {
  54309. case GLTF2.EComponentType.BYTE:
  54310. bufferViewData = new Int8Array(buffer, byteOffset, byteLength);
  54311. break;
  54312. case GLTF2.EComponentType.UNSIGNED_BYTE:
  54313. bufferViewData = new Uint8Array(buffer, byteOffset, byteLength);
  54314. break;
  54315. case GLTF2.EComponentType.SHORT:
  54316. bufferViewData = new Int16Array(buffer, byteOffset, byteLength);
  54317. break;
  54318. case GLTF2.EComponentType.UNSIGNED_SHORT:
  54319. bufferViewData = new Uint16Array(buffer, byteOffset, byteLength);
  54320. break;
  54321. case GLTF2.EComponentType.UNSIGNED_INT:
  54322. bufferViewData = new Uint32Array(buffer, byteOffset, byteLength);
  54323. break;
  54324. case GLTF2.EComponentType.FLOAT:
  54325. bufferViewData = new Float32Array(buffer, byteOffset, byteLength);
  54326. break;
  54327. default:
  54328. _this._onError("Invalid component type (" + componentType + ")");
  54329. return;
  54330. }
  54331. onSuccess(bufferViewData);
  54332. });
  54333. };
  54334. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  54335. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  54336. var byteOffset = accessor.byteOffset || 0;
  54337. var byteLength = accessor.count * this._getByteStrideFromType(accessor);
  54338. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, accessor.componentType, onSuccess);
  54339. };
  54340. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  54341. switch (accessor.type) {
  54342. case "SCALAR": return 1;
  54343. case "VEC2": return 2;
  54344. case "VEC3": return 3;
  54345. case "VEC4": return 4;
  54346. case "MAT2": return 4;
  54347. case "MAT3": return 9;
  54348. case "MAT4": return 16;
  54349. default:
  54350. this._onError("Invalid accessor type (" + accessor.type + ")");
  54351. return 0;
  54352. }
  54353. };
  54354. Object.defineProperty(GLTFLoader.prototype, "blockPendingTracking", {
  54355. set: function (value) {
  54356. this._blockPendingTracking = value;
  54357. },
  54358. enumerable: true,
  54359. configurable: true
  54360. });
  54361. GLTFLoader.prototype.addPendingData = function (data) {
  54362. if (!this._renderReady) {
  54363. this._renderPendingCount++;
  54364. }
  54365. this.addLoaderPendingData(data);
  54366. };
  54367. GLTFLoader.prototype.removePendingData = function (data) {
  54368. if (!this._renderReady) {
  54369. if (--this._renderPendingCount === 0) {
  54370. this._renderReady = true;
  54371. this._onRenderReady();
  54372. }
  54373. }
  54374. this.removeLoaderPendingData(data);
  54375. };
  54376. GLTFLoader.prototype.addLoaderNonBlockingPendingData = function (data) {
  54377. if (!this._nonBlockingData) {
  54378. this._nonBlockingData = new Array();
  54379. }
  54380. this._nonBlockingData.push(data);
  54381. };
  54382. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  54383. if (this._blockPendingTracking) {
  54384. this.addLoaderNonBlockingPendingData(data);
  54385. return;
  54386. }
  54387. this._loaderPendingCount++;
  54388. };
  54389. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  54390. var indexInPending = this._nonBlockingData ? this._nonBlockingData.indexOf(data) : -1;
  54391. if (indexInPending !== -1) {
  54392. this._nonBlockingData.splice(indexInPending, 1);
  54393. }
  54394. else if (--this._loaderPendingCount === 0) {
  54395. this._onLoaderFirstLODComplete();
  54396. }
  54397. if ((!this._nonBlockingData || this._nonBlockingData.length === 0) && this._loaderPendingCount === 0) {
  54398. this._onLoaderComplete();
  54399. this.dispose();
  54400. }
  54401. };
  54402. GLTFLoader.prototype._getDefaultMaterial = function () {
  54403. if (!this._defaultMaterial) {
  54404. var id = "__gltf_default";
  54405. var material = this._babylonScene.getMaterialByName(id);
  54406. if (!material) {
  54407. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  54408. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  54409. material.metallic = 1;
  54410. material.roughness = 1;
  54411. }
  54412. this._defaultMaterial = material;
  54413. }
  54414. return this._defaultMaterial;
  54415. };
  54416. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  54417. var babylonMaterial = material.babylonMaterial;
  54418. // Ensure metallic workflow
  54419. babylonMaterial.metallic = 1;
  54420. babylonMaterial.roughness = 1;
  54421. var properties = material.pbrMetallicRoughness;
  54422. if (!properties) {
  54423. return;
  54424. }
  54425. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  54426. babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  54427. babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  54428. if (properties.baseColorTexture) {
  54429. babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  54430. }
  54431. if (properties.metallicRoughnessTexture) {
  54432. babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  54433. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  54434. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  54435. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  54436. }
  54437. this.loadMaterialAlphaProperties(material, properties.baseColorFactor);
  54438. };
  54439. GLTFLoader.prototype.loadMaterial = function (material, assign) {
  54440. if (material.babylonMaterial) {
  54441. assign(material.babylonMaterial, false);
  54442. return;
  54443. }
  54444. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  54445. return;
  54446. }
  54447. this.createPbrMaterial(material);
  54448. this.loadMaterialBaseProperties(material);
  54449. this._loadMaterialMetallicRoughnessProperties(material);
  54450. assign(material.babylonMaterial, true);
  54451. };
  54452. GLTFLoader.prototype.createPbrMaterial = function (material) {
  54453. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  54454. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  54455. material.babylonMaterial = babylonMaterial;
  54456. };
  54457. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  54458. var babylonMaterial = material.babylonMaterial;
  54459. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  54460. if (material.doubleSided) {
  54461. babylonMaterial.backFaceCulling = false;
  54462. babylonMaterial.twoSidedLighting = true;
  54463. }
  54464. if (material.normalTexture) {
  54465. babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  54466. babylonMaterial.invertNormalMapX = true;
  54467. babylonMaterial.invertNormalMapY = false;
  54468. if (material.normalTexture.scale !== undefined) {
  54469. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  54470. }
  54471. }
  54472. if (material.occlusionTexture) {
  54473. babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  54474. babylonMaterial.useAmbientInGrayScale = true;
  54475. if (material.occlusionTexture.strength !== undefined) {
  54476. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  54477. }
  54478. }
  54479. if (material.emissiveTexture) {
  54480. babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  54481. }
  54482. };
  54483. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material, colorFactor) {
  54484. var babylonMaterial = material.babylonMaterial;
  54485. var alphaMode = material.alphaMode || "OPAQUE";
  54486. switch (alphaMode) {
  54487. case "OPAQUE":
  54488. // default is opaque
  54489. break;
  54490. case "MASK":
  54491. case "BLEND":
  54492. if (colorFactor) {
  54493. babylonMaterial.alpha = colorFactor[3];
  54494. }
  54495. if (babylonMaterial.albedoTexture) {
  54496. babylonMaterial.albedoTexture.hasAlpha = true;
  54497. babylonMaterial.useAlphaFromAlbedoTexture = (alphaMode === "BLEND");
  54498. }
  54499. break;
  54500. default:
  54501. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  54502. break;
  54503. }
  54504. };
  54505. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  54506. var _this = this;
  54507. var texture = this._gltf.textures[textureInfo.index];
  54508. var texCoord = textureInfo.texCoord || 0;
  54509. if (!texture || texture.source === undefined) {
  54510. return null;
  54511. }
  54512. // check the cache first
  54513. var babylonTexture;
  54514. if (texture.babylonTextures) {
  54515. babylonTexture = texture.babylonTextures[texCoord];
  54516. if (!babylonTexture) {
  54517. for (var i = 0; i < texture.babylonTextures.length; i++) {
  54518. babylonTexture = texture.babylonTextures[i];
  54519. if (babylonTexture) {
  54520. babylonTexture = babylonTexture.clone();
  54521. babylonTexture.coordinatesIndex = texCoord;
  54522. break;
  54523. }
  54524. }
  54525. }
  54526. return babylonTexture;
  54527. }
  54528. var source = this._gltf.images[texture.source];
  54529. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  54530. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  54531. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  54532. this.addPendingData(texture);
  54533. babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  54534. if (!_this._disposed) {
  54535. _this.removePendingData(texture);
  54536. }
  54537. }, function () {
  54538. if (!_this._disposed) {
  54539. _this._onError("Failed to load texture '" + source.uri + "'");
  54540. _this.removePendingData(texture);
  54541. }
  54542. });
  54543. var setTextureData = function (data) {
  54544. var url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  54545. _this._objectURLs.push(url);
  54546. babylonTexture.updateURL(url);
  54547. };
  54548. if (!source.uri) {
  54549. var bufferView = this._gltf.bufferViews[source.bufferView];
  54550. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  54551. }
  54552. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  54553. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  54554. }
  54555. else {
  54556. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  54557. if (!_this._disposed) {
  54558. _this._onProgress(event);
  54559. }
  54560. }, this._babylonScene.database, true, function (request) {
  54561. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  54562. });
  54563. }
  54564. babylonTexture.coordinatesIndex = texCoord;
  54565. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  54566. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  54567. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  54568. // Cache the texture
  54569. texture.babylonTextures = texture.babylonTextures || [];
  54570. texture.babylonTextures[texCoord] = babylonTexture;
  54571. if (this._parent.onTextureLoaded) {
  54572. this._parent.onTextureLoaded(babylonTexture);
  54573. }
  54574. return babylonTexture;
  54575. };
  54576. GLTFLoader.Extensions = {};
  54577. return GLTFLoader;
  54578. }());
  54579. GLTF2.GLTFLoader = GLTFLoader;
  54580. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  54581. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54582. })(BABYLON || (BABYLON = {}));
  54583. //# sourceMappingURL=babylon.glTFLoader.js.map
  54584. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  54585. var BABYLON;
  54586. (function (BABYLON) {
  54587. var GLTF2;
  54588. (function (GLTF2) {
  54589. /**
  54590. * Utils functions for GLTF
  54591. */
  54592. var GLTFUtils = (function () {
  54593. function GLTFUtils() {
  54594. }
  54595. /**
  54596. * If the uri is a base64 string
  54597. * @param uri: the uri to test
  54598. */
  54599. GLTFUtils.IsBase64 = function (uri) {
  54600. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  54601. };
  54602. /**
  54603. * Decode the base64 uri
  54604. * @param uri: the uri to decode
  54605. */
  54606. GLTFUtils.DecodeBase64 = function (uri) {
  54607. var decodedString = atob(uri.split(",")[1]);
  54608. var bufferLength = decodedString.length;
  54609. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  54610. for (var i = 0; i < bufferLength; i++) {
  54611. bufferView[i] = decodedString.charCodeAt(i);
  54612. }
  54613. return bufferView.buffer;
  54614. };
  54615. GLTFUtils.ForEach = function (view, func) {
  54616. for (var index = 0; index < view.length; index++) {
  54617. func(view[index], index);
  54618. }
  54619. };
  54620. GLTFUtils.GetTextureWrapMode = function (mode) {
  54621. // Set defaults if undefined
  54622. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  54623. switch (mode) {
  54624. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  54625. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  54626. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  54627. default:
  54628. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  54629. return BABYLON.Texture.WRAP_ADDRESSMODE;
  54630. }
  54631. };
  54632. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  54633. // Set defaults if undefined
  54634. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  54635. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST : minFilter;
  54636. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  54637. switch (minFilter) {
  54638. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  54639. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  54640. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  54641. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  54642. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  54643. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  54644. default:
  54645. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  54646. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  54647. }
  54648. }
  54649. else {
  54650. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  54651. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  54652. }
  54653. switch (minFilter) {
  54654. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  54655. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  54656. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  54657. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  54658. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  54659. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  54660. default:
  54661. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  54662. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  54663. }
  54664. }
  54665. };
  54666. /**
  54667. * Decodes a buffer view into a string
  54668. * @param view: the buffer view
  54669. */
  54670. GLTFUtils.DecodeBufferToText = function (view) {
  54671. var result = "";
  54672. var length = view.byteLength;
  54673. for (var i = 0; i < length; ++i) {
  54674. result += String.fromCharCode(view[i]);
  54675. }
  54676. return result;
  54677. };
  54678. return GLTFUtils;
  54679. }());
  54680. GLTF2.GLTFUtils = GLTFUtils;
  54681. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54682. })(BABYLON || (BABYLON = {}));
  54683. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  54684. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  54685. var BABYLON;
  54686. (function (BABYLON) {
  54687. var GLTF2;
  54688. (function (GLTF2) {
  54689. var GLTFLoaderExtension = (function () {
  54690. function GLTFLoaderExtension() {
  54691. this.enabled = true;
  54692. }
  54693. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  54694. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  54695. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  54696. };
  54697. GLTFLoaderExtension._ApplyExtensions = function (action) {
  54698. var extensions = GLTFLoaderExtension._Extensions;
  54699. if (!extensions) {
  54700. return;
  54701. }
  54702. for (var i = 0; i < extensions.length; i++) {
  54703. var extension = extensions[i];
  54704. if (extension.enabled && action(extension)) {
  54705. return true;
  54706. }
  54707. }
  54708. return false;
  54709. };
  54710. //
  54711. // Utilities
  54712. //
  54713. GLTFLoaderExtension._Extensions = [];
  54714. return GLTFLoaderExtension;
  54715. }());
  54716. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  54717. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54718. })(BABYLON || (BABYLON = {}));
  54719. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  54720. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  54721. var BABYLON;
  54722. (function (BABYLON) {
  54723. var GLTF2;
  54724. (function (GLTF2) {
  54725. var Extensions;
  54726. (function (Extensions) {
  54727. var MSFTLOD = (function (_super) {
  54728. __extends(MSFTLOD, _super);
  54729. function MSFTLOD() {
  54730. return _super !== null && _super.apply(this, arguments) || this;
  54731. }
  54732. Object.defineProperty(MSFTLOD.prototype, "name", {
  54733. get: function () {
  54734. return "MSFT_lod";
  54735. },
  54736. enumerable: true,
  54737. configurable: true
  54738. });
  54739. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  54740. if (!material.extensions) {
  54741. return false;
  54742. }
  54743. var properties = material.extensions[this.name];
  54744. if (!properties) {
  54745. return false;
  54746. }
  54747. // Clear out the extension so that it won't get loaded again.
  54748. material.extensions[this.name] = undefined;
  54749. // Tell the loader not to clear its state until the highest LOD is loaded.
  54750. var materialLODs = [material.index].concat(properties.ids);
  54751. loader.addLoaderPendingData(material);
  54752. for (var index = 0; index < materialLODs.length; index++) {
  54753. loader.addLoaderNonBlockingPendingData(index);
  54754. }
  54755. // Start with the lowest quality LOD.
  54756. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  54757. return true;
  54758. };
  54759. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  54760. var _this = this;
  54761. var materialLOD = loader.gltf.materials[materialLODs[lod]];
  54762. if (lod !== materialLODs.length - 1) {
  54763. loader.blockPendingTracking = true;
  54764. }
  54765. loader.loadMaterial(materialLOD, function (babylonMaterial, isNew) {
  54766. assign(babylonMaterial, isNew);
  54767. loader.removeLoaderPendingData(lod);
  54768. // Loading is considered complete if this is the lowest quality LOD.
  54769. if (lod === materialLODs.length - 1) {
  54770. loader.removeLoaderPendingData(material);
  54771. }
  54772. if (lod === 0) {
  54773. loader.blockPendingTracking = false;
  54774. return;
  54775. }
  54776. // Load the next LOD when the loader is ready to render and
  54777. // all active material textures of the current LOD are loaded.
  54778. loader.executeWhenRenderReady(function () {
  54779. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  54780. setTimeout(function () {
  54781. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  54782. }, MSFTLOD.MinimalLODDelay);
  54783. });
  54784. });
  54785. });
  54786. };
  54787. /**
  54788. * Specify the minimal delay between LODs in ms (default = 250)
  54789. */
  54790. MSFTLOD.MinimalLODDelay = 250;
  54791. return MSFTLOD;
  54792. }(GLTF2.GLTFLoaderExtension));
  54793. Extensions.MSFTLOD = MSFTLOD;
  54794. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  54795. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  54796. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54797. })(BABYLON || (BABYLON = {}));
  54798. //# sourceMappingURL=MSFT_lod.js.map
  54799. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  54800. var BABYLON;
  54801. (function (BABYLON) {
  54802. var GLTF2;
  54803. (function (GLTF2) {
  54804. var Extensions;
  54805. (function (Extensions) {
  54806. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  54807. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  54808. function KHRMaterialsPbrSpecularGlossiness() {
  54809. return _super !== null && _super.apply(this, arguments) || this;
  54810. }
  54811. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  54812. get: function () {
  54813. return "KHR_materials_pbrSpecularGlossiness";
  54814. },
  54815. enumerable: true,
  54816. configurable: true
  54817. });
  54818. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  54819. if (!material.extensions) {
  54820. return false;
  54821. }
  54822. var properties = material.extensions[this.name];
  54823. if (!properties) {
  54824. return false;
  54825. }
  54826. loader.createPbrMaterial(material);
  54827. loader.loadMaterialBaseProperties(material);
  54828. this._loadSpecularGlossinessProperties(loader, material, properties);
  54829. assign(material.babylonMaterial, true);
  54830. return true;
  54831. };
  54832. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  54833. var babylonMaterial = material.babylonMaterial;
  54834. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  54835. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  54836. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  54837. if (properties.diffuseTexture) {
  54838. babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  54839. loader.loadMaterialAlphaProperties(material);
  54840. }
  54841. if (properties.specularGlossinessTexture) {
  54842. babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  54843. babylonMaterial.reflectivityTexture.hasAlpha = true;
  54844. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  54845. }
  54846. loader.loadMaterialAlphaProperties(material, properties.diffuseFactor);
  54847. };
  54848. return KHRMaterialsPbrSpecularGlossiness;
  54849. }(GLTF2.GLTFLoaderExtension));
  54850. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  54851. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  54852. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  54853. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54854. })(BABYLON || (BABYLON = {}));
  54855. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  54856. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  54857. module.exports = BABYLON;
  54858. };