babylon.max.js 2.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457
  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. // Lost context
  7457. this.onContextLostObservable = new BABYLON.Observable();
  7458. this.onContextRestoredObservable = new BABYLON.Observable();
  7459. this._contextWasLost = false;
  7460. this._doNotHandleContextLost = false;
  7461. // FPS
  7462. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7463. this._fps = 60;
  7464. this._deltaTime = 0;
  7465. /**
  7466. * Turn this value on if you want to pause FPS computation when in background
  7467. */
  7468. this.disablePerformanceMonitorInBackground = false;
  7469. // States
  7470. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7471. this._stencilState = new BABYLON.Internals._StencilState();
  7472. this._alphaState = new BABYLON.Internals._AlphaState();
  7473. this._alphaMode = Engine.ALPHA_DISABLE;
  7474. // Cache
  7475. this._internalTexturesCache = new Array();
  7476. this._maxTextureChannels = 16;
  7477. this._activeTexturesCache = {};
  7478. this._compiledEffects = {};
  7479. this._vertexAttribArraysEnabled = [];
  7480. this._uintIndicesCurrentlySet = false;
  7481. this._currentBoundBuffer = new Array();
  7482. this._currentBufferPointers = new Array();
  7483. this._currentInstanceLocations = new Array();
  7484. this._currentInstanceBuffers = new Array();
  7485. this._vaoRecordInProgress = false;
  7486. this._mustWipeVertexAttributes = false;
  7487. // Hardware supported Compressed Textures
  7488. this._texturesSupported = new Array();
  7489. this._onVRFullScreenTriggered = function () {
  7490. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7491. //get the old size before we change
  7492. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7493. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7494. //get the width and height, change the render size
  7495. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7496. var width, height;
  7497. _this.setHardwareScalingLevel(1);
  7498. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7499. }
  7500. else {
  7501. //When the specs are implemented, need to uncomment this.
  7502. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7503. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7504. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7505. _this._vrDisplayEnabled = undefined;
  7506. }
  7507. };
  7508. var canvas;
  7509. Engine.Instances.push(this);
  7510. options = options || {};
  7511. if (canvasOrContext.getContext) {
  7512. canvas = canvasOrContext;
  7513. this._renderingCanvas = canvas;
  7514. if (antialias != null) {
  7515. options.antialias = antialias;
  7516. }
  7517. if (options.deterministicLockstep === undefined) {
  7518. options.deterministicLockstep = false;
  7519. }
  7520. if (options.lockstepMaxSteps === undefined) {
  7521. options.lockstepMaxSteps = 4;
  7522. }
  7523. if (options.preserveDrawingBuffer === undefined) {
  7524. options.preserveDrawingBuffer = false;
  7525. }
  7526. if (options.audioEngine === undefined) {
  7527. options.audioEngine = true;
  7528. }
  7529. if (options.stencil === undefined) {
  7530. options.stencil = true;
  7531. }
  7532. this._deterministicLockstep = options.deterministicLockstep;
  7533. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7534. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7535. // GL
  7536. if (!options.disableWebGL2Support) {
  7537. try {
  7538. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7539. if (this._gl) {
  7540. this._webGLVersion = 2.0;
  7541. }
  7542. }
  7543. catch (e) {
  7544. // Do nothing
  7545. }
  7546. }
  7547. if (!this._gl) {
  7548. if (!canvas) {
  7549. throw new Error("The provided canvas is null or undefined.");
  7550. }
  7551. try {
  7552. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7553. }
  7554. catch (e) {
  7555. throw new Error("WebGL not supported");
  7556. }
  7557. }
  7558. if (!this._gl) {
  7559. throw new Error("WebGL not supported");
  7560. }
  7561. this._onBlur = function () {
  7562. if (_this.disablePerformanceMonitorInBackground) {
  7563. _this._performanceMonitor.disable();
  7564. }
  7565. _this._windowIsBackground = true;
  7566. };
  7567. this._onFocus = function () {
  7568. if (_this.disablePerformanceMonitorInBackground) {
  7569. _this._performanceMonitor.enable();
  7570. }
  7571. _this._windowIsBackground = false;
  7572. };
  7573. this._onCanvasBlur = function () {
  7574. _this.onCanvasBlurObservable.notifyObservers(_this);
  7575. };
  7576. window.addEventListener("blur", this._onBlur);
  7577. window.addEventListener("focus", this._onFocus);
  7578. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7579. }
  7580. else {
  7581. this._gl = canvasOrContext;
  7582. this._renderingCanvas = this._gl.canvas;
  7583. if (this._gl.renderbufferStorageMultisample) {
  7584. this._webGLVersion = 2.0;
  7585. }
  7586. options.stencil = this._gl.getContextAttributes().stencil;
  7587. }
  7588. // Context lost
  7589. if (!this._doNotHandleContextLost) {
  7590. this._onContextLost = function (evt) {
  7591. evt.preventDefault();
  7592. _this._contextWasLost = true;
  7593. BABYLON.Tools.Warn("WebGL context lost.");
  7594. _this.onContextLostObservable.notifyObservers(_this);
  7595. };
  7596. this._onContextRestored = function (evt) {
  7597. // Rebuild gl context
  7598. _this._initGLContext();
  7599. // Rebuild effects
  7600. _this._rebuildEffects();
  7601. // Rebuild textures
  7602. _this._rebuildInternalTextures();
  7603. // Rebuild buffers
  7604. _this._rebuildBuffers();
  7605. // Cache
  7606. _this.wipeCaches(true);
  7607. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7608. _this.onContextRestoredObservable.notifyObservers(_this);
  7609. _this._contextWasLost = false;
  7610. };
  7611. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7612. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7613. }
  7614. // Viewport
  7615. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7616. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7617. this.resize();
  7618. this._isStencilEnable = options.stencil;
  7619. this._initGLContext();
  7620. if (canvas) {
  7621. // Fullscreen
  7622. this._onFullscreenChange = function () {
  7623. if (document.fullscreen !== undefined) {
  7624. _this.isFullscreen = document.fullscreen;
  7625. }
  7626. else if (document.mozFullScreen !== undefined) {
  7627. _this.isFullscreen = document.mozFullScreen;
  7628. }
  7629. else if (document.webkitIsFullScreen !== undefined) {
  7630. _this.isFullscreen = document.webkitIsFullScreen;
  7631. }
  7632. else if (document.msIsFullScreen !== undefined) {
  7633. _this.isFullscreen = document.msIsFullScreen;
  7634. }
  7635. // Pointer lock
  7636. if (_this.isFullscreen && _this._pointerLockRequested) {
  7637. canvas.requestPointerLock = canvas.requestPointerLock ||
  7638. canvas.msRequestPointerLock ||
  7639. canvas.mozRequestPointerLock ||
  7640. canvas.webkitRequestPointerLock;
  7641. if (canvas.requestPointerLock) {
  7642. canvas.requestPointerLock();
  7643. }
  7644. }
  7645. };
  7646. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7647. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7648. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7649. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7650. // Pointer lock
  7651. this._onPointerLockChange = function () {
  7652. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7653. document.webkitPointerLockElement === canvas ||
  7654. document.msPointerLockElement === canvas ||
  7655. document.pointerLockElement === canvas);
  7656. };
  7657. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7658. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7659. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7660. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7661. this._onVRDisplayPointerRestricted = function () {
  7662. canvas.requestPointerLock();
  7663. };
  7664. this._onVRDisplayPointerUnrestricted = function () {
  7665. document.exitPointerLock();
  7666. };
  7667. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7668. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7669. }
  7670. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7671. Engine.audioEngine = new BABYLON.AudioEngine();
  7672. }
  7673. // Prepare buffer pointers
  7674. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7675. this._currentBufferPointers[i] = new BufferPointer();
  7676. }
  7677. // Load WebVR Devices
  7678. if (options.autoEnableWebVR) {
  7679. this.initWebVR();
  7680. }
  7681. // Detect if we are running on a faulty buggy OS.
  7682. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7683. // Detect if we are running on a faulty buggy desktop OS.
  7684. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7685. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7686. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7687. }
  7688. Object.defineProperty(Engine, "LastCreatedEngine", {
  7689. get: function () {
  7690. if (Engine.Instances.length === 0) {
  7691. return null;
  7692. }
  7693. return Engine.Instances[Engine.Instances.length - 1];
  7694. },
  7695. enumerable: true,
  7696. configurable: true
  7697. });
  7698. Object.defineProperty(Engine, "LastCreatedScene", {
  7699. get: function () {
  7700. var lastCreatedEngine = Engine.LastCreatedEngine;
  7701. if (!lastCreatedEngine) {
  7702. return null;
  7703. }
  7704. if (lastCreatedEngine.scenes.length === 0) {
  7705. return null;
  7706. }
  7707. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7708. },
  7709. enumerable: true,
  7710. configurable: true
  7711. });
  7712. /**
  7713. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7714. */
  7715. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7716. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7717. var engine = Engine.Instances[engineIndex];
  7718. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7719. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7720. }
  7721. }
  7722. };
  7723. Object.defineProperty(Engine, "NEVER", {
  7724. get: function () {
  7725. return Engine._NEVER;
  7726. },
  7727. enumerable: true,
  7728. configurable: true
  7729. });
  7730. Object.defineProperty(Engine, "ALWAYS", {
  7731. get: function () {
  7732. return Engine._ALWAYS;
  7733. },
  7734. enumerable: true,
  7735. configurable: true
  7736. });
  7737. Object.defineProperty(Engine, "LESS", {
  7738. get: function () {
  7739. return Engine._LESS;
  7740. },
  7741. enumerable: true,
  7742. configurable: true
  7743. });
  7744. Object.defineProperty(Engine, "EQUAL", {
  7745. get: function () {
  7746. return Engine._EQUAL;
  7747. },
  7748. enumerable: true,
  7749. configurable: true
  7750. });
  7751. Object.defineProperty(Engine, "LEQUAL", {
  7752. get: function () {
  7753. return Engine._LEQUAL;
  7754. },
  7755. enumerable: true,
  7756. configurable: true
  7757. });
  7758. Object.defineProperty(Engine, "GREATER", {
  7759. get: function () {
  7760. return Engine._GREATER;
  7761. },
  7762. enumerable: true,
  7763. configurable: true
  7764. });
  7765. Object.defineProperty(Engine, "GEQUAL", {
  7766. get: function () {
  7767. return Engine._GEQUAL;
  7768. },
  7769. enumerable: true,
  7770. configurable: true
  7771. });
  7772. Object.defineProperty(Engine, "NOTEQUAL", {
  7773. get: function () {
  7774. return Engine._NOTEQUAL;
  7775. },
  7776. enumerable: true,
  7777. configurable: true
  7778. });
  7779. Object.defineProperty(Engine, "KEEP", {
  7780. get: function () {
  7781. return Engine._KEEP;
  7782. },
  7783. enumerable: true,
  7784. configurable: true
  7785. });
  7786. Object.defineProperty(Engine, "REPLACE", {
  7787. get: function () {
  7788. return Engine._REPLACE;
  7789. },
  7790. enumerable: true,
  7791. configurable: true
  7792. });
  7793. Object.defineProperty(Engine, "INCR", {
  7794. get: function () {
  7795. return Engine._INCR;
  7796. },
  7797. enumerable: true,
  7798. configurable: true
  7799. });
  7800. Object.defineProperty(Engine, "DECR", {
  7801. get: function () {
  7802. return Engine._DECR;
  7803. },
  7804. enumerable: true,
  7805. configurable: true
  7806. });
  7807. Object.defineProperty(Engine, "INVERT", {
  7808. get: function () {
  7809. return Engine._INVERT;
  7810. },
  7811. enumerable: true,
  7812. configurable: true
  7813. });
  7814. Object.defineProperty(Engine, "INCR_WRAP", {
  7815. get: function () {
  7816. return Engine._INCR_WRAP;
  7817. },
  7818. enumerable: true,
  7819. configurable: true
  7820. });
  7821. Object.defineProperty(Engine, "DECR_WRAP", {
  7822. get: function () {
  7823. return Engine._DECR_WRAP;
  7824. },
  7825. enumerable: true,
  7826. configurable: true
  7827. });
  7828. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7829. get: function () {
  7830. return Engine._ALPHA_DISABLE;
  7831. },
  7832. enumerable: true,
  7833. configurable: true
  7834. });
  7835. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7836. get: function () {
  7837. return Engine._ALPHA_ONEONE;
  7838. },
  7839. enumerable: true,
  7840. configurable: true
  7841. });
  7842. Object.defineProperty(Engine, "ALPHA_ADD", {
  7843. get: function () {
  7844. return Engine._ALPHA_ADD;
  7845. },
  7846. enumerable: true,
  7847. configurable: true
  7848. });
  7849. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7850. get: function () {
  7851. return Engine._ALPHA_COMBINE;
  7852. },
  7853. enumerable: true,
  7854. configurable: true
  7855. });
  7856. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7857. get: function () {
  7858. return Engine._ALPHA_SUBTRACT;
  7859. },
  7860. enumerable: true,
  7861. configurable: true
  7862. });
  7863. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7864. get: function () {
  7865. return Engine._ALPHA_MULTIPLY;
  7866. },
  7867. enumerable: true,
  7868. configurable: true
  7869. });
  7870. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7871. get: function () {
  7872. return Engine._ALPHA_MAXIMIZED;
  7873. },
  7874. enumerable: true,
  7875. configurable: true
  7876. });
  7877. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7878. get: function () {
  7879. return Engine._ALPHA_PREMULTIPLIED;
  7880. },
  7881. enumerable: true,
  7882. configurable: true
  7883. });
  7884. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7885. get: function () {
  7886. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7887. },
  7888. enumerable: true,
  7889. configurable: true
  7890. });
  7891. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7892. get: function () {
  7893. return Engine._ALPHA_INTERPOLATE;
  7894. },
  7895. enumerable: true,
  7896. configurable: true
  7897. });
  7898. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7899. get: function () {
  7900. return Engine._ALPHA_SCREENMODE;
  7901. },
  7902. enumerable: true,
  7903. configurable: true
  7904. });
  7905. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7906. get: function () {
  7907. return Engine._DELAYLOADSTATE_NONE;
  7908. },
  7909. enumerable: true,
  7910. configurable: true
  7911. });
  7912. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7913. get: function () {
  7914. return Engine._DELAYLOADSTATE_LOADED;
  7915. },
  7916. enumerable: true,
  7917. configurable: true
  7918. });
  7919. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7920. get: function () {
  7921. return Engine._DELAYLOADSTATE_LOADING;
  7922. },
  7923. enumerable: true,
  7924. configurable: true
  7925. });
  7926. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7927. get: function () {
  7928. return Engine._DELAYLOADSTATE_NOTLOADED;
  7929. },
  7930. enumerable: true,
  7931. configurable: true
  7932. });
  7933. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7934. get: function () {
  7935. return Engine._TEXTUREFORMAT_ALPHA;
  7936. },
  7937. enumerable: true,
  7938. configurable: true
  7939. });
  7940. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7941. get: function () {
  7942. return Engine._TEXTUREFORMAT_LUMINANCE;
  7943. },
  7944. enumerable: true,
  7945. configurable: true
  7946. });
  7947. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7948. get: function () {
  7949. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7950. },
  7951. enumerable: true,
  7952. configurable: true
  7953. });
  7954. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7955. get: function () {
  7956. return Engine._TEXTUREFORMAT_RGB;
  7957. },
  7958. enumerable: true,
  7959. configurable: true
  7960. });
  7961. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7962. get: function () {
  7963. return Engine._TEXTUREFORMAT_RGBA;
  7964. },
  7965. enumerable: true,
  7966. configurable: true
  7967. });
  7968. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7969. get: function () {
  7970. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7971. },
  7972. enumerable: true,
  7973. configurable: true
  7974. });
  7975. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7976. get: function () {
  7977. return Engine._TEXTURETYPE_FLOAT;
  7978. },
  7979. enumerable: true,
  7980. configurable: true
  7981. });
  7982. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7983. get: function () {
  7984. return Engine._TEXTURETYPE_HALF_FLOAT;
  7985. },
  7986. enumerable: true,
  7987. configurable: true
  7988. });
  7989. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7990. get: function () {
  7991. return Engine._SCALEMODE_FLOOR;
  7992. },
  7993. enumerable: true,
  7994. configurable: true
  7995. });
  7996. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7997. get: function () {
  7998. return Engine._SCALEMODE_NEAREST;
  7999. },
  8000. enumerable: true,
  8001. configurable: true
  8002. });
  8003. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8004. get: function () {
  8005. return Engine._SCALEMODE_CEILING;
  8006. },
  8007. enumerable: true,
  8008. configurable: true
  8009. });
  8010. Object.defineProperty(Engine, "Version", {
  8011. get: function () {
  8012. return "3.1-alpha";
  8013. },
  8014. enumerable: true,
  8015. configurable: true
  8016. });
  8017. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8018. get: function () {
  8019. return this._webGLVersion < 2 || this.forcePOTTextures;
  8020. },
  8021. enumerable: true,
  8022. configurable: true
  8023. });
  8024. Object.defineProperty(Engine.prototype, "badOS", {
  8025. get: function () {
  8026. return this._badOS;
  8027. },
  8028. enumerable: true,
  8029. configurable: true
  8030. });
  8031. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8032. get: function () {
  8033. return this._badDesktopOS;
  8034. },
  8035. enumerable: true,
  8036. configurable: true
  8037. });
  8038. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8039. get: function () {
  8040. return this._performanceMonitor;
  8041. },
  8042. enumerable: true,
  8043. configurable: true
  8044. });
  8045. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8046. get: function () {
  8047. return this._texturesSupported;
  8048. },
  8049. enumerable: true,
  8050. configurable: true
  8051. });
  8052. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8053. get: function () {
  8054. return this._textureFormatInUse;
  8055. },
  8056. enumerable: true,
  8057. configurable: true
  8058. });
  8059. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8060. // Empty texture
  8061. get: function () {
  8062. if (!this._emptyTexture) {
  8063. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8064. }
  8065. return this._emptyTexture;
  8066. },
  8067. enumerable: true,
  8068. configurable: true
  8069. });
  8070. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8071. get: function () {
  8072. if (!this._emptyCubeTexture) {
  8073. var faceData = new Uint8Array(4);
  8074. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8075. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8076. }
  8077. return this._emptyCubeTexture;
  8078. },
  8079. enumerable: true,
  8080. configurable: true
  8081. });
  8082. Engine.prototype._rebuildInternalTextures = function () {
  8083. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8084. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8085. var internalTexture = currentState_1[_i];
  8086. internalTexture._rebuild();
  8087. }
  8088. };
  8089. Engine.prototype._rebuildEffects = function () {
  8090. for (var key in this._compiledEffects) {
  8091. var effect = this._compiledEffects[key];
  8092. effect._prepareEffect();
  8093. }
  8094. BABYLON.Effect.ResetCache();
  8095. };
  8096. Engine.prototype._rebuildBuffers = function () {
  8097. // Index / Vertex
  8098. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8099. var scene = _a[_i];
  8100. scene.resetCachedMaterial();
  8101. scene._rebuildGeometries();
  8102. scene._rebuildTextures();
  8103. }
  8104. // Uniforms
  8105. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8106. var uniformBuffer = _c[_b];
  8107. uniformBuffer._rebuild();
  8108. }
  8109. };
  8110. Engine.prototype._initGLContext = function () {
  8111. // Caps
  8112. this._caps = new EngineCapabilities();
  8113. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8114. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8115. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8116. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8117. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8118. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8119. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8120. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8121. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8122. // Infos
  8123. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8124. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8125. if (rendererInfo != null) {
  8126. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8127. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8128. }
  8129. if (!this._glVendor) {
  8130. this._glVendor = "Unknown vendor";
  8131. }
  8132. if (!this._glRenderer) {
  8133. this._glRenderer = "Unknown renderer";
  8134. }
  8135. // Constants
  8136. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8137. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8138. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8139. this._gl.DEPTH24_STENCIL8 = 35056;
  8140. // Extensions
  8141. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8142. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8143. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8144. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8145. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8146. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8147. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8148. 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');
  8149. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8150. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8151. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8152. this._caps.highPrecisionShaderSupported = true;
  8153. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8154. // Checks if some of the format renders first to allow the use of webgl inspector.
  8155. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8156. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8157. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8158. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8159. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8160. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8161. if (this._webGLVersion > 1) {
  8162. this._gl.HALF_FLOAT_OES = 0x140B;
  8163. }
  8164. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8165. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8166. // Vertex array object
  8167. if (this._webGLVersion > 1) {
  8168. this._caps.vertexArrayObject = true;
  8169. }
  8170. else {
  8171. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8172. if (vertexArrayObjectExtension != null) {
  8173. this._caps.vertexArrayObject = true;
  8174. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8175. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8176. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8177. }
  8178. else {
  8179. this._caps.vertexArrayObject = false;
  8180. }
  8181. }
  8182. // Instances count
  8183. if (this._webGLVersion > 1) {
  8184. this._caps.instancedArrays = true;
  8185. }
  8186. else {
  8187. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8188. if (instanceExtension != null) {
  8189. this._caps.instancedArrays = true;
  8190. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8191. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8192. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8193. }
  8194. else {
  8195. this._caps.instancedArrays = false;
  8196. }
  8197. }
  8198. // Intelligently add supported compressed formats in order to check for.
  8199. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8200. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8201. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8202. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8203. if (this._caps.astc)
  8204. this.texturesSupported.push('-astc.ktx');
  8205. if (this._caps.s3tc)
  8206. this.texturesSupported.push('-dxt.ktx');
  8207. if (this._caps.pvrtc)
  8208. this.texturesSupported.push('-pvrtc.ktx');
  8209. if (this._caps.etc2)
  8210. this.texturesSupported.push('-etc2.ktx');
  8211. if (this._caps.etc1)
  8212. this.texturesSupported.push('-etc1.ktx');
  8213. if (this._gl.getShaderPrecisionFormat) {
  8214. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8215. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8216. }
  8217. // Depth buffer
  8218. this.setDepthBuffer(true);
  8219. this.setDepthFunctionToLessOrEqual();
  8220. this.setDepthWrite(true);
  8221. };
  8222. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8223. get: function () {
  8224. return this._webGLVersion;
  8225. },
  8226. enumerable: true,
  8227. configurable: true
  8228. });
  8229. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8230. /**
  8231. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8232. */
  8233. get: function () {
  8234. return this._isStencilEnable;
  8235. },
  8236. enumerable: true,
  8237. configurable: true
  8238. });
  8239. Engine.prototype._prepareWorkingCanvas = function () {
  8240. if (this._workingCanvas) {
  8241. return;
  8242. }
  8243. this._workingCanvas = document.createElement("canvas");
  8244. this._workingContext = this._workingCanvas.getContext("2d");
  8245. };
  8246. Engine.prototype.resetTextureCache = function () {
  8247. for (var key in this._activeTexturesCache) {
  8248. this._activeTexturesCache[key] = null;
  8249. }
  8250. };
  8251. Engine.prototype.isDeterministicLockStep = function () {
  8252. return this._deterministicLockstep;
  8253. };
  8254. Engine.prototype.getLockstepMaxSteps = function () {
  8255. return this._lockstepMaxSteps;
  8256. };
  8257. Engine.prototype.getGlInfo = function () {
  8258. return {
  8259. vendor: this._glVendor,
  8260. renderer: this._glRenderer,
  8261. version: this._glVersion
  8262. };
  8263. };
  8264. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8265. if (useScreen === void 0) { useScreen = false; }
  8266. var viewport = camera.viewport;
  8267. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8268. };
  8269. Engine.prototype.getRenderWidth = function (useScreen) {
  8270. if (useScreen === void 0) { useScreen = false; }
  8271. if (!useScreen && this._currentRenderTarget) {
  8272. return this._currentRenderTarget.width;
  8273. }
  8274. return this._gl.drawingBufferWidth;
  8275. };
  8276. Engine.prototype.getRenderHeight = function (useScreen) {
  8277. if (useScreen === void 0) { useScreen = false; }
  8278. if (!useScreen && this._currentRenderTarget) {
  8279. return this._currentRenderTarget.height;
  8280. }
  8281. return this._gl.drawingBufferHeight;
  8282. };
  8283. Engine.prototype.getRenderingCanvas = function () {
  8284. return this._renderingCanvas;
  8285. };
  8286. Engine.prototype.getRenderingCanvasClientRect = function () {
  8287. return this._renderingCanvas.getBoundingClientRect();
  8288. };
  8289. Engine.prototype.setHardwareScalingLevel = function (level) {
  8290. this._hardwareScalingLevel = level;
  8291. this.resize();
  8292. };
  8293. Engine.prototype.getHardwareScalingLevel = function () {
  8294. return this._hardwareScalingLevel;
  8295. };
  8296. Engine.prototype.getLoadedTexturesCache = function () {
  8297. return this._internalTexturesCache;
  8298. };
  8299. Engine.prototype.getCaps = function () {
  8300. return this._caps;
  8301. };
  8302. Object.defineProperty(Engine.prototype, "drawCalls", {
  8303. /** The number of draw calls submitted last frame */
  8304. get: function () {
  8305. return this._drawCalls.current;
  8306. },
  8307. enumerable: true,
  8308. configurable: true
  8309. });
  8310. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8311. get: function () {
  8312. return this._drawCalls;
  8313. },
  8314. enumerable: true,
  8315. configurable: true
  8316. });
  8317. Engine.prototype.getDepthFunction = function () {
  8318. return this._depthCullingState.depthFunc;
  8319. };
  8320. Engine.prototype.setDepthFunction = function (depthFunc) {
  8321. this._depthCullingState.depthFunc = depthFunc;
  8322. };
  8323. Engine.prototype.setDepthFunctionToGreater = function () {
  8324. this._depthCullingState.depthFunc = this._gl.GREATER;
  8325. };
  8326. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8327. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8328. };
  8329. Engine.prototype.setDepthFunctionToLess = function () {
  8330. this._depthCullingState.depthFunc = this._gl.LESS;
  8331. };
  8332. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8333. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8334. };
  8335. Engine.prototype.getStencilBuffer = function () {
  8336. return this._stencilState.stencilTest;
  8337. };
  8338. Engine.prototype.setStencilBuffer = function (enable) {
  8339. this._stencilState.stencilTest = enable;
  8340. };
  8341. Engine.prototype.getStencilMask = function () {
  8342. return this._stencilState.stencilMask;
  8343. };
  8344. Engine.prototype.setStencilMask = function (mask) {
  8345. this._stencilState.stencilMask = mask;
  8346. };
  8347. Engine.prototype.getStencilFunction = function () {
  8348. return this._stencilState.stencilFunc;
  8349. };
  8350. Engine.prototype.getStencilFunctionReference = function () {
  8351. return this._stencilState.stencilFuncRef;
  8352. };
  8353. Engine.prototype.getStencilFunctionMask = function () {
  8354. return this._stencilState.stencilFuncMask;
  8355. };
  8356. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8357. this._stencilState.stencilFunc = stencilFunc;
  8358. };
  8359. Engine.prototype.setStencilFunctionReference = function (reference) {
  8360. this._stencilState.stencilFuncRef = reference;
  8361. };
  8362. Engine.prototype.setStencilFunctionMask = function (mask) {
  8363. this._stencilState.stencilFuncMask = mask;
  8364. };
  8365. Engine.prototype.getStencilOperationFail = function () {
  8366. return this._stencilState.stencilOpStencilFail;
  8367. };
  8368. Engine.prototype.getStencilOperationDepthFail = function () {
  8369. return this._stencilState.stencilOpDepthFail;
  8370. };
  8371. Engine.prototype.getStencilOperationPass = function () {
  8372. return this._stencilState.stencilOpStencilDepthPass;
  8373. };
  8374. Engine.prototype.setStencilOperationFail = function (operation) {
  8375. this._stencilState.stencilOpStencilFail = operation;
  8376. };
  8377. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8378. this._stencilState.stencilOpDepthFail = operation;
  8379. };
  8380. Engine.prototype.setStencilOperationPass = function (operation) {
  8381. this._stencilState.stencilOpStencilDepthPass = operation;
  8382. };
  8383. Engine.prototype.setDitheringState = function (value) {
  8384. if (value) {
  8385. this._gl.enable(this._gl.DITHER);
  8386. }
  8387. else {
  8388. this._gl.disable(this._gl.DITHER);
  8389. }
  8390. };
  8391. /**
  8392. * stop executing a render loop function and remove it from the execution array
  8393. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8394. */
  8395. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8396. if (!renderFunction) {
  8397. this._activeRenderLoops = [];
  8398. return;
  8399. }
  8400. var index = this._activeRenderLoops.indexOf(renderFunction);
  8401. if (index >= 0) {
  8402. this._activeRenderLoops.splice(index, 1);
  8403. }
  8404. };
  8405. Engine.prototype._renderLoop = function () {
  8406. if (!this._contextWasLost) {
  8407. var shouldRender = true;
  8408. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8409. shouldRender = false;
  8410. }
  8411. if (shouldRender) {
  8412. // Start new frame
  8413. this.beginFrame();
  8414. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8415. var renderFunction = this._activeRenderLoops[index];
  8416. renderFunction();
  8417. }
  8418. // Present
  8419. this.endFrame();
  8420. }
  8421. }
  8422. if (this._activeRenderLoops.length > 0) {
  8423. // Register new frame
  8424. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8425. }
  8426. else {
  8427. this._renderingQueueLaunched = false;
  8428. }
  8429. };
  8430. /**
  8431. * Register and execute a render loop. The engine can have more than one render function.
  8432. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8433. * @example
  8434. * engine.runRenderLoop(function () {
  8435. * scene.render()
  8436. * })
  8437. */
  8438. Engine.prototype.runRenderLoop = function (renderFunction) {
  8439. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8440. return;
  8441. }
  8442. this._activeRenderLoops.push(renderFunction);
  8443. if (!this._renderingQueueLaunched) {
  8444. this._renderingQueueLaunched = true;
  8445. this._bindedRenderFunction = this._renderLoop.bind(this);
  8446. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8447. }
  8448. };
  8449. /**
  8450. * Toggle full screen mode.
  8451. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8452. * @param {any} options - an options object to be sent to the requestFullscreen function
  8453. */
  8454. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8455. if (this.isFullscreen) {
  8456. BABYLON.Tools.ExitFullscreen();
  8457. }
  8458. else {
  8459. this._pointerLockRequested = requestPointerLock;
  8460. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8461. }
  8462. };
  8463. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8464. if (stencil === void 0) { stencil = false; }
  8465. this.applyStates();
  8466. var mode = 0;
  8467. if (backBuffer && color) {
  8468. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8469. mode |= this._gl.COLOR_BUFFER_BIT;
  8470. }
  8471. if (depth) {
  8472. this._gl.clearDepth(1.0);
  8473. mode |= this._gl.DEPTH_BUFFER_BIT;
  8474. }
  8475. if (stencil) {
  8476. this._gl.clearStencil(0);
  8477. mode |= this._gl.STENCIL_BUFFER_BIT;
  8478. }
  8479. this._gl.clear(mode);
  8480. };
  8481. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8482. var gl = this._gl;
  8483. // Save state
  8484. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8485. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8486. // Change state
  8487. gl.enable(gl.SCISSOR_TEST);
  8488. gl.scissor(x, y, width, height);
  8489. // Clear
  8490. this.clear(clearColor, true, true, true);
  8491. // Restore state
  8492. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8493. if (curScissor === true) {
  8494. gl.enable(gl.SCISSOR_TEST);
  8495. }
  8496. else {
  8497. gl.disable(gl.SCISSOR_TEST);
  8498. }
  8499. };
  8500. /**
  8501. * Set the WebGL's viewport
  8502. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8503. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8504. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8505. */
  8506. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8507. var width = requiredWidth || this.getRenderWidth();
  8508. var height = requiredHeight || this.getRenderHeight();
  8509. var x = viewport.x || 0;
  8510. var y = viewport.y || 0;
  8511. this._cachedViewport = viewport;
  8512. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8513. };
  8514. /**
  8515. * Directly set the WebGL Viewport
  8516. * The x, y, width & height are directly passed to the WebGL call
  8517. * @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.
  8518. */
  8519. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8520. var currentViewport = this._cachedViewport;
  8521. this._cachedViewport = null;
  8522. this._gl.viewport(x, y, width, height);
  8523. return currentViewport;
  8524. };
  8525. Engine.prototype.beginFrame = function () {
  8526. this._measureFps();
  8527. };
  8528. Engine.prototype.endFrame = function () {
  8529. //force a flush in case we are using a bad OS.
  8530. if (this._badOS) {
  8531. this.flushFramebuffer();
  8532. }
  8533. //submit frame to the vr device, if enabled
  8534. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8535. this._vrDisplayEnabled.submitFrame();
  8536. }
  8537. };
  8538. /**
  8539. * resize the view according to the canvas' size.
  8540. * @example
  8541. * window.addEventListener("resize", function () {
  8542. * engine.resize();
  8543. * });
  8544. */
  8545. Engine.prototype.resize = function () {
  8546. // We're not resizing the size of the canvas while in VR mode & presenting
  8547. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8548. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8549. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8550. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8551. }
  8552. };
  8553. /**
  8554. * force a specific size of the canvas
  8555. * @param {number} width - the new canvas' width
  8556. * @param {number} height - the new canvas' height
  8557. */
  8558. Engine.prototype.setSize = function (width, height) {
  8559. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8560. return;
  8561. }
  8562. this._renderingCanvas.width = width;
  8563. this._renderingCanvas.height = height;
  8564. for (var index = 0; index < this.scenes.length; index++) {
  8565. var scene = this.scenes[index];
  8566. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8567. var cam = scene.cameras[camIndex];
  8568. cam._currentRenderId = 0;
  8569. }
  8570. }
  8571. if (this.onResizeObservable.hasObservers) {
  8572. this.onResizeObservable.notifyObservers(this);
  8573. }
  8574. };
  8575. //WebVR functions
  8576. Engine.prototype.isVRDevicePresent = function (callback) {
  8577. this.getVRDevice(null, function (device) {
  8578. callback(device !== null);
  8579. });
  8580. };
  8581. Engine.prototype.getVRDevice = function (name, callback) {
  8582. if (!this.vrDisplaysPromise) {
  8583. callback(null);
  8584. return;
  8585. }
  8586. this.vrDisplaysPromise.then(function (devices) {
  8587. if (devices.length > 0) {
  8588. if (name) {
  8589. var found = devices.some(function (device) {
  8590. if (device.displayName === name) {
  8591. callback(device);
  8592. return true;
  8593. }
  8594. else {
  8595. return false;
  8596. }
  8597. });
  8598. if (!found) {
  8599. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8600. callback(devices[0]);
  8601. }
  8602. }
  8603. else {
  8604. //choose the first one
  8605. callback(devices[0]);
  8606. }
  8607. }
  8608. else {
  8609. BABYLON.Tools.Error("No WebVR devices found!");
  8610. callback(null);
  8611. }
  8612. });
  8613. };
  8614. Engine.prototype.initWebVR = function () {
  8615. if (!this.vrDisplaysPromise) {
  8616. this._getVRDisplays();
  8617. }
  8618. };
  8619. Engine.prototype.enableVR = function (vrDevice) {
  8620. this._vrDisplayEnabled = vrDevice;
  8621. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8622. };
  8623. Engine.prototype.disableVR = function () {
  8624. if (this._vrDisplayEnabled) {
  8625. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8626. }
  8627. };
  8628. Engine.prototype._getVRDisplays = function () {
  8629. var _this = this;
  8630. var getWebVRDevices = function (devices) {
  8631. _this._vrDisplays = devices.filter(function (device) {
  8632. return device instanceof VRDisplay;
  8633. });
  8634. return _this._vrDisplays;
  8635. };
  8636. if (navigator.getVRDisplays) {
  8637. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8638. }
  8639. };
  8640. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8641. if (this._currentRenderTarget) {
  8642. this.unBindFramebuffer(this._currentRenderTarget);
  8643. }
  8644. this._currentRenderTarget = texture;
  8645. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8646. var gl = this._gl;
  8647. if (texture.isCube) {
  8648. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8649. }
  8650. if (this._cachedViewport && !forceFullscreenViewport) {
  8651. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8652. }
  8653. else {
  8654. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8655. }
  8656. this.wipeCaches();
  8657. };
  8658. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8659. if (this._currentFramebuffer !== framebuffer) {
  8660. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8661. this._currentFramebuffer = framebuffer;
  8662. }
  8663. };
  8664. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8665. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8666. this._currentRenderTarget = null;
  8667. // If MSAA, we need to bitblt back to main texture
  8668. var gl = this._gl;
  8669. if (texture._MSAAFramebuffer) {
  8670. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8671. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8672. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8673. }
  8674. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8675. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8676. gl.generateMipmap(gl.TEXTURE_2D);
  8677. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8678. }
  8679. if (onBeforeUnbind) {
  8680. if (texture._MSAAFramebuffer) {
  8681. // Bind the correct framebuffer
  8682. this.bindUnboundFramebuffer(texture._framebuffer);
  8683. }
  8684. onBeforeUnbind();
  8685. }
  8686. this.bindUnboundFramebuffer(null);
  8687. };
  8688. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8689. if (texture.generateMipMaps) {
  8690. var gl = this._gl;
  8691. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8692. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8693. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8694. }
  8695. };
  8696. Engine.prototype.flushFramebuffer = function () {
  8697. this._gl.flush();
  8698. };
  8699. Engine.prototype.restoreDefaultFramebuffer = function () {
  8700. if (this._currentRenderTarget) {
  8701. this.unBindFramebuffer(this._currentRenderTarget);
  8702. }
  8703. else {
  8704. this.bindUnboundFramebuffer(null);
  8705. }
  8706. if (this._cachedViewport) {
  8707. this.setViewport(this._cachedViewport);
  8708. }
  8709. this.wipeCaches();
  8710. };
  8711. // UBOs
  8712. Engine.prototype.createUniformBuffer = function (elements) {
  8713. var ubo = this._gl.createBuffer();
  8714. this.bindUniformBuffer(ubo);
  8715. if (elements instanceof Float32Array) {
  8716. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8717. }
  8718. else {
  8719. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8720. }
  8721. this.bindUniformBuffer(null);
  8722. ubo.references = 1;
  8723. return ubo;
  8724. };
  8725. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8726. var ubo = this._gl.createBuffer();
  8727. this.bindUniformBuffer(ubo);
  8728. if (elements instanceof Float32Array) {
  8729. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8730. }
  8731. else {
  8732. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8733. }
  8734. this.bindUniformBuffer(null);
  8735. ubo.references = 1;
  8736. return ubo;
  8737. };
  8738. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8739. this.bindUniformBuffer(uniformBuffer);
  8740. if (offset === undefined) {
  8741. offset = 0;
  8742. }
  8743. if (count === undefined) {
  8744. if (elements instanceof Float32Array) {
  8745. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8746. }
  8747. else {
  8748. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8749. }
  8750. }
  8751. else {
  8752. if (elements instanceof Float32Array) {
  8753. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8754. }
  8755. else {
  8756. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8757. }
  8758. }
  8759. this.bindUniformBuffer(null);
  8760. };
  8761. // VBOs
  8762. Engine.prototype._resetVertexBufferBinding = function () {
  8763. this.bindArrayBuffer(null);
  8764. this._cachedVertexBuffers = null;
  8765. };
  8766. Engine.prototype.createVertexBuffer = function (vertices) {
  8767. var vbo = this._gl.createBuffer();
  8768. this.bindArrayBuffer(vbo);
  8769. if (vertices instanceof Float32Array) {
  8770. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8771. }
  8772. else {
  8773. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8774. }
  8775. this._resetVertexBufferBinding();
  8776. vbo.references = 1;
  8777. return vbo;
  8778. };
  8779. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8780. var vbo = this._gl.createBuffer();
  8781. this.bindArrayBuffer(vbo);
  8782. if (vertices instanceof Float32Array) {
  8783. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8784. }
  8785. else {
  8786. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8787. }
  8788. this._resetVertexBufferBinding();
  8789. vbo.references = 1;
  8790. return vbo;
  8791. };
  8792. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8793. this.bindArrayBuffer(vertexBuffer);
  8794. if (offset === undefined) {
  8795. offset = 0;
  8796. }
  8797. if (count === undefined) {
  8798. if (vertices instanceof Float32Array) {
  8799. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8800. }
  8801. else {
  8802. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8803. }
  8804. }
  8805. else {
  8806. if (vertices instanceof Float32Array) {
  8807. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8808. }
  8809. else {
  8810. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8811. }
  8812. }
  8813. this._resetVertexBufferBinding();
  8814. };
  8815. Engine.prototype._resetIndexBufferBinding = function () {
  8816. this.bindIndexBuffer(null);
  8817. this._cachedIndexBuffer = null;
  8818. };
  8819. Engine.prototype.createIndexBuffer = function (indices) {
  8820. var vbo = this._gl.createBuffer();
  8821. this.bindIndexBuffer(vbo);
  8822. // Check for 32 bits indices
  8823. var arrayBuffer;
  8824. var need32Bits = false;
  8825. if (indices instanceof Uint16Array) {
  8826. arrayBuffer = indices;
  8827. }
  8828. else {
  8829. //check 32 bit support
  8830. if (this._caps.uintIndices) {
  8831. if (indices instanceof Uint32Array) {
  8832. arrayBuffer = indices;
  8833. need32Bits = true;
  8834. }
  8835. else {
  8836. //number[] or Int32Array, check if 32 bit is necessary
  8837. for (var index = 0; index < indices.length; index++) {
  8838. if (indices[index] > 65535) {
  8839. need32Bits = true;
  8840. break;
  8841. }
  8842. }
  8843. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8844. }
  8845. }
  8846. else {
  8847. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8848. arrayBuffer = new Uint16Array(indices);
  8849. }
  8850. }
  8851. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8852. this._resetIndexBufferBinding();
  8853. vbo.references = 1;
  8854. vbo.is32Bits = need32Bits;
  8855. return vbo;
  8856. };
  8857. Engine.prototype.bindArrayBuffer = function (buffer) {
  8858. if (!this._vaoRecordInProgress) {
  8859. this._unbindVertexArrayObject();
  8860. }
  8861. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8862. };
  8863. Engine.prototype.bindUniformBuffer = function (buffer) {
  8864. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8865. };
  8866. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8867. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8868. };
  8869. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8870. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8871. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8872. };
  8873. ;
  8874. Engine.prototype.bindIndexBuffer = function (buffer) {
  8875. if (!this._vaoRecordInProgress) {
  8876. this._unbindVertexArrayObject();
  8877. }
  8878. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8879. };
  8880. Engine.prototype.bindBuffer = function (buffer, target) {
  8881. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8882. this._gl.bindBuffer(target, buffer);
  8883. this._currentBoundBuffer[target] = buffer;
  8884. }
  8885. };
  8886. Engine.prototype.updateArrayBuffer = function (data) {
  8887. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8888. };
  8889. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8890. var pointer = this._currentBufferPointers[indx];
  8891. var changed = false;
  8892. if (!pointer.active) {
  8893. changed = true;
  8894. pointer.active = true;
  8895. pointer.index = indx;
  8896. pointer.size = size;
  8897. pointer.type = type;
  8898. pointer.normalized = normalized;
  8899. pointer.stride = stride;
  8900. pointer.offset = offset;
  8901. pointer.buffer = buffer;
  8902. }
  8903. else {
  8904. if (pointer.buffer !== buffer) {
  8905. pointer.buffer = buffer;
  8906. changed = true;
  8907. }
  8908. if (pointer.size !== size) {
  8909. pointer.size = size;
  8910. changed = true;
  8911. }
  8912. if (pointer.type !== type) {
  8913. pointer.type = type;
  8914. changed = true;
  8915. }
  8916. if (pointer.normalized !== normalized) {
  8917. pointer.normalized = normalized;
  8918. changed = true;
  8919. }
  8920. if (pointer.stride !== stride) {
  8921. pointer.stride = stride;
  8922. changed = true;
  8923. }
  8924. if (pointer.offset !== offset) {
  8925. pointer.offset = offset;
  8926. changed = true;
  8927. }
  8928. }
  8929. if (changed || this._vaoRecordInProgress) {
  8930. this.bindArrayBuffer(buffer);
  8931. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8932. }
  8933. };
  8934. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8935. if (indexBuffer == null) {
  8936. return;
  8937. }
  8938. if (this._cachedIndexBuffer !== indexBuffer) {
  8939. this._cachedIndexBuffer = indexBuffer;
  8940. this.bindIndexBuffer(indexBuffer);
  8941. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8942. }
  8943. };
  8944. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8945. var attributes = effect.getAttributesNames();
  8946. if (!this._vaoRecordInProgress) {
  8947. this._unbindVertexArrayObject();
  8948. }
  8949. this.unbindAllAttributes();
  8950. for (var index = 0; index < attributes.length; index++) {
  8951. var order = effect.getAttributeLocation(index);
  8952. if (order >= 0) {
  8953. var vertexBuffer = vertexBuffers[attributes[index]];
  8954. if (!vertexBuffer) {
  8955. continue;
  8956. }
  8957. this._gl.enableVertexAttribArray(order);
  8958. if (!this._vaoRecordInProgress) {
  8959. this._vertexAttribArraysEnabled[order] = true;
  8960. }
  8961. var buffer = vertexBuffer.getBuffer();
  8962. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8963. if (vertexBuffer.getIsInstanced()) {
  8964. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8965. if (!this._vaoRecordInProgress) {
  8966. this._currentInstanceLocations.push(order);
  8967. this._currentInstanceBuffers.push(buffer);
  8968. }
  8969. }
  8970. }
  8971. }
  8972. };
  8973. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8974. var vao = this._gl.createVertexArray();
  8975. this._vaoRecordInProgress = true;
  8976. this._gl.bindVertexArray(vao);
  8977. this._mustWipeVertexAttributes = true;
  8978. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8979. this.bindIndexBuffer(indexBuffer);
  8980. this._vaoRecordInProgress = false;
  8981. this._gl.bindVertexArray(null);
  8982. return vao;
  8983. };
  8984. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8985. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8986. this._cachedVertexArrayObject = vertexArrayObject;
  8987. this._gl.bindVertexArray(vertexArrayObject);
  8988. this._cachedVertexBuffers = null;
  8989. this._cachedIndexBuffer = null;
  8990. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8991. this._mustWipeVertexAttributes = true;
  8992. }
  8993. };
  8994. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8995. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8996. this._cachedVertexBuffers = vertexBuffer;
  8997. this._cachedEffectForVertexBuffers = effect;
  8998. var attributesCount = effect.getAttributesCount();
  8999. this._unbindVertexArrayObject();
  9000. this.unbindAllAttributes();
  9001. var offset = 0;
  9002. for (var index = 0; index < attributesCount; index++) {
  9003. if (index < vertexDeclaration.length) {
  9004. var order = effect.getAttributeLocation(index);
  9005. if (order >= 0) {
  9006. this._gl.enableVertexAttribArray(order);
  9007. this._vertexAttribArraysEnabled[order] = true;
  9008. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9009. }
  9010. offset += vertexDeclaration[index] * 4;
  9011. }
  9012. }
  9013. }
  9014. this._bindIndexBufferWithCache(indexBuffer);
  9015. };
  9016. Engine.prototype._unbindVertexArrayObject = function () {
  9017. if (!this._cachedVertexArrayObject) {
  9018. return;
  9019. }
  9020. this._cachedVertexArrayObject = null;
  9021. this._gl.bindVertexArray(null);
  9022. };
  9023. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9024. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9025. this._cachedVertexBuffers = vertexBuffers;
  9026. this._cachedEffectForVertexBuffers = effect;
  9027. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9028. }
  9029. this._bindIndexBufferWithCache(indexBuffer);
  9030. };
  9031. Engine.prototype.unbindInstanceAttributes = function () {
  9032. var boundBuffer;
  9033. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9034. var instancesBuffer = this._currentInstanceBuffers[i];
  9035. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9036. boundBuffer = instancesBuffer;
  9037. this.bindArrayBuffer(instancesBuffer);
  9038. }
  9039. var offsetLocation = this._currentInstanceLocations[i];
  9040. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9041. }
  9042. this._currentInstanceBuffers.length = 0;
  9043. this._currentInstanceLocations.length = 0;
  9044. };
  9045. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9046. this._gl.deleteVertexArray(vao);
  9047. };
  9048. Engine.prototype._releaseBuffer = function (buffer) {
  9049. buffer.references--;
  9050. if (buffer.references === 0) {
  9051. this._gl.deleteBuffer(buffer);
  9052. return true;
  9053. }
  9054. return false;
  9055. };
  9056. Engine.prototype.createInstancesBuffer = function (capacity) {
  9057. var buffer = this._gl.createBuffer();
  9058. buffer.capacity = capacity;
  9059. this.bindArrayBuffer(buffer);
  9060. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9061. return buffer;
  9062. };
  9063. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9064. this._gl.deleteBuffer(buffer);
  9065. };
  9066. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9067. this.bindArrayBuffer(instancesBuffer);
  9068. if (data) {
  9069. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9070. }
  9071. if (offsetLocations[0].index !== undefined) {
  9072. var stride = 0;
  9073. for (var i = 0; i < offsetLocations.length; i++) {
  9074. var ai = offsetLocations[i];
  9075. stride += ai.attributeSize * 4;
  9076. }
  9077. for (var i = 0; i < offsetLocations.length; i++) {
  9078. var ai = offsetLocations[i];
  9079. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9080. this._gl.enableVertexAttribArray(ai.index);
  9081. this._vertexAttribArraysEnabled[ai.index] = true;
  9082. }
  9083. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9084. this._gl.vertexAttribDivisor(ai.index, 1);
  9085. this._currentInstanceLocations.push(ai.index);
  9086. this._currentInstanceBuffers.push(instancesBuffer);
  9087. }
  9088. }
  9089. else {
  9090. for (var index = 0; index < 4; index++) {
  9091. var offsetLocation = offsetLocations[index];
  9092. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9093. this._gl.enableVertexAttribArray(offsetLocation);
  9094. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9095. }
  9096. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9097. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9098. this._currentInstanceLocations.push(offsetLocation);
  9099. this._currentInstanceBuffers.push(instancesBuffer);
  9100. }
  9101. }
  9102. };
  9103. Engine.prototype.applyStates = function () {
  9104. this._depthCullingState.apply(this._gl);
  9105. this._stencilState.apply(this._gl);
  9106. this._alphaState.apply(this._gl);
  9107. };
  9108. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9109. // Apply states
  9110. this.applyStates();
  9111. this._drawCalls.addCount(1, false);
  9112. // Render
  9113. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9114. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9115. if (instancesCount) {
  9116. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9117. return;
  9118. }
  9119. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9120. };
  9121. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9122. // Apply states
  9123. this.applyStates();
  9124. this._drawCalls.addCount(1, false);
  9125. if (instancesCount) {
  9126. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9127. return;
  9128. }
  9129. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9130. };
  9131. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9132. // Apply states
  9133. this.applyStates();
  9134. this._drawCalls.addCount(1, false);
  9135. if (instancesCount) {
  9136. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9137. return;
  9138. }
  9139. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9140. };
  9141. // Shaders
  9142. Engine.prototype._releaseEffect = function (effect) {
  9143. if (this._compiledEffects[effect._key]) {
  9144. delete this._compiledEffects[effect._key];
  9145. if (effect.getProgram()) {
  9146. this._gl.deleteProgram(effect.getProgram());
  9147. }
  9148. }
  9149. };
  9150. /**
  9151. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9152. * @param samplers An array of string used to represent textures
  9153. */
  9154. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9155. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9156. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9157. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9158. if (this._compiledEffects[name]) {
  9159. var compiledEffect = this._compiledEffects[name];
  9160. if (onCompiled && compiledEffect.isReady()) {
  9161. onCompiled(compiledEffect);
  9162. }
  9163. return compiledEffect;
  9164. }
  9165. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9166. effect._key = name;
  9167. this._compiledEffects[name] = effect;
  9168. return effect;
  9169. };
  9170. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9171. if (uniformsNames === void 0) { uniformsNames = []; }
  9172. if (samplers === void 0) { samplers = []; }
  9173. if (defines === void 0) { defines = ""; }
  9174. return this.createEffect({
  9175. vertex: "particles",
  9176. fragmentElement: fragmentName
  9177. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9178. };
  9179. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9180. context = context || this._gl;
  9181. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9182. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9183. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9184. var shaderProgram = context.createProgram();
  9185. context.attachShader(shaderProgram, vertexShader);
  9186. context.attachShader(shaderProgram, fragmentShader);
  9187. context.linkProgram(shaderProgram);
  9188. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9189. if (!linked) {
  9190. context.validateProgram(shaderProgram);
  9191. var error = context.getProgramInfoLog(shaderProgram);
  9192. if (error) {
  9193. throw new Error(error);
  9194. }
  9195. }
  9196. context.deleteShader(vertexShader);
  9197. context.deleteShader(fragmentShader);
  9198. return shaderProgram;
  9199. };
  9200. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9201. var results = [];
  9202. for (var index = 0; index < uniformsNames.length; index++) {
  9203. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9204. }
  9205. return results;
  9206. };
  9207. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9208. var results = [];
  9209. for (var index = 0; index < attributesNames.length; index++) {
  9210. try {
  9211. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9212. }
  9213. catch (e) {
  9214. results.push(-1);
  9215. }
  9216. }
  9217. return results;
  9218. };
  9219. Engine.prototype.enableEffect = function (effect) {
  9220. // Use program
  9221. this.setProgram(effect.getProgram());
  9222. this._currentEffect = effect;
  9223. if (effect.onBind) {
  9224. effect.onBind(effect);
  9225. }
  9226. effect.onBindObservable.notifyObservers(effect);
  9227. };
  9228. Engine.prototype.setIntArray = function (uniform, array) {
  9229. if (!uniform)
  9230. return;
  9231. this._gl.uniform1iv(uniform, array);
  9232. };
  9233. Engine.prototype.setIntArray2 = function (uniform, array) {
  9234. if (!uniform || array.length % 2 !== 0)
  9235. return;
  9236. this._gl.uniform2iv(uniform, array);
  9237. };
  9238. Engine.prototype.setIntArray3 = function (uniform, array) {
  9239. if (!uniform || array.length % 3 !== 0)
  9240. return;
  9241. this._gl.uniform3iv(uniform, array);
  9242. };
  9243. Engine.prototype.setIntArray4 = function (uniform, array) {
  9244. if (!uniform || array.length % 4 !== 0)
  9245. return;
  9246. this._gl.uniform4iv(uniform, array);
  9247. };
  9248. Engine.prototype.setFloatArray = function (uniform, array) {
  9249. if (!uniform)
  9250. return;
  9251. this._gl.uniform1fv(uniform, array);
  9252. };
  9253. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9254. if (!uniform || array.length % 2 !== 0)
  9255. return;
  9256. this._gl.uniform2fv(uniform, array);
  9257. };
  9258. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9259. if (!uniform || array.length % 3 !== 0)
  9260. return;
  9261. this._gl.uniform3fv(uniform, array);
  9262. };
  9263. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9264. if (!uniform || array.length % 4 !== 0)
  9265. return;
  9266. this._gl.uniform4fv(uniform, array);
  9267. };
  9268. Engine.prototype.setArray = function (uniform, array) {
  9269. if (!uniform)
  9270. return;
  9271. this._gl.uniform1fv(uniform, array);
  9272. };
  9273. Engine.prototype.setArray2 = function (uniform, array) {
  9274. if (!uniform || array.length % 2 !== 0)
  9275. return;
  9276. this._gl.uniform2fv(uniform, array);
  9277. };
  9278. Engine.prototype.setArray3 = function (uniform, array) {
  9279. if (!uniform || array.length % 3 !== 0)
  9280. return;
  9281. this._gl.uniform3fv(uniform, array);
  9282. };
  9283. Engine.prototype.setArray4 = function (uniform, array) {
  9284. if (!uniform || array.length % 4 !== 0)
  9285. return;
  9286. this._gl.uniform4fv(uniform, array);
  9287. };
  9288. Engine.prototype.setMatrices = function (uniform, matrices) {
  9289. if (!uniform)
  9290. return;
  9291. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9292. };
  9293. Engine.prototype.setMatrix = function (uniform, matrix) {
  9294. if (!uniform)
  9295. return;
  9296. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9297. };
  9298. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9299. if (!uniform)
  9300. return;
  9301. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9302. };
  9303. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9304. if (!uniform)
  9305. return;
  9306. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9307. };
  9308. Engine.prototype.setFloat = function (uniform, value) {
  9309. if (!uniform)
  9310. return;
  9311. this._gl.uniform1f(uniform, value);
  9312. };
  9313. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9314. if (!uniform)
  9315. return;
  9316. this._gl.uniform2f(uniform, x, y);
  9317. };
  9318. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9319. if (!uniform)
  9320. return;
  9321. this._gl.uniform3f(uniform, x, y, z);
  9322. };
  9323. Engine.prototype.setBool = function (uniform, bool) {
  9324. if (!uniform)
  9325. return;
  9326. this._gl.uniform1i(uniform, bool);
  9327. };
  9328. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9329. if (!uniform)
  9330. return;
  9331. this._gl.uniform4f(uniform, x, y, z, w);
  9332. };
  9333. Engine.prototype.setColor3 = function (uniform, color3) {
  9334. if (!uniform)
  9335. return;
  9336. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9337. };
  9338. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9339. if (!uniform)
  9340. return;
  9341. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9342. };
  9343. // States
  9344. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9345. if (zOffset === void 0) { zOffset = 0; }
  9346. if (reverseSide === void 0) { reverseSide = false; }
  9347. // Culling
  9348. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9349. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9350. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9351. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9352. if (culling) {
  9353. this._depthCullingState.cullFace = cullFace;
  9354. this._depthCullingState.cull = true;
  9355. }
  9356. else {
  9357. this._depthCullingState.cull = false;
  9358. }
  9359. }
  9360. // Z offset
  9361. this.setZOffset(zOffset);
  9362. };
  9363. Engine.prototype.setZOffset = function (value) {
  9364. this._depthCullingState.zOffset = value;
  9365. };
  9366. Engine.prototype.getZOffset = function () {
  9367. return this._depthCullingState.zOffset;
  9368. };
  9369. Engine.prototype.setDepthBuffer = function (enable) {
  9370. this._depthCullingState.depthTest = enable;
  9371. };
  9372. Engine.prototype.getDepthWrite = function () {
  9373. return this._depthCullingState.depthMask;
  9374. };
  9375. Engine.prototype.setDepthWrite = function (enable) {
  9376. this._depthCullingState.depthMask = enable;
  9377. };
  9378. Engine.prototype.setColorWrite = function (enable) {
  9379. this._gl.colorMask(enable, enable, enable, enable);
  9380. };
  9381. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9382. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9383. };
  9384. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9385. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9386. if (this._alphaMode === mode) {
  9387. return;
  9388. }
  9389. switch (mode) {
  9390. case Engine.ALPHA_DISABLE:
  9391. this._alphaState.alphaBlend = false;
  9392. break;
  9393. case Engine.ALPHA_PREMULTIPLIED:
  9394. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9395. this._alphaState.alphaBlend = true;
  9396. break;
  9397. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9398. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9399. this._alphaState.alphaBlend = true;
  9400. break;
  9401. case Engine.ALPHA_COMBINE:
  9402. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9403. this._alphaState.alphaBlend = true;
  9404. break;
  9405. case Engine.ALPHA_ONEONE:
  9406. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9407. this._alphaState.alphaBlend = true;
  9408. break;
  9409. case Engine.ALPHA_ADD:
  9410. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9411. this._alphaState.alphaBlend = true;
  9412. break;
  9413. case Engine.ALPHA_SUBTRACT:
  9414. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9415. this._alphaState.alphaBlend = true;
  9416. break;
  9417. case Engine.ALPHA_MULTIPLY:
  9418. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9419. this._alphaState.alphaBlend = true;
  9420. break;
  9421. case Engine.ALPHA_MAXIMIZED:
  9422. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9423. this._alphaState.alphaBlend = true;
  9424. break;
  9425. case Engine.ALPHA_INTERPOLATE:
  9426. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9427. this._alphaState.alphaBlend = true;
  9428. break;
  9429. case Engine.ALPHA_SCREENMODE:
  9430. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9431. this._alphaState.alphaBlend = true;
  9432. break;
  9433. }
  9434. if (!noDepthWriteChange) {
  9435. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9436. }
  9437. this._alphaMode = mode;
  9438. };
  9439. Engine.prototype.getAlphaMode = function () {
  9440. return this._alphaMode;
  9441. };
  9442. Engine.prototype.setAlphaTesting = function (enable) {
  9443. this._alphaTest = enable;
  9444. };
  9445. Engine.prototype.getAlphaTesting = function () {
  9446. return !!this._alphaTest;
  9447. };
  9448. // Textures
  9449. Engine.prototype.wipeCaches = function (bruteForce) {
  9450. if (this.preventCacheWipeBetweenFrames) {
  9451. return;
  9452. }
  9453. this.resetTextureCache();
  9454. this._currentEffect = null;
  9455. // 6/8/2017: deltakosh: Should not be required anymore.
  9456. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9457. if (bruteForce) {
  9458. this._currentProgram = null;
  9459. this._stencilState.reset();
  9460. this._depthCullingState.reset();
  9461. this.setDepthFunctionToLessOrEqual();
  9462. this._alphaState.reset();
  9463. }
  9464. this._cachedVertexBuffers = null;
  9465. this._cachedIndexBuffer = null;
  9466. this._cachedEffectForVertexBuffers = null;
  9467. this._unbindVertexArrayObject();
  9468. this.bindIndexBuffer(null);
  9469. this.bindArrayBuffer(null);
  9470. };
  9471. /**
  9472. * Set the compressed texture format to use, based on the formats you have, and the formats
  9473. * supported by the hardware / browser.
  9474. *
  9475. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9476. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9477. * to API arguments needed to compressed textures. This puts the burden on the container
  9478. * generator to house the arcane code for determining these for current & future formats.
  9479. *
  9480. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9481. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9482. *
  9483. * Note: The result of this call is not taken into account when a texture is base64.
  9484. *
  9485. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9486. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9487. *
  9488. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9489. * @returns The extension selected.
  9490. */
  9491. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9492. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9493. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9494. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9495. return this._textureFormatInUse = this._texturesSupported[i];
  9496. }
  9497. }
  9498. }
  9499. // actively set format to nothing, to allow this to be called more than once
  9500. // and possibly fail the 2nd time
  9501. return this._textureFormatInUse = null;
  9502. };
  9503. Engine.prototype._createTexture = function () {
  9504. return this._gl.createTexture();
  9505. };
  9506. /**
  9507. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9508. * @param {string} urlArg- This contains one of the following:
  9509. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9510. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9511. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9512. *
  9513. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9514. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9515. * @param {Scene} scene- Needed for loading to the correct scene.
  9516. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9517. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9518. * @param {callback} onError- Optional callback to be called upon failure.
  9519. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9520. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9521. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9522. *
  9523. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9524. */
  9525. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9526. var _this = this;
  9527. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9528. if (onLoad === void 0) { onLoad = null; }
  9529. if (onError === void 0) { onError = null; }
  9530. if (buffer === void 0) { buffer = null; }
  9531. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9532. var fromData = url.substr(0, 5) === "data:";
  9533. var fromBlob = url.substr(0, 5) === "blob:";
  9534. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9535. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9536. // establish the file extension, if possible
  9537. var lastDot = url.lastIndexOf('.');
  9538. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9539. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9540. var isTGA = (extension === ".tga");
  9541. // determine if a ktx file should be substituted
  9542. var isKTX = false;
  9543. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9544. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9545. isKTX = true;
  9546. }
  9547. if (scene) {
  9548. scene._addPendingData(texture);
  9549. }
  9550. texture.url = url;
  9551. texture.generateMipMaps = !noMipmap;
  9552. texture.samplingMode = samplingMode;
  9553. texture.invertY = invertY;
  9554. if (!this._doNotHandleContextLost) {
  9555. // Keep a link to the buffer only if we plan to handle context lost
  9556. texture._buffer = buffer;
  9557. }
  9558. if (onLoad) {
  9559. texture.onLoadedObservable.add(onLoad);
  9560. }
  9561. if (!fallBack)
  9562. this._internalTexturesCache.push(texture);
  9563. var onerror = function () {
  9564. if (scene) {
  9565. scene._removePendingData(texture);
  9566. }
  9567. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9568. if (isKTX) {
  9569. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9570. }
  9571. else if (onError) {
  9572. onError();
  9573. }
  9574. };
  9575. var callback;
  9576. // processing for non-image formats
  9577. if (isKTX || isTGA || isDDS) {
  9578. if (isKTX) {
  9579. callback = function (data) {
  9580. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9581. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9582. ktx.uploadLevels(_this._gl, !noMipmap);
  9583. return false;
  9584. }, samplingMode);
  9585. };
  9586. }
  9587. else if (isTGA) {
  9588. callback = function (arrayBuffer) {
  9589. var data = new Uint8Array(arrayBuffer);
  9590. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9591. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9592. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9593. return false;
  9594. }, samplingMode);
  9595. };
  9596. }
  9597. else if (isDDS) {
  9598. callback = function (data) {
  9599. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9600. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9601. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9602. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9603. return false;
  9604. }, samplingMode);
  9605. };
  9606. }
  9607. if (!buffer) {
  9608. BABYLON.Tools.LoadFile(url, function (data) {
  9609. callback(data);
  9610. }, null, scene ? scene.database : null, true, onerror);
  9611. }
  9612. else {
  9613. callback(buffer);
  9614. }
  9615. // image format processing
  9616. }
  9617. else {
  9618. var onload = function (img) {
  9619. if (fromBlob && !_this._doNotHandleContextLost) {
  9620. // We need to store the image if we need to rebuild the texture
  9621. // in case of a webgl context lost
  9622. texture._buffer = img;
  9623. }
  9624. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9625. var gl = _this._gl;
  9626. var isPot = (img.width === potWidth && img.height === potHeight);
  9627. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9628. if (isPot) {
  9629. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9630. return false;
  9631. }
  9632. // Using shaders to rescale because canvas.drawImage is lossy
  9633. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9634. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9635. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9636. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9637. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9638. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9639. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9640. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9641. _this._releaseTexture(source);
  9642. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9643. continuationCallback();
  9644. });
  9645. return true;
  9646. }, samplingMode);
  9647. };
  9648. if (!fromData || isBase64)
  9649. if (buffer instanceof HTMLImageElement) {
  9650. onload(buffer);
  9651. }
  9652. else {
  9653. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9654. }
  9655. else if (buffer instanceof Array || typeof buffer === "string")
  9656. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9657. else
  9658. onload(buffer);
  9659. }
  9660. return texture;
  9661. };
  9662. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9663. var _this = this;
  9664. var rtt = this.createRenderTargetTexture({
  9665. width: destination.width,
  9666. height: destination.height,
  9667. }, {
  9668. generateMipMaps: false,
  9669. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9670. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9671. generateDepthBuffer: false,
  9672. generateStencilBuffer: false
  9673. });
  9674. if (!this._rescalePostProcess) {
  9675. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9676. }
  9677. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9678. _this._rescalePostProcess.onApply = function (effect) {
  9679. effect._bindTexture("textureSampler", source);
  9680. };
  9681. scene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9682. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9683. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9684. _this.unBindFramebuffer(rtt);
  9685. _this._releaseTexture(rtt);
  9686. if (onComplete) {
  9687. onComplete();
  9688. }
  9689. });
  9690. };
  9691. Engine.prototype._getInternalFormat = function (format) {
  9692. var internalFormat = this._gl.RGBA;
  9693. switch (format) {
  9694. case Engine.TEXTUREFORMAT_ALPHA:
  9695. internalFormat = this._gl.ALPHA;
  9696. break;
  9697. case Engine.TEXTUREFORMAT_LUMINANCE:
  9698. internalFormat = this._gl.LUMINANCE;
  9699. break;
  9700. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9701. internalFormat = this._gl.LUMINANCE_ALPHA;
  9702. break;
  9703. case Engine.TEXTUREFORMAT_RGB:
  9704. internalFormat = this._gl.RGB;
  9705. break;
  9706. case Engine.TEXTUREFORMAT_RGBA:
  9707. internalFormat = this._gl.RGBA;
  9708. break;
  9709. }
  9710. return internalFormat;
  9711. };
  9712. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9713. if (compression === void 0) { compression = null; }
  9714. var internalFormat = this._getInternalFormat(format);
  9715. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9716. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9717. if (!this._doNotHandleContextLost) {
  9718. texture._bufferView = data;
  9719. texture.format = format;
  9720. texture.invertY = invertY;
  9721. texture._compression = compression;
  9722. }
  9723. if (texture.width % 4 !== 0) {
  9724. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9725. }
  9726. if (compression) {
  9727. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  9728. }
  9729. else {
  9730. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9731. }
  9732. if (texture.generateMipMaps) {
  9733. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9734. }
  9735. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9736. this.resetTextureCache();
  9737. texture.isReady = true;
  9738. };
  9739. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9740. if (compression === void 0) { compression = null; }
  9741. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  9742. texture.baseWidth = width;
  9743. texture.baseHeight = height;
  9744. texture.width = width;
  9745. texture.height = height;
  9746. texture.format = format;
  9747. texture.generateMipMaps = generateMipMaps;
  9748. texture.samplingMode = samplingMode;
  9749. texture.invertY = invertY;
  9750. texture._compression = compression;
  9751. if (!this._doNotHandleContextLost) {
  9752. texture._bufferView = data;
  9753. }
  9754. this.updateRawTexture(texture, data, format, invertY, compression);
  9755. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9756. // Filters
  9757. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9758. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9759. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9760. if (generateMipMaps) {
  9761. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9762. }
  9763. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9764. this._internalTexturesCache.push(texture);
  9765. return texture;
  9766. };
  9767. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9768. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  9769. texture.baseWidth = width;
  9770. texture.baseHeight = height;
  9771. if (generateMipMaps) {
  9772. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9773. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9774. }
  9775. this.resetTextureCache();
  9776. texture.width = width;
  9777. texture.height = height;
  9778. texture.isReady = false;
  9779. texture.generateMipMaps = generateMipMaps;
  9780. texture.samplingMode = samplingMode;
  9781. this.updateTextureSamplingMode(samplingMode, texture);
  9782. this._internalTexturesCache.push(texture);
  9783. return texture;
  9784. };
  9785. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9786. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9787. if (texture.isCube) {
  9788. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9789. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9790. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9791. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9792. }
  9793. else {
  9794. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9795. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9796. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9797. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9798. }
  9799. texture.samplingMode = samplingMode;
  9800. };
  9801. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9802. if (premulAlpha === void 0) { premulAlpha = false; }
  9803. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9804. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9805. if (premulAlpha) {
  9806. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9807. }
  9808. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9809. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9810. if (texture.generateMipMaps) {
  9811. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9812. }
  9813. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9814. if (premulAlpha) {
  9815. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9816. }
  9817. this.resetTextureCache();
  9818. texture.isReady = true;
  9819. };
  9820. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9821. if (texture._isDisabled) {
  9822. return;
  9823. }
  9824. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9825. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9826. try {
  9827. // Testing video texture support
  9828. if (this._videoTextureSupported === undefined) {
  9829. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9830. if (this._gl.getError() !== 0) {
  9831. this._videoTextureSupported = false;
  9832. }
  9833. else {
  9834. this._videoTextureSupported = true;
  9835. }
  9836. }
  9837. // Copy video through the current working canvas if video texture is not supported
  9838. if (!this._videoTextureSupported) {
  9839. if (!texture._workingCanvas) {
  9840. texture._workingCanvas = document.createElement("canvas");
  9841. texture._workingContext = texture._workingCanvas.getContext("2d");
  9842. texture._workingCanvas.width = texture.width;
  9843. texture._workingCanvas.height = texture.height;
  9844. }
  9845. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  9846. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9847. }
  9848. else {
  9849. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9850. }
  9851. if (texture.generateMipMaps) {
  9852. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9853. }
  9854. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9855. this.resetTextureCache();
  9856. texture.isReady = true;
  9857. }
  9858. catch (ex) {
  9859. // Something unexpected
  9860. // Let's disable the texture
  9861. texture._isDisabled = true;
  9862. }
  9863. };
  9864. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9865. var fullOptions = new RenderTargetCreationOptions();
  9866. if (options !== undefined && typeof options === "object") {
  9867. fullOptions.generateMipMaps = options.generateMipMaps;
  9868. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9869. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  9870. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  9871. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  9872. }
  9873. else {
  9874. fullOptions.generateMipMaps = options;
  9875. fullOptions.generateDepthBuffer = true;
  9876. fullOptions.generateStencilBuffer = false;
  9877. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9878. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9879. }
  9880. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9881. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9882. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9883. }
  9884. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9885. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9886. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9887. }
  9888. var gl = this._gl;
  9889. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  9890. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9891. var width = size.width || size;
  9892. var height = size.height || size;
  9893. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  9894. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9895. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9896. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9897. }
  9898. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9899. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9900. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9901. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9902. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  9903. // Create the framebuffer
  9904. var framebuffer = gl.createFramebuffer();
  9905. this.bindUnboundFramebuffer(framebuffer);
  9906. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  9907. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  9908. if (fullOptions.generateMipMaps) {
  9909. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9910. }
  9911. // Unbind
  9912. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9913. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9914. this.bindUnboundFramebuffer(null);
  9915. texture._framebuffer = framebuffer;
  9916. texture.baseWidth = width;
  9917. texture.baseHeight = height;
  9918. texture.width = width;
  9919. texture.height = height;
  9920. texture.isReady = true;
  9921. texture.samples = 1;
  9922. texture.generateMipMaps = fullOptions.generateMipMaps;
  9923. texture.samplingMode = fullOptions.samplingMode;
  9924. texture.type = fullOptions.type;
  9925. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  9926. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  9927. this.resetTextureCache();
  9928. this._internalTexturesCache.push(texture);
  9929. return texture;
  9930. };
  9931. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9932. var generateMipMaps = false;
  9933. var generateDepthBuffer = true;
  9934. var generateStencilBuffer = false;
  9935. var generateDepthTexture = false;
  9936. var textureCount = 1;
  9937. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9938. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9939. var types = [], samplingModes = [];
  9940. if (options !== undefined) {
  9941. generateMipMaps = options.generateMipMaps;
  9942. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9943. generateStencilBuffer = options.generateStencilBuffer;
  9944. generateDepthTexture = options.generateDepthTexture;
  9945. textureCount = options.textureCount || 1;
  9946. if (options.types) {
  9947. types = options.types;
  9948. }
  9949. if (options.samplingModes) {
  9950. samplingModes = options.samplingModes;
  9951. }
  9952. }
  9953. var gl = this._gl;
  9954. // Create the framebuffer
  9955. var framebuffer = gl.createFramebuffer();
  9956. this.bindUnboundFramebuffer(framebuffer);
  9957. var width = size.width || size;
  9958. var height = size.height || size;
  9959. var textures = [];
  9960. var attachments = [];
  9961. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9962. for (var i = 0; i < textureCount; i++) {
  9963. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9964. var type = types[i] || defaultType;
  9965. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9966. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9967. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9968. }
  9969. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9970. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9971. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9972. }
  9973. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9974. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9975. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9976. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9977. }
  9978. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  9979. var attachment = gl["COLOR_ATTACHMENT" + i];
  9980. textures.push(texture);
  9981. attachments.push(attachment);
  9982. gl.activeTexture(gl["TEXTURE" + i]);
  9983. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  9984. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9985. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9986. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9987. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9988. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9989. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  9990. if (generateMipMaps) {
  9991. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9992. }
  9993. // Unbind
  9994. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9995. texture._framebuffer = framebuffer;
  9996. texture._depthStencilBuffer = depthStencilBuffer;
  9997. texture.baseWidth = width;
  9998. texture.baseHeight = height;
  9999. texture.width = width;
  10000. texture.height = height;
  10001. texture.isReady = true;
  10002. texture.samples = 1;
  10003. texture.generateMipMaps = generateMipMaps;
  10004. texture.samplingMode = samplingMode;
  10005. texture.type = type;
  10006. texture._generateDepthBuffer = generateDepthBuffer;
  10007. texture._generateStencilBuffer = generateStencilBuffer;
  10008. this._internalTexturesCache.push(texture);
  10009. }
  10010. if (generateDepthTexture) {
  10011. // Depth texture
  10012. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10013. gl.activeTexture(gl.TEXTURE0);
  10014. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10016. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10017. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10018. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10019. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  10020. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10021. depthTexture._framebuffer = framebuffer;
  10022. depthTexture.baseWidth = width;
  10023. depthTexture.baseHeight = height;
  10024. depthTexture.width = width;
  10025. depthTexture.height = height;
  10026. depthTexture.isReady = true;
  10027. depthTexture.samples = 1;
  10028. depthTexture.generateMipMaps = generateMipMaps;
  10029. depthTexture.samplingMode = gl.NEAREST;
  10030. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10031. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10032. textures.push(depthTexture);
  10033. this._internalTexturesCache.push(depthTexture);
  10034. }
  10035. gl.drawBuffers(attachments);
  10036. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10037. this.bindUnboundFramebuffer(null);
  10038. this.resetTextureCache();
  10039. return textures;
  10040. };
  10041. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10042. if (samples === void 0) { samples = 1; }
  10043. var depthStencilBuffer = null;
  10044. var gl = this._gl;
  10045. // Create the depth/stencil buffer
  10046. if (generateStencilBuffer) {
  10047. depthStencilBuffer = gl.createRenderbuffer();
  10048. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10049. if (samples > 1) {
  10050. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10051. }
  10052. else {
  10053. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10054. }
  10055. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10056. }
  10057. else if (generateDepthBuffer) {
  10058. depthStencilBuffer = gl.createRenderbuffer();
  10059. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10060. if (samples > 1) {
  10061. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10062. }
  10063. else {
  10064. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10065. }
  10066. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10067. }
  10068. return depthStencilBuffer;
  10069. };
  10070. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10071. if (this.webGLVersion < 2) {
  10072. return 1;
  10073. }
  10074. if (texture.samples === samples) {
  10075. return samples;
  10076. }
  10077. var gl = this._gl;
  10078. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10079. // Dispose previous render buffers
  10080. if (texture._depthStencilBuffer) {
  10081. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10082. }
  10083. if (texture._MSAAFramebuffer) {
  10084. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10085. }
  10086. if (texture._MSAARenderBuffer) {
  10087. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10088. }
  10089. if (samples > 1) {
  10090. texture._MSAAFramebuffer = gl.createFramebuffer();
  10091. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10092. var colorRenderbuffer = gl.createRenderbuffer();
  10093. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10094. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10095. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10096. texture._MSAARenderBuffer = colorRenderbuffer;
  10097. }
  10098. else {
  10099. this.bindUnboundFramebuffer(texture._framebuffer);
  10100. }
  10101. texture.samples = samples;
  10102. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10103. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10104. this.bindUnboundFramebuffer(null);
  10105. return samples;
  10106. };
  10107. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10108. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10109. };
  10110. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10111. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10112. };
  10113. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10114. var gl = this._gl;
  10115. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10116. var generateMipMaps = true;
  10117. var generateDepthBuffer = true;
  10118. var generateStencilBuffer = false;
  10119. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10120. if (options !== undefined) {
  10121. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10122. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10123. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10124. if (options.samplingMode !== undefined) {
  10125. samplingMode = options.samplingMode;
  10126. }
  10127. }
  10128. texture.isCube = true;
  10129. texture.generateMipMaps = generateMipMaps;
  10130. texture.samples = 1;
  10131. texture.samplingMode = samplingMode;
  10132. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10133. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10134. for (var face = 0; face < 6; face++) {
  10135. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10136. }
  10137. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10138. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10139. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10140. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10141. // Create the framebuffer
  10142. var framebuffer = gl.createFramebuffer();
  10143. this.bindUnboundFramebuffer(framebuffer);
  10144. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10145. // Mipmaps
  10146. if (texture.generateMipMaps) {
  10147. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10148. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10149. }
  10150. // Unbind
  10151. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10152. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10153. this.bindUnboundFramebuffer(null);
  10154. texture._framebuffer = framebuffer;
  10155. texture.width = size;
  10156. texture.height = size;
  10157. texture.isReady = true;
  10158. this.resetTextureCache();
  10159. this._internalTexturesCache.push(texture);
  10160. return texture;
  10161. };
  10162. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10163. var _this = this;
  10164. if (onError === void 0) { onError = null; }
  10165. if (forcedExtension === void 0) { forcedExtension = null; }
  10166. var callback = function (loadData) {
  10167. if (!loadData) {
  10168. if (onLoad) {
  10169. onLoad(null);
  10170. }
  10171. return;
  10172. }
  10173. var texture = loadData.texture;
  10174. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10175. texture._lodGenerationScale = scale;
  10176. texture._lodGenerationOffset = offset;
  10177. if (_this._caps.textureLOD) {
  10178. // Do not add extra process if texture lod is supported.
  10179. if (onLoad) {
  10180. onLoad(texture);
  10181. }
  10182. return;
  10183. }
  10184. var mipSlices = 3;
  10185. var gl = _this._gl;
  10186. var width = loadData.width;
  10187. if (!width) {
  10188. return;
  10189. }
  10190. var textures = [];
  10191. for (var i = 0; i < mipSlices; i++) {
  10192. //compute LOD from even spacing in smoothness (matching shader calculation)
  10193. var smoothness = i / (mipSlices - 1);
  10194. var roughness = 1 - smoothness;
  10195. var minLODIndex = offset; // roughness = 0
  10196. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10197. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10198. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10199. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10200. glTextureFromLod.isCube = true;
  10201. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10202. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10203. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10204. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10205. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10206. if (loadData.isDDS) {
  10207. var info = loadData.info;
  10208. var data = loadData.data;
  10209. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10210. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10211. }
  10212. else {
  10213. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10214. }
  10215. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10216. // Wrap in a base texture for easy binding.
  10217. var lodTexture = new BABYLON.BaseTexture(scene);
  10218. lodTexture.isCube = true;
  10219. lodTexture._texture = glTextureFromLod;
  10220. glTextureFromLod.isReady = true;
  10221. textures.push(lodTexture);
  10222. }
  10223. texture._lodTextureHigh = textures[2];
  10224. texture._lodTextureMid = textures[1];
  10225. texture._lodTextureLow = textures[0];
  10226. if (onLoad) {
  10227. onLoad(texture);
  10228. }
  10229. };
  10230. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10231. };
  10232. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10233. var _this = this;
  10234. if (onLoad === void 0) { onLoad = null; }
  10235. if (onError === void 0) { onError = null; }
  10236. if (forcedExtension === void 0) { forcedExtension = null; }
  10237. var gl = this._gl;
  10238. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10239. texture.isCube = true;
  10240. texture.url = rootUrl;
  10241. texture.generateMipMaps = !noMipmap;
  10242. if (!this._doNotHandleContextLost) {
  10243. texture._extension = forcedExtension;
  10244. texture._files = files;
  10245. }
  10246. var isKTX = false;
  10247. var isDDS = false;
  10248. var lastDot = rootUrl.lastIndexOf('.');
  10249. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10250. if (this._textureFormatInUse) {
  10251. extension = this._textureFormatInUse;
  10252. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10253. isKTX = true;
  10254. }
  10255. else {
  10256. isDDS = (extension === ".dds");
  10257. }
  10258. if (isKTX) {
  10259. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10260. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10261. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10262. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10263. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10264. ktx.uploadLevels(_this._gl, !noMipmap);
  10265. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10266. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10267. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10268. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10269. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10270. _this.resetTextureCache();
  10271. texture.width = ktx.pixelWidth;
  10272. texture.height = ktx.pixelHeight;
  10273. texture.isReady = true;
  10274. }, null, null, true, onError);
  10275. }
  10276. else if (isDDS) {
  10277. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10278. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10279. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10280. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10281. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10282. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10283. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10284. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10285. }
  10286. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10287. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10288. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10289. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10290. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10291. _this.resetTextureCache();
  10292. texture.width = info.width;
  10293. texture.height = info.height;
  10294. texture.isReady = true;
  10295. texture.type = info.textureType;
  10296. if (onLoad) {
  10297. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10298. }
  10299. }, null, null, true, onError);
  10300. }
  10301. else {
  10302. cascadeLoad(rootUrl, scene, function (imgs) {
  10303. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10304. var height = width;
  10305. _this._prepareWorkingCanvas();
  10306. _this._workingCanvas.width = width;
  10307. _this._workingCanvas.height = height;
  10308. var faces = [
  10309. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10310. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10311. ];
  10312. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10313. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10314. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10315. for (var index = 0; index < faces.length; index++) {
  10316. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10317. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10318. }
  10319. if (!noMipmap) {
  10320. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10321. }
  10322. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10323. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10324. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10325. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10326. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10327. _this.resetTextureCache();
  10328. texture.width = width;
  10329. texture.height = height;
  10330. texture.isReady = true;
  10331. texture.format = format;
  10332. texture.onLoadedObservable.notifyObservers(texture);
  10333. texture.onLoadedObservable.clear();
  10334. if (onLoad) {
  10335. onLoad();
  10336. }
  10337. }, files, onError);
  10338. }
  10339. this._internalTexturesCache.push(texture);
  10340. return texture;
  10341. };
  10342. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10343. if (compression === void 0) { compression = null; }
  10344. if (level === void 0) { level = 0; }
  10345. texture._bufferViewArray = data;
  10346. texture.format = format;
  10347. texture.type = type;
  10348. texture.invertY = invertY;
  10349. texture._compression = compression;
  10350. var gl = this._gl;
  10351. var textureType = this._getWebGLTextureType(type);
  10352. var internalFormat = this._getInternalFormat(format);
  10353. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10354. var needConversion = false;
  10355. if (internalFormat === gl.RGB) {
  10356. internalFormat = gl.RGBA;
  10357. needConversion = true;
  10358. }
  10359. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10360. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10361. if (texture.width % 4 !== 0) {
  10362. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10363. }
  10364. // Data are known to be in +X +Y +Z -X -Y -Z
  10365. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10366. var faceData = data[faceIndex];
  10367. if (compression) {
  10368. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10369. }
  10370. else {
  10371. if (needConversion) {
  10372. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10373. }
  10374. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10375. }
  10376. }
  10377. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10378. if (isPot && texture.generateMipMaps && level === 0) {
  10379. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10380. }
  10381. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10382. this.resetTextureCache();
  10383. texture.isReady = true;
  10384. };
  10385. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10386. if (compression === void 0) { compression = null; }
  10387. var gl = this._gl;
  10388. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10389. texture.isCube = true;
  10390. texture.generateMipMaps = generateMipMaps;
  10391. texture.format = format;
  10392. texture.type = type;
  10393. if (!this._doNotHandleContextLost) {
  10394. texture._bufferViewArray = data;
  10395. }
  10396. var textureType = this._getWebGLTextureType(type);
  10397. var internalFormat = this._getInternalFormat(format);
  10398. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10399. var needConversion = false;
  10400. if (internalFormat === gl.RGB) {
  10401. internalFormat = gl.RGBA;
  10402. needConversion = true;
  10403. }
  10404. var width = size;
  10405. var height = width;
  10406. texture.width = width;
  10407. texture.height = height;
  10408. // Double check on POT to generate Mips.
  10409. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10410. if (!isPot) {
  10411. generateMipMaps = false;
  10412. }
  10413. // Upload data if needed. The texture won't be ready until then.
  10414. if (data) {
  10415. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10416. }
  10417. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10418. // Filters
  10419. if (data && generateMipMaps) {
  10420. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10421. }
  10422. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10424. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10425. }
  10426. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10427. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10428. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10429. }
  10430. else {
  10431. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10432. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10433. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10434. }
  10435. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10436. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10437. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10438. return texture;
  10439. };
  10440. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10441. var _this = this;
  10442. if (onLoad === void 0) { onLoad = null; }
  10443. if (onError === void 0) { onError = null; }
  10444. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10445. if (invertY === void 0) { invertY = false; }
  10446. var gl = this._gl;
  10447. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10448. scene._addPendingData(texture);
  10449. texture.url = url;
  10450. this._internalTexturesCache.push(texture);
  10451. var onerror = function () {
  10452. scene._removePendingData(texture);
  10453. if (onError) {
  10454. onError();
  10455. }
  10456. };
  10457. var internalCallback = function (data) {
  10458. var width = texture.width;
  10459. var height = texture.height;
  10460. var faceDataArrays = callback(data);
  10461. if (mipmmapGenerator) {
  10462. var textureType = _this._getWebGLTextureType(type);
  10463. var internalFormat = _this._getInternalFormat(format);
  10464. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10465. var needConversion = false;
  10466. if (internalFormat === gl.RGB) {
  10467. internalFormat = gl.RGBA;
  10468. needConversion = true;
  10469. }
  10470. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10471. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10472. var mipData = mipmmapGenerator(faceDataArrays);
  10473. for (var level = 0; level < mipData.length; level++) {
  10474. var mipSize = width >> level;
  10475. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10476. var mipFaceData = mipData[level][faceIndex];
  10477. if (needConversion) {
  10478. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10479. }
  10480. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10481. }
  10482. }
  10483. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10484. }
  10485. else {
  10486. texture.generateMipMaps = !noMipmap;
  10487. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10488. }
  10489. texture.isReady = true;
  10490. _this.resetTextureCache();
  10491. scene._removePendingData(texture);
  10492. if (onLoad) {
  10493. onLoad();
  10494. }
  10495. };
  10496. BABYLON.Tools.LoadFile(url, function (data) {
  10497. internalCallback(data);
  10498. }, onerror, scene.database, true);
  10499. return texture;
  10500. };
  10501. ;
  10502. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10503. var gl = this._gl;
  10504. if (!gl) {
  10505. return;
  10506. }
  10507. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10508. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10509. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10510. if (!noMipmap && !isCompressed) {
  10511. gl.generateMipmap(gl.TEXTURE_2D);
  10512. }
  10513. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10514. this.resetTextureCache();
  10515. if (scene) {
  10516. scene._removePendingData(texture);
  10517. }
  10518. texture.onLoadedObservable.notifyObservers(texture);
  10519. texture.onLoadedObservable.clear();
  10520. };
  10521. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10522. var _this = this;
  10523. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10524. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10525. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10526. var gl = this._gl;
  10527. if (!gl) {
  10528. return;
  10529. }
  10530. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10531. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10532. texture.baseWidth = width;
  10533. texture.baseHeight = height;
  10534. texture.width = potWidth;
  10535. texture.height = potHeight;
  10536. texture.isReady = true;
  10537. if (processFunction(potWidth, potHeight, function () {
  10538. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10539. })) {
  10540. // Returning as texture needs extra async steps
  10541. return;
  10542. }
  10543. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10544. };
  10545. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10546. // Create new RGBA data container.
  10547. var rgbaData;
  10548. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10549. rgbaData = new Float32Array(width * height * 4);
  10550. }
  10551. else {
  10552. rgbaData = new Uint32Array(width * height * 4);
  10553. }
  10554. // Convert each pixel.
  10555. for (var x = 0; x < width; x++) {
  10556. for (var y = 0; y < height; y++) {
  10557. var index = (y * width + x) * 3;
  10558. var newIndex = (y * width + x) * 4;
  10559. // Map Old Value to new value.
  10560. rgbaData[newIndex + 0] = rgbData[index + 0];
  10561. rgbaData[newIndex + 1] = rgbData[index + 1];
  10562. rgbaData[newIndex + 2] = rgbData[index + 2];
  10563. // Add fully opaque alpha channel.
  10564. rgbaData[newIndex + 3] = 1;
  10565. }
  10566. }
  10567. return rgbaData;
  10568. };
  10569. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10570. var gl = this._gl;
  10571. if (texture._framebuffer) {
  10572. gl.deleteFramebuffer(texture._framebuffer);
  10573. texture._framebuffer = null;
  10574. }
  10575. if (texture._depthStencilBuffer) {
  10576. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10577. texture._depthStencilBuffer = null;
  10578. }
  10579. if (texture._MSAAFramebuffer) {
  10580. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10581. texture._MSAAFramebuffer = null;
  10582. }
  10583. if (texture._MSAARenderBuffer) {
  10584. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10585. texture._MSAARenderBuffer = null;
  10586. }
  10587. };
  10588. Engine.prototype._releaseTexture = function (texture) {
  10589. var gl = this._gl;
  10590. this._releaseFramebufferObjects(texture);
  10591. gl.deleteTexture(texture._webGLTexture);
  10592. // Unbind channels
  10593. this.unbindAllTextures();
  10594. var index = this._internalTexturesCache.indexOf(texture);
  10595. if (index !== -1) {
  10596. this._internalTexturesCache.splice(index, 1);
  10597. }
  10598. // Integrated fixed lod samplers.
  10599. if (texture._lodTextureHigh) {
  10600. texture._lodTextureHigh.dispose();
  10601. }
  10602. if (texture._lodTextureMid) {
  10603. texture._lodTextureMid.dispose();
  10604. }
  10605. if (texture._lodTextureLow) {
  10606. texture._lodTextureLow.dispose();
  10607. }
  10608. };
  10609. Engine.prototype.setProgram = function (program) {
  10610. if (this._currentProgram !== program) {
  10611. this._gl.useProgram(program);
  10612. this._currentProgram = program;
  10613. }
  10614. };
  10615. Engine.prototype.bindSamplers = function (effect) {
  10616. this.setProgram(effect.getProgram());
  10617. var samplers = effect.getSamplers();
  10618. for (var index = 0; index < samplers.length; index++) {
  10619. var uniform = effect.getUniform(samplers[index]);
  10620. this._gl.uniform1i(uniform, index);
  10621. }
  10622. this._currentEffect = null;
  10623. };
  10624. Engine.prototype.activateTexture = function (texture) {
  10625. if (this._activeTexture !== texture) {
  10626. this._gl.activeTexture(texture);
  10627. this._activeTexture = texture;
  10628. }
  10629. };
  10630. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10631. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10632. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10633. this._activeTexturesCache[this._activeTexture] = texture;
  10634. }
  10635. };
  10636. Engine.prototype._bindTexture = function (channel, texture) {
  10637. if (channel < 0) {
  10638. return;
  10639. }
  10640. this.activateTexture(this._gl.TEXTURE0 + channel);
  10641. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10642. };
  10643. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10644. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10645. };
  10646. Engine.prototype.unbindAllTextures = function () {
  10647. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10648. this.activateTexture(this._gl["TEXTURE" + channel]);
  10649. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10650. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10651. }
  10652. };
  10653. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10654. if (channel < 0) {
  10655. return;
  10656. }
  10657. this._gl.uniform1i(uniform, channel);
  10658. this._setTexture(channel, texture);
  10659. };
  10660. Engine.prototype._setTexture = function (channel, texture) {
  10661. // Not ready?
  10662. if (!texture) {
  10663. if (this._activeTexturesCache[channel] != null) {
  10664. this.activateTexture(this._gl["TEXTURE" + channel]);
  10665. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10666. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10667. }
  10668. return;
  10669. }
  10670. // Video
  10671. var alreadyActivated = false;
  10672. if (texture.video) {
  10673. this.activateTexture(this._gl["TEXTURE" + channel]);
  10674. alreadyActivated = true;
  10675. texture.update();
  10676. }
  10677. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10678. texture.delayLoad();
  10679. return;
  10680. }
  10681. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10682. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10683. if (this._activeTexturesCache[channel] === internalTexture) {
  10684. return;
  10685. }
  10686. if (!alreadyActivated) {
  10687. this.activateTexture(this._gl["TEXTURE" + channel]);
  10688. }
  10689. if (internalTexture.isCube) {
  10690. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10691. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10692. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10693. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10694. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10695. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10696. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10697. }
  10698. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10699. }
  10700. else {
  10701. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10702. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10703. internalTexture._cachedWrapU = texture.wrapU;
  10704. switch (texture.wrapU) {
  10705. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10706. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10707. break;
  10708. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10709. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10710. break;
  10711. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10712. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10713. break;
  10714. }
  10715. }
  10716. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10717. internalTexture._cachedWrapV = texture.wrapV;
  10718. switch (texture.wrapV) {
  10719. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10720. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10721. break;
  10722. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10723. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10724. break;
  10725. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10726. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10727. break;
  10728. }
  10729. }
  10730. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10731. }
  10732. };
  10733. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10734. if (channel < 0) {
  10735. return;
  10736. }
  10737. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10738. this._textureUnits = new Int32Array(textures.length);
  10739. }
  10740. for (var i = 0; i < textures.length; i++) {
  10741. this._textureUnits[i] = channel + i;
  10742. }
  10743. this._gl.uniform1iv(uniform, this._textureUnits);
  10744. for (var index = 0; index < textures.length; index++) {
  10745. this._setTexture(channel + index, textures[index]);
  10746. }
  10747. };
  10748. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10749. var internalTexture = texture.getInternalTexture();
  10750. if (!internalTexture) {
  10751. return;
  10752. }
  10753. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10754. var value = texture.anisotropicFilteringLevel;
  10755. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10756. value = 1;
  10757. }
  10758. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  10759. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10760. internalTexture._cachedAnisotropicFilteringLevel = value;
  10761. }
  10762. };
  10763. Engine.prototype.readPixels = function (x, y, width, height) {
  10764. var data = new Uint8Array(height * width * 4);
  10765. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10766. return data;
  10767. };
  10768. /**
  10769. * Add an externaly attached data from its key.
  10770. * This method call will fail and return false, if such key already exists.
  10771. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10772. * @param key the unique key that identifies the data
  10773. * @param data the data object to associate to the key for this Engine instance
  10774. * @return true if no such key were already present and the data was added successfully, false otherwise
  10775. */
  10776. Engine.prototype.addExternalData = function (key, data) {
  10777. if (!this._externalData) {
  10778. this._externalData = new BABYLON.StringDictionary();
  10779. }
  10780. return this._externalData.add(key, data);
  10781. };
  10782. /**
  10783. * Get an externaly attached data from its key
  10784. * @param key the unique key that identifies the data
  10785. * @return the associated data, if present (can be null), or undefined if not present
  10786. */
  10787. Engine.prototype.getExternalData = function (key) {
  10788. if (!this._externalData) {
  10789. this._externalData = new BABYLON.StringDictionary();
  10790. }
  10791. return this._externalData.get(key);
  10792. };
  10793. /**
  10794. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10795. * @param key the unique key that identifies the data
  10796. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10797. * @return the associated data, can be null if the factory returned null.
  10798. */
  10799. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10800. if (!this._externalData) {
  10801. this._externalData = new BABYLON.StringDictionary();
  10802. }
  10803. return this._externalData.getOrAddWithFactory(key, factory);
  10804. };
  10805. /**
  10806. * Remove an externaly attached data from the Engine instance
  10807. * @param key the unique key that identifies the data
  10808. * @return true if the data was successfully removed, false if it doesn't exist
  10809. */
  10810. Engine.prototype.removeExternalData = function (key) {
  10811. if (!this._externalData) {
  10812. this._externalData = new BABYLON.StringDictionary();
  10813. }
  10814. return this._externalData.remove(key);
  10815. };
  10816. Engine.prototype.unbindAllAttributes = function () {
  10817. if (this._mustWipeVertexAttributes) {
  10818. this._mustWipeVertexAttributes = false;
  10819. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10820. this._gl.disableVertexAttribArray(i);
  10821. this._vertexAttribArraysEnabled[i] = false;
  10822. this._currentBufferPointers[i].active = false;
  10823. }
  10824. return;
  10825. }
  10826. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10827. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10828. continue;
  10829. }
  10830. this._gl.disableVertexAttribArray(i);
  10831. this._vertexAttribArraysEnabled[i] = false;
  10832. this._currentBufferPointers[i].active = false;
  10833. }
  10834. };
  10835. Engine.prototype.releaseEffects = function () {
  10836. for (var name in this._compiledEffects) {
  10837. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10838. }
  10839. this._compiledEffects = {};
  10840. };
  10841. // Dispose
  10842. Engine.prototype.dispose = function () {
  10843. this.hideLoadingUI();
  10844. this.stopRenderLoop();
  10845. // Release postProcesses
  10846. while (this.postProcesses.length) {
  10847. this.postProcesses[0].dispose();
  10848. }
  10849. // Empty texture
  10850. if (this._emptyTexture) {
  10851. this._releaseTexture(this._emptyTexture);
  10852. this._emptyTexture = null;
  10853. }
  10854. if (this._emptyCubeTexture) {
  10855. this._releaseTexture(this._emptyCubeTexture);
  10856. this._emptyCubeTexture = null;
  10857. }
  10858. // Rescale PP
  10859. if (this._rescalePostProcess) {
  10860. this._rescalePostProcess.dispose();
  10861. }
  10862. // Release scenes
  10863. while (this.scenes.length) {
  10864. this.scenes[0].dispose();
  10865. }
  10866. // Release audio engine
  10867. if (Engine.audioEngine) {
  10868. Engine.audioEngine.dispose();
  10869. }
  10870. // Release effects
  10871. this.releaseEffects();
  10872. // Unbind
  10873. this.unbindAllAttributes();
  10874. if (this._dummyFramebuffer) {
  10875. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10876. }
  10877. this._gl = null;
  10878. //WebVR
  10879. this.disableVR();
  10880. // Events
  10881. window.removeEventListener("blur", this._onBlur);
  10882. window.removeEventListener("focus", this._onFocus);
  10883. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  10884. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  10885. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  10886. if (!this._doNotHandleContextLost) {
  10887. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  10888. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  10889. }
  10890. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10891. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10892. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10893. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10894. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10895. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10896. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10897. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10898. // Remove from Instances
  10899. var index = Engine.Instances.indexOf(this);
  10900. if (index >= 0) {
  10901. Engine.Instances.splice(index, 1);
  10902. }
  10903. this._workingCanvas = null;
  10904. this._workingContext = null;
  10905. this._currentBufferPointers = null;
  10906. this._renderingCanvas = null;
  10907. this._currentProgram = null;
  10908. this.onResizeObservable.clear();
  10909. this.onCanvasBlurObservable.clear();
  10910. BABYLON.Effect.ResetCache();
  10911. };
  10912. // Loading screen
  10913. Engine.prototype.displayLoadingUI = function () {
  10914. var loadingScreen = this.loadingScreen;
  10915. if (loadingScreen) {
  10916. loadingScreen.displayLoadingUI();
  10917. }
  10918. };
  10919. Engine.prototype.hideLoadingUI = function () {
  10920. var loadingScreen = this.loadingScreen;
  10921. if (loadingScreen) {
  10922. loadingScreen.hideLoadingUI();
  10923. }
  10924. };
  10925. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10926. get: function () {
  10927. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10928. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10929. return this._loadingScreen;
  10930. },
  10931. set: function (loadingScreen) {
  10932. this._loadingScreen = loadingScreen;
  10933. },
  10934. enumerable: true,
  10935. configurable: true
  10936. });
  10937. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10938. set: function (text) {
  10939. this.loadingScreen.loadingUIText = text;
  10940. },
  10941. enumerable: true,
  10942. configurable: true
  10943. });
  10944. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10945. set: function (color) {
  10946. this.loadingScreen.loadingUIBackgroundColor = color;
  10947. },
  10948. enumerable: true,
  10949. configurable: true
  10950. });
  10951. Engine.prototype.attachContextLostEvent = function (callback) {
  10952. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10953. };
  10954. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10955. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10956. };
  10957. Engine.prototype.getVertexShaderSource = function (program) {
  10958. var shaders = this._gl.getAttachedShaders(program);
  10959. return this._gl.getShaderSource(shaders[0]);
  10960. };
  10961. Engine.prototype.getFragmentShaderSource = function (program) {
  10962. var shaders = this._gl.getAttachedShaders(program);
  10963. return this._gl.getShaderSource(shaders[1]);
  10964. };
  10965. Engine.prototype.getError = function () {
  10966. return this._gl.getError();
  10967. };
  10968. // FPS
  10969. Engine.prototype.getFps = function () {
  10970. return this._fps;
  10971. };
  10972. Engine.prototype.getDeltaTime = function () {
  10973. return this._deltaTime;
  10974. };
  10975. Engine.prototype._measureFps = function () {
  10976. this._performanceMonitor.sampleFrame();
  10977. this._fps = this._performanceMonitor.averageFPS;
  10978. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  10979. };
  10980. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10981. if (faceIndex === void 0) { faceIndex = -1; }
  10982. var gl = this._gl;
  10983. if (!this._dummyFramebuffer) {
  10984. this._dummyFramebuffer = gl.createFramebuffer();
  10985. }
  10986. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10987. if (faceIndex > -1) {
  10988. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10989. }
  10990. else {
  10991. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10992. }
  10993. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  10994. var buffer;
  10995. switch (readType) {
  10996. case gl.UNSIGNED_BYTE:
  10997. buffer = new Uint8Array(4 * width * height);
  10998. readType = gl.UNSIGNED_BYTE;
  10999. break;
  11000. default:
  11001. buffer = new Float32Array(4 * width * height);
  11002. readType = gl.FLOAT;
  11003. break;
  11004. }
  11005. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11006. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11007. return buffer;
  11008. };
  11009. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11010. if (this._webGLVersion > 1) {
  11011. return this._caps.colorBufferFloat;
  11012. }
  11013. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11014. };
  11015. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11016. if (this._webGLVersion > 1) {
  11017. return this._caps.colorBufferFloat;
  11018. }
  11019. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11020. };
  11021. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11022. Engine.prototype._canRenderToFramebuffer = function (type) {
  11023. var gl = this._gl;
  11024. //clear existing errors
  11025. while (gl.getError() !== gl.NO_ERROR) { }
  11026. var successful = true;
  11027. var texture = gl.createTexture();
  11028. gl.bindTexture(gl.TEXTURE_2D, texture);
  11029. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11030. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11031. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11032. var fb = gl.createFramebuffer();
  11033. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11034. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11035. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11036. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11037. successful = successful && (gl.getError() === gl.NO_ERROR);
  11038. //try render by clearing frame buffer's color buffer
  11039. if (successful) {
  11040. gl.clear(gl.COLOR_BUFFER_BIT);
  11041. successful = successful && (gl.getError() === gl.NO_ERROR);
  11042. }
  11043. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11044. if (successful) {
  11045. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11046. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11047. var readFormat = gl.RGBA;
  11048. var readType = gl.UNSIGNED_BYTE;
  11049. var buffer = new Uint8Array(4);
  11050. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11051. successful = successful && (gl.getError() === gl.NO_ERROR);
  11052. }
  11053. //clean up
  11054. gl.deleteTexture(texture);
  11055. gl.deleteFramebuffer(fb);
  11056. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11057. //clear accumulated errors
  11058. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11059. return successful;
  11060. };
  11061. Engine.prototype._getWebGLTextureType = function (type) {
  11062. if (type === Engine.TEXTURETYPE_FLOAT) {
  11063. return this._gl.FLOAT;
  11064. }
  11065. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11066. // Add Half Float Constant.
  11067. return this._gl.HALF_FLOAT_OES;
  11068. }
  11069. return this._gl.UNSIGNED_BYTE;
  11070. };
  11071. ;
  11072. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11073. if (this._webGLVersion === 1) {
  11074. return this._gl.RGBA;
  11075. }
  11076. if (type === Engine.TEXTURETYPE_FLOAT) {
  11077. return this._gl.RGBA32F;
  11078. }
  11079. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11080. return this._gl.RGBA16F;
  11081. }
  11082. return this._gl.RGBA;
  11083. };
  11084. ;
  11085. Engine.prototype.createQuery = function () {
  11086. return this._gl.createQuery();
  11087. };
  11088. Engine.prototype.deleteQuery = function (query) {
  11089. this._gl.deleteQuery(query);
  11090. return this;
  11091. };
  11092. Engine.prototype.isQueryResultAvailable = function (query) {
  11093. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11094. };
  11095. Engine.prototype.getQueryResult = function (query) {
  11096. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11097. };
  11098. Engine.prototype.beginQuery = function (algorithmType, query) {
  11099. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11100. this._gl.beginQuery(glAlgorithm, query);
  11101. };
  11102. Engine.prototype.endQuery = function (algorithmType) {
  11103. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11104. this._gl.endQuery(glAlgorithm);
  11105. return this;
  11106. };
  11107. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11108. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11109. };
  11110. // Statics
  11111. Engine.isSupported = function () {
  11112. try {
  11113. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11114. if (navigator.isCocoonJS) {
  11115. return true;
  11116. }
  11117. var tempcanvas = document.createElement("canvas");
  11118. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11119. return gl != null && !!window.WebGLRenderingContext;
  11120. }
  11121. catch (e) {
  11122. return false;
  11123. }
  11124. };
  11125. Engine.Instances = new Array();
  11126. // Const statics
  11127. Engine._ALPHA_DISABLE = 0;
  11128. Engine._ALPHA_ADD = 1;
  11129. Engine._ALPHA_COMBINE = 2;
  11130. Engine._ALPHA_SUBTRACT = 3;
  11131. Engine._ALPHA_MULTIPLY = 4;
  11132. Engine._ALPHA_MAXIMIZED = 5;
  11133. Engine._ALPHA_ONEONE = 6;
  11134. Engine._ALPHA_PREMULTIPLIED = 7;
  11135. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11136. Engine._ALPHA_INTERPOLATE = 9;
  11137. Engine._ALPHA_SCREENMODE = 10;
  11138. Engine._DELAYLOADSTATE_NONE = 0;
  11139. Engine._DELAYLOADSTATE_LOADED = 1;
  11140. Engine._DELAYLOADSTATE_LOADING = 2;
  11141. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11142. Engine._TEXTUREFORMAT_ALPHA = 0;
  11143. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11144. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11145. Engine._TEXTUREFORMAT_RGB = 4;
  11146. Engine._TEXTUREFORMAT_RGBA = 5;
  11147. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11148. Engine._TEXTURETYPE_FLOAT = 1;
  11149. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11150. // Depht or Stencil test Constants.
  11151. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11152. 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.
  11153. 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.
  11154. 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.
  11155. 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.
  11156. 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.
  11157. 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.
  11158. 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.
  11159. // Stencil Actions Constants.
  11160. Engine._KEEP = 0x1E00;
  11161. Engine._REPLACE = 0x1E01;
  11162. Engine._INCR = 0x1E02;
  11163. Engine._DECR = 0x1E03;
  11164. Engine._INVERT = 0x150A;
  11165. Engine._INCR_WRAP = 0x8507;
  11166. Engine._DECR_WRAP = 0x8508;
  11167. // Texture rescaling mode
  11168. Engine._SCALEMODE_FLOOR = 1;
  11169. Engine._SCALEMODE_NEAREST = 2;
  11170. Engine._SCALEMODE_CEILING = 3;
  11171. // Updatable statics so stick with vars here
  11172. Engine.CollisionsEpsilon = 0.001;
  11173. Engine.CodeRepository = "src/";
  11174. Engine.ShadersRepository = "src/Shaders/";
  11175. return Engine;
  11176. }());
  11177. BABYLON.Engine = Engine;
  11178. })(BABYLON || (BABYLON = {}));
  11179. //# sourceMappingURL=babylon.engine.js.map
  11180. /// <reference path="Tools\babylon.decorators.ts" />
  11181. var BABYLON;
  11182. (function (BABYLON) {
  11183. /**
  11184. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11185. */
  11186. var Node = (function () {
  11187. /**
  11188. * @constructor
  11189. * @param {string} name - the name and id to be given to this node
  11190. * @param {BABYLON.Scene} the scene this node will be added to
  11191. */
  11192. function Node(name, scene) {
  11193. this.state = "";
  11194. this.metadata = null;
  11195. this.doNotSerialize = false;
  11196. this.animations = new Array();
  11197. this._ranges = {};
  11198. this._childrenFlag = -1;
  11199. this._isEnabled = true;
  11200. this._isReady = true;
  11201. this._currentRenderId = -1;
  11202. this._parentRenderId = -1;
  11203. /**
  11204. * An event triggered when the mesh is disposed.
  11205. * @type {BABYLON.Observable}
  11206. */
  11207. this.onDisposeObservable = new BABYLON.Observable();
  11208. // Behaviors
  11209. this._behaviors = new Array();
  11210. this.name = name;
  11211. this.id = name;
  11212. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11213. this._initCache();
  11214. }
  11215. Object.defineProperty(Node.prototype, "parent", {
  11216. get: function () {
  11217. return this._parentNode;
  11218. },
  11219. set: function (parent) {
  11220. if (this._parentNode === parent) {
  11221. return;
  11222. }
  11223. if (this._parentNode) {
  11224. var index = this._parentNode._children.indexOf(this);
  11225. if (index !== -1) {
  11226. this._parentNode._children.splice(index, 1);
  11227. }
  11228. }
  11229. this._parentNode = parent;
  11230. if (this._parentNode) {
  11231. if (!this._parentNode._children) {
  11232. this._parentNode._children = new Array();
  11233. }
  11234. this._parentNode._children.push(this);
  11235. }
  11236. },
  11237. enumerable: true,
  11238. configurable: true
  11239. });
  11240. Node.prototype.getClassName = function () {
  11241. return "Node";
  11242. };
  11243. Object.defineProperty(Node.prototype, "onDispose", {
  11244. set: function (callback) {
  11245. if (this._onDisposeObserver) {
  11246. this.onDisposeObservable.remove(this._onDisposeObserver);
  11247. }
  11248. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11249. },
  11250. enumerable: true,
  11251. configurable: true
  11252. });
  11253. Node.prototype.getScene = function () {
  11254. return this._scene;
  11255. };
  11256. Node.prototype.getEngine = function () {
  11257. return this._scene.getEngine();
  11258. };
  11259. Node.prototype.addBehavior = function (behavior) {
  11260. var index = this._behaviors.indexOf(behavior);
  11261. if (index !== -1) {
  11262. return;
  11263. }
  11264. behavior.attach(this);
  11265. this._behaviors.push(behavior);
  11266. return this;
  11267. };
  11268. Node.prototype.removeBehavior = function (behavior) {
  11269. var index = this._behaviors.indexOf(behavior);
  11270. if (index === -1) {
  11271. return;
  11272. }
  11273. this._behaviors[index].detach();
  11274. this._behaviors.splice(index, 1);
  11275. return this;
  11276. };
  11277. Object.defineProperty(Node.prototype, "behaviors", {
  11278. get: function () {
  11279. return this._behaviors;
  11280. },
  11281. enumerable: true,
  11282. configurable: true
  11283. });
  11284. Node.prototype.getBehaviorByName = function (name) {
  11285. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11286. var behavior = _a[_i];
  11287. if (behavior.name === name) {
  11288. return behavior;
  11289. }
  11290. }
  11291. return null;
  11292. };
  11293. // override it in derived class
  11294. Node.prototype.getWorldMatrix = function () {
  11295. return BABYLON.Matrix.Identity();
  11296. };
  11297. // override it in derived class if you add new variables to the cache
  11298. // and call the parent class method
  11299. Node.prototype._initCache = function () {
  11300. this._cache = {};
  11301. this._cache.parent = undefined;
  11302. };
  11303. Node.prototype.updateCache = function (force) {
  11304. if (!force && this.isSynchronized())
  11305. return;
  11306. this._cache.parent = this.parent;
  11307. this._updateCache();
  11308. };
  11309. // override it in derived class if you add new variables to the cache
  11310. // and call the parent class method if !ignoreParentClass
  11311. Node.prototype._updateCache = function (ignoreParentClass) {
  11312. };
  11313. // override it in derived class if you add new variables to the cache
  11314. Node.prototype._isSynchronized = function () {
  11315. return true;
  11316. };
  11317. Node.prototype._markSyncedWithParent = function () {
  11318. this._parentRenderId = this.parent._currentRenderId;
  11319. };
  11320. Node.prototype.isSynchronizedWithParent = function () {
  11321. if (!this.parent) {
  11322. return true;
  11323. }
  11324. if (this._parentRenderId !== this.parent._currentRenderId) {
  11325. return false;
  11326. }
  11327. return this.parent.isSynchronized();
  11328. };
  11329. Node.prototype.isSynchronized = function (updateCache) {
  11330. var check = this.hasNewParent();
  11331. check = check || !this.isSynchronizedWithParent();
  11332. check = check || !this._isSynchronized();
  11333. if (updateCache)
  11334. this.updateCache(true);
  11335. return !check;
  11336. };
  11337. Node.prototype.hasNewParent = function (update) {
  11338. if (this._cache.parent === this.parent)
  11339. return false;
  11340. if (update)
  11341. this._cache.parent = this.parent;
  11342. return true;
  11343. };
  11344. /**
  11345. * Is this node ready to be used/rendered
  11346. * @return {boolean} is it ready
  11347. */
  11348. Node.prototype.isReady = function () {
  11349. return this._isReady;
  11350. };
  11351. /**
  11352. * Is this node enabled.
  11353. * If the node has a parent and is enabled, the parent will be inspected as well.
  11354. * @return {boolean} whether this node (and its parent) is enabled.
  11355. * @see setEnabled
  11356. */
  11357. Node.prototype.isEnabled = function () {
  11358. if (!this._isEnabled) {
  11359. return false;
  11360. }
  11361. if (this.parent) {
  11362. return this.parent.isEnabled();
  11363. }
  11364. return true;
  11365. };
  11366. /**
  11367. * Set the enabled state of this node.
  11368. * @param {boolean} value - the new enabled state
  11369. * @see isEnabled
  11370. */
  11371. Node.prototype.setEnabled = function (value) {
  11372. this._isEnabled = value;
  11373. };
  11374. /**
  11375. * Is this node a descendant of the given node.
  11376. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11377. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11378. * @see parent
  11379. */
  11380. Node.prototype.isDescendantOf = function (ancestor) {
  11381. if (this.parent) {
  11382. if (this.parent === ancestor) {
  11383. return true;
  11384. }
  11385. return this.parent.isDescendantOf(ancestor);
  11386. }
  11387. return false;
  11388. };
  11389. /**
  11390. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11391. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11392. * @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.
  11393. * @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.
  11394. */
  11395. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11396. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11397. if (!this._children) {
  11398. return;
  11399. }
  11400. for (var index = 0; index < this._children.length; index++) {
  11401. var item = this._children[index];
  11402. if (!predicate || predicate(item)) {
  11403. results.push(item);
  11404. }
  11405. if (!directDescendantsOnly) {
  11406. item._getDescendants(results, false, predicate);
  11407. }
  11408. }
  11409. };
  11410. /**
  11411. * Will return all nodes that have this node as ascendant.
  11412. * @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.
  11413. * @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.
  11414. * @return {BABYLON.Node[]} all children nodes of all types.
  11415. */
  11416. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11417. var results = [];
  11418. this._getDescendants(results, directDescendantsOnly, predicate);
  11419. return results;
  11420. };
  11421. /**
  11422. * Get all child-meshes of this node.
  11423. */
  11424. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11425. var results = [];
  11426. this._getDescendants(results, directDecendantsOnly, function (node) {
  11427. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11428. });
  11429. return results;
  11430. };
  11431. /**
  11432. * Get all direct children of this node.
  11433. */
  11434. Node.prototype.getChildren = function (predicate) {
  11435. return this.getDescendants(true, predicate);
  11436. };
  11437. Node.prototype._setReady = function (state) {
  11438. if (state === this._isReady) {
  11439. return;
  11440. }
  11441. if (!state) {
  11442. this._isReady = false;
  11443. return;
  11444. }
  11445. this._isReady = true;
  11446. if (this.onReady) {
  11447. this.onReady(this);
  11448. }
  11449. };
  11450. Node.prototype.getAnimationByName = function (name) {
  11451. for (var i = 0; i < this.animations.length; i++) {
  11452. var animation = this.animations[i];
  11453. if (animation.name === name) {
  11454. return animation;
  11455. }
  11456. }
  11457. return null;
  11458. };
  11459. Node.prototype.createAnimationRange = function (name, from, to) {
  11460. // check name not already in use
  11461. if (!this._ranges[name]) {
  11462. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11463. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11464. if (this.animations[i]) {
  11465. this.animations[i].createRange(name, from, to);
  11466. }
  11467. }
  11468. }
  11469. };
  11470. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11471. if (deleteFrames === void 0) { deleteFrames = true; }
  11472. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11473. if (this.animations[i]) {
  11474. this.animations[i].deleteRange(name, deleteFrames);
  11475. }
  11476. }
  11477. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11478. };
  11479. Node.prototype.getAnimationRange = function (name) {
  11480. return this._ranges[name];
  11481. };
  11482. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11483. var range = this.getAnimationRange(name);
  11484. if (!range) {
  11485. return null;
  11486. }
  11487. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11488. };
  11489. Node.prototype.serializeAnimationRanges = function () {
  11490. var serializationRanges = [];
  11491. for (var name in this._ranges) {
  11492. var range = {};
  11493. range.name = name;
  11494. range.from = this._ranges[name].from;
  11495. range.to = this._ranges[name].to;
  11496. serializationRanges.push(range);
  11497. }
  11498. return serializationRanges;
  11499. };
  11500. Node.prototype.dispose = function () {
  11501. this.parent = null;
  11502. // Callback
  11503. this.onDisposeObservable.notifyObservers(this);
  11504. this.onDisposeObservable.clear();
  11505. // Behaviors
  11506. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11507. var behavior = _a[_i];
  11508. behavior.detach();
  11509. }
  11510. this._behaviors = [];
  11511. };
  11512. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11513. if (parsedNode.ranges) {
  11514. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11515. var data = parsedNode.ranges[index];
  11516. node.createAnimationRange(data.name, data.from, data.to);
  11517. }
  11518. }
  11519. };
  11520. __decorate([
  11521. BABYLON.serialize()
  11522. ], Node.prototype, "name", void 0);
  11523. __decorate([
  11524. BABYLON.serialize()
  11525. ], Node.prototype, "id", void 0);
  11526. __decorate([
  11527. BABYLON.serialize()
  11528. ], Node.prototype, "uniqueId", void 0);
  11529. __decorate([
  11530. BABYLON.serialize()
  11531. ], Node.prototype, "state", void 0);
  11532. __decorate([
  11533. BABYLON.serialize()
  11534. ], Node.prototype, "metadata", void 0);
  11535. return Node;
  11536. }());
  11537. BABYLON.Node = Node;
  11538. })(BABYLON || (BABYLON = {}));
  11539. //# sourceMappingURL=babylon.node.js.map
  11540. var BABYLON;
  11541. (function (BABYLON) {
  11542. var BoundingSphere = (function () {
  11543. function BoundingSphere(minimum, maximum) {
  11544. this.minimum = minimum;
  11545. this.maximum = maximum;
  11546. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11547. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11548. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11549. this.radius = distance * 0.5;
  11550. this.centerWorld = BABYLON.Vector3.Zero();
  11551. this._update(BABYLON.Matrix.Identity());
  11552. }
  11553. // Methods
  11554. BoundingSphere.prototype._update = function (world) {
  11555. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11556. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11557. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11558. };
  11559. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11560. for (var i = 0; i < 6; i++) {
  11561. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11562. return false;
  11563. }
  11564. return true;
  11565. };
  11566. BoundingSphere.prototype.intersectsPoint = function (point) {
  11567. var x = this.centerWorld.x - point.x;
  11568. var y = this.centerWorld.y - point.y;
  11569. var z = this.centerWorld.z - point.z;
  11570. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11571. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11572. return false;
  11573. return true;
  11574. };
  11575. // Statics
  11576. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11577. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11578. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11579. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11580. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11581. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11582. return false;
  11583. return true;
  11584. };
  11585. return BoundingSphere;
  11586. }());
  11587. BABYLON.BoundingSphere = BoundingSphere;
  11588. })(BABYLON || (BABYLON = {}));
  11589. //# sourceMappingURL=babylon.boundingSphere.js.map
  11590. var BABYLON;
  11591. (function (BABYLON) {
  11592. var BoundingBox = (function () {
  11593. function BoundingBox(minimum, maximum) {
  11594. this.minimum = minimum;
  11595. this.maximum = maximum;
  11596. this.vectors = new Array();
  11597. this.vectorsWorld = new Array();
  11598. // Bounding vectors
  11599. this.vectors.push(this.minimum.clone());
  11600. this.vectors.push(this.maximum.clone());
  11601. this.vectors.push(this.minimum.clone());
  11602. this.vectors[2].x = this.maximum.x;
  11603. this.vectors.push(this.minimum.clone());
  11604. this.vectors[3].y = this.maximum.y;
  11605. this.vectors.push(this.minimum.clone());
  11606. this.vectors[4].z = this.maximum.z;
  11607. this.vectors.push(this.maximum.clone());
  11608. this.vectors[5].z = this.minimum.z;
  11609. this.vectors.push(this.maximum.clone());
  11610. this.vectors[6].x = this.minimum.x;
  11611. this.vectors.push(this.maximum.clone());
  11612. this.vectors[7].y = this.minimum.y;
  11613. // OBB
  11614. this.center = this.maximum.add(this.minimum).scale(0.5);
  11615. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11616. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11617. // World
  11618. for (var index = 0; index < this.vectors.length; index++) {
  11619. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11620. }
  11621. this.minimumWorld = BABYLON.Vector3.Zero();
  11622. this.maximumWorld = BABYLON.Vector3.Zero();
  11623. this.centerWorld = BABYLON.Vector3.Zero();
  11624. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11625. this._update(BABYLON.Matrix.Identity());
  11626. }
  11627. // Methods
  11628. BoundingBox.prototype.getWorldMatrix = function () {
  11629. return this._worldMatrix;
  11630. };
  11631. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11632. this._worldMatrix.copyFrom(matrix);
  11633. return this;
  11634. };
  11635. BoundingBox.prototype._update = function (world) {
  11636. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11637. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11638. for (var index = 0; index < this.vectors.length; index++) {
  11639. var v = this.vectorsWorld[index];
  11640. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11641. if (v.x < this.minimumWorld.x)
  11642. this.minimumWorld.x = v.x;
  11643. if (v.y < this.minimumWorld.y)
  11644. this.minimumWorld.y = v.y;
  11645. if (v.z < this.minimumWorld.z)
  11646. this.minimumWorld.z = v.z;
  11647. if (v.x > this.maximumWorld.x)
  11648. this.maximumWorld.x = v.x;
  11649. if (v.y > this.maximumWorld.y)
  11650. this.maximumWorld.y = v.y;
  11651. if (v.z > this.maximumWorld.z)
  11652. this.maximumWorld.z = v.z;
  11653. }
  11654. // Extend
  11655. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11656. this.extendSizeWorld.scaleInPlace(0.5);
  11657. // OBB
  11658. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11659. this.centerWorld.scaleInPlace(0.5);
  11660. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11661. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11662. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11663. this._worldMatrix = world;
  11664. };
  11665. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11666. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11667. };
  11668. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11669. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11670. };
  11671. BoundingBox.prototype.intersectsPoint = function (point) {
  11672. var delta = -BABYLON.Epsilon;
  11673. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11674. return false;
  11675. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11676. return false;
  11677. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11678. return false;
  11679. return true;
  11680. };
  11681. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11682. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11683. };
  11684. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11685. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11686. return false;
  11687. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11688. return false;
  11689. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11690. return false;
  11691. return true;
  11692. };
  11693. // Statics
  11694. BoundingBox.Intersects = function (box0, box1) {
  11695. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11696. return false;
  11697. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11698. return false;
  11699. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11700. return false;
  11701. return true;
  11702. };
  11703. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11704. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11705. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11706. return (num <= (sphereRadius * sphereRadius));
  11707. };
  11708. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11709. for (var p = 0; p < 6; p++) {
  11710. for (var i = 0; i < 8; i++) {
  11711. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11712. return false;
  11713. }
  11714. }
  11715. }
  11716. return true;
  11717. };
  11718. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11719. for (var p = 0; p < 6; p++) {
  11720. var inCount = 8;
  11721. for (var i = 0; i < 8; i++) {
  11722. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11723. --inCount;
  11724. }
  11725. else {
  11726. break;
  11727. }
  11728. }
  11729. if (inCount === 0)
  11730. return false;
  11731. }
  11732. return true;
  11733. };
  11734. return BoundingBox;
  11735. }());
  11736. BABYLON.BoundingBox = BoundingBox;
  11737. })(BABYLON || (BABYLON = {}));
  11738. //# sourceMappingURL=babylon.boundingBox.js.map
  11739. var BABYLON;
  11740. (function (BABYLON) {
  11741. var computeBoxExtents = function (axis, box) {
  11742. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11743. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11744. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11745. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11746. var r = r0 + r1 + r2;
  11747. return {
  11748. min: p - r,
  11749. max: p + r
  11750. };
  11751. };
  11752. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11753. var axisOverlap = function (axis, box0, box1) {
  11754. var result0 = computeBoxExtents(axis, box0);
  11755. var result1 = computeBoxExtents(axis, box1);
  11756. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11757. };
  11758. var BoundingInfo = (function () {
  11759. function BoundingInfo(minimum, maximum) {
  11760. this.minimum = minimum;
  11761. this.maximum = maximum;
  11762. this._isLocked = false;
  11763. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11764. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11765. }
  11766. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11767. get: function () {
  11768. return this._isLocked;
  11769. },
  11770. set: function (value) {
  11771. this._isLocked = value;
  11772. },
  11773. enumerable: true,
  11774. configurable: true
  11775. });
  11776. // Methods
  11777. BoundingInfo.prototype.update = function (world) {
  11778. if (this._isLocked) {
  11779. return;
  11780. }
  11781. this.boundingBox._update(world);
  11782. this.boundingSphere._update(world);
  11783. };
  11784. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11785. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11786. return false;
  11787. return this.boundingBox.isInFrustum(frustumPlanes);
  11788. };
  11789. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  11790. /**
  11791. * Gets the world distance between the min and max points of the bounding box
  11792. */
  11793. get: function () {
  11794. var boundingBox = this.boundingBox;
  11795. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  11796. return size.length();
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11802. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11803. };
  11804. BoundingInfo.prototype._checkCollision = function (collider) {
  11805. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11806. };
  11807. BoundingInfo.prototype.intersectsPoint = function (point) {
  11808. if (!this.boundingSphere.centerWorld) {
  11809. return false;
  11810. }
  11811. if (!this.boundingSphere.intersectsPoint(point)) {
  11812. return false;
  11813. }
  11814. if (!this.boundingBox.intersectsPoint(point)) {
  11815. return false;
  11816. }
  11817. return true;
  11818. };
  11819. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11820. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11821. return false;
  11822. }
  11823. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11824. return false;
  11825. }
  11826. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11827. return false;
  11828. }
  11829. if (!precise) {
  11830. return true;
  11831. }
  11832. var box0 = this.boundingBox;
  11833. var box1 = boundingInfo.boundingBox;
  11834. if (!axisOverlap(box0.directions[0], box0, box1))
  11835. return false;
  11836. if (!axisOverlap(box0.directions[1], box0, box1))
  11837. return false;
  11838. if (!axisOverlap(box0.directions[2], box0, box1))
  11839. return false;
  11840. if (!axisOverlap(box1.directions[0], box0, box1))
  11841. return false;
  11842. if (!axisOverlap(box1.directions[1], box0, box1))
  11843. return false;
  11844. if (!axisOverlap(box1.directions[2], box0, box1))
  11845. return false;
  11846. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11847. return false;
  11848. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11849. return false;
  11850. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11851. return false;
  11852. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11853. return false;
  11854. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11855. return false;
  11856. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11857. return false;
  11858. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11859. return false;
  11860. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11861. return false;
  11862. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11863. return false;
  11864. return true;
  11865. };
  11866. return BoundingInfo;
  11867. }());
  11868. BABYLON.BoundingInfo = BoundingInfo;
  11869. })(BABYLON || (BABYLON = {}));
  11870. //# sourceMappingURL=babylon.boundingInfo.js.map
  11871. var BABYLON;
  11872. (function (BABYLON) {
  11873. var AbstractMesh = (function (_super) {
  11874. __extends(AbstractMesh, _super);
  11875. // Constructor
  11876. function AbstractMesh(name, scene) {
  11877. var _this = _super.call(this, name, scene) || this;
  11878. _this._facetNb = 0; // facet number
  11879. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11880. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11881. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11882. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11883. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11884. _this._subDiv = {
  11885. max: 1,
  11886. X: 1,
  11887. Y: 1,
  11888. Z: 1
  11889. };
  11890. // Events
  11891. /**
  11892. * An event triggered when this mesh collides with another one
  11893. * @type {BABYLON.Observable}
  11894. */
  11895. _this.onCollideObservable = new BABYLON.Observable();
  11896. /**
  11897. * An event triggered when the collision's position changes
  11898. * @type {BABYLON.Observable}
  11899. */
  11900. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11901. /**
  11902. * An event triggered after the world matrix is updated
  11903. * @type {BABYLON.Observable}
  11904. */
  11905. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11906. /**
  11907. * An event triggered when material is changed
  11908. * @type {BABYLON.Observable}
  11909. */
  11910. _this.onMaterialChangedObservable = new BABYLON.Observable();
  11911. // Properties
  11912. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11913. _this.position = BABYLON.Vector3.Zero();
  11914. /**
  11915. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  11916. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  11917. * or
  11918. * 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.
  11919. * for more info check WebGl documentations
  11920. */
  11921. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  11922. /**
  11923. * 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:
  11924. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  11925. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  11926. * 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.
  11927. */
  11928. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  11929. /**
  11930. * 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.
  11931. * The default value is -1 which means don't break the query and wait till the result.
  11932. */
  11933. _this.occlusionRetryCount = -1;
  11934. _this._occlusionInternalRetryCounter = 0;
  11935. _this._isOccluded = false;
  11936. _this._isOcclusionQueryInProgress = false;
  11937. _this._rotation = BABYLON.Vector3.Zero();
  11938. _this._scaling = BABYLON.Vector3.One();
  11939. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11940. _this.visibility = 1.0;
  11941. _this.alphaIndex = Number.MAX_VALUE;
  11942. _this.infiniteDistance = false;
  11943. _this.isVisible = true;
  11944. _this.isPickable = true;
  11945. _this.showBoundingBox = false;
  11946. _this.showSubMeshesBoundingBox = false;
  11947. _this.isBlocker = false;
  11948. _this.enablePointerMoveEvents = false;
  11949. _this.renderingGroupId = 0;
  11950. _this._receiveShadows = false;
  11951. _this.renderOutline = false;
  11952. _this.outlineColor = BABYLON.Color3.Red();
  11953. _this.outlineWidth = 0.02;
  11954. _this.renderOverlay = false;
  11955. _this.overlayColor = BABYLON.Color3.Red();
  11956. _this.overlayAlpha = 0.5;
  11957. _this._hasVertexAlpha = false;
  11958. _this._useVertexColors = true;
  11959. _this._computeBonesUsingShaders = true;
  11960. _this._numBoneInfluencers = 4;
  11961. _this._applyFog = true;
  11962. _this.scalingDeterminant = 1;
  11963. _this.useOctreeForRenderingSelection = true;
  11964. _this.useOctreeForPicking = true;
  11965. _this.useOctreeForCollisions = true;
  11966. _this._layerMask = 0x0FFFFFFF;
  11967. /**
  11968. * True if the mesh must be rendered in any case.
  11969. */
  11970. _this.alwaysSelectAsActiveMesh = false;
  11971. // Collisions
  11972. _this._checkCollisions = false;
  11973. _this._collisionMask = -1;
  11974. _this._collisionGroup = -1;
  11975. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11976. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11977. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11978. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11979. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11980. // Edges
  11981. _this.edgesWidth = 1;
  11982. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11983. // Cache
  11984. _this._localWorld = BABYLON.Matrix.Zero();
  11985. _this._worldMatrix = BABYLON.Matrix.Zero();
  11986. _this._absolutePosition = BABYLON.Vector3.Zero();
  11987. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11988. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11989. _this._isDirty = false;
  11990. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11991. _this._isDisposed = false;
  11992. _this._renderId = 0;
  11993. _this._intersectionsInProgress = new Array();
  11994. _this._isWorldMatrixFrozen = false;
  11995. _this._unIndexed = false;
  11996. _this._lightSources = new Array();
  11997. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11998. if (collidedMesh === void 0) { collidedMesh = null; }
  11999. //TODO move this to the collision coordinator!
  12000. if (_this.getScene().workerCollisions)
  12001. newPosition.multiplyInPlace(_this._collider.radius);
  12002. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12003. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12004. _this.position.addInPlace(_this._diffPositionForCollisions);
  12005. }
  12006. if (collidedMesh) {
  12007. _this.onCollideObservable.notifyObservers(collidedMesh);
  12008. }
  12009. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12010. };
  12011. _this.getScene().addMesh(_this);
  12012. _this._resyncLightSources();
  12013. return _this;
  12014. }
  12015. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12016. get: function () {
  12017. return AbstractMesh._BILLBOARDMODE_NONE;
  12018. },
  12019. enumerable: true,
  12020. configurable: true
  12021. });
  12022. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12023. get: function () {
  12024. return AbstractMesh._BILLBOARDMODE_X;
  12025. },
  12026. enumerable: true,
  12027. configurable: true
  12028. });
  12029. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12030. get: function () {
  12031. return AbstractMesh._BILLBOARDMODE_Y;
  12032. },
  12033. enumerable: true,
  12034. configurable: true
  12035. });
  12036. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12037. get: function () {
  12038. return AbstractMesh._BILLBOARDMODE_Z;
  12039. },
  12040. enumerable: true,
  12041. configurable: true
  12042. });
  12043. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12044. get: function () {
  12045. return AbstractMesh._BILLBOARDMODE_ALL;
  12046. },
  12047. enumerable: true,
  12048. configurable: true
  12049. });
  12050. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12051. /**
  12052. * Read-only : the number of facets in the mesh
  12053. */
  12054. get: function () {
  12055. return this._facetNb;
  12056. },
  12057. enumerable: true,
  12058. configurable: true
  12059. });
  12060. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12061. /**
  12062. * The number (integer) of subdivisions per axis in the partioning space
  12063. */
  12064. get: function () {
  12065. return this._partitioningSubdivisions;
  12066. },
  12067. set: function (nb) {
  12068. this._partitioningSubdivisions = nb;
  12069. },
  12070. enumerable: true,
  12071. configurable: true
  12072. });
  12073. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12074. /**
  12075. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12076. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12077. */
  12078. get: function () {
  12079. return this._partitioningBBoxRatio;
  12080. },
  12081. set: function (ratio) {
  12082. this._partitioningBBoxRatio = ratio;
  12083. },
  12084. enumerable: true,
  12085. configurable: true
  12086. });
  12087. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12088. /**
  12089. * Read-only boolean : is the feature facetData enabled ?
  12090. */
  12091. get: function () {
  12092. return this._facetDataEnabled;
  12093. },
  12094. enumerable: true,
  12095. configurable: true
  12096. });
  12097. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12098. set: function (callback) {
  12099. if (this._onCollideObserver) {
  12100. this.onCollideObservable.remove(this._onCollideObserver);
  12101. }
  12102. this._onCollideObserver = this.onCollideObservable.add(callback);
  12103. },
  12104. enumerable: true,
  12105. configurable: true
  12106. });
  12107. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12108. set: function (callback) {
  12109. if (this._onCollisionPositionChangeObserver) {
  12110. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12111. }
  12112. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12113. },
  12114. enumerable: true,
  12115. configurable: true
  12116. });
  12117. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12118. /**
  12119. * 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.
  12120. */
  12121. get: function () {
  12122. return this._isOccluded;
  12123. },
  12124. set: function (value) {
  12125. this._isOccluded = value;
  12126. },
  12127. enumerable: true,
  12128. configurable: true
  12129. });
  12130. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12131. /**
  12132. * Flag to check the progress status of the query
  12133. */
  12134. get: function () {
  12135. return this._isOcclusionQueryInProgress;
  12136. },
  12137. enumerable: true,
  12138. configurable: true
  12139. });
  12140. Object.defineProperty(AbstractMesh.prototype, "material", {
  12141. get: function () {
  12142. return this._material;
  12143. },
  12144. set: function (value) {
  12145. if (this._material === value) {
  12146. return;
  12147. }
  12148. this._material = value;
  12149. if (this.onMaterialChangedObservable.hasObservers) {
  12150. this.onMaterialChangedObservable.notifyObservers(this);
  12151. }
  12152. if (!this.subMeshes) {
  12153. return;
  12154. }
  12155. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12156. var subMesh = _a[_i];
  12157. subMesh.setEffect(null);
  12158. }
  12159. },
  12160. enumerable: true,
  12161. configurable: true
  12162. });
  12163. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12164. get: function () {
  12165. return this._receiveShadows;
  12166. },
  12167. set: function (value) {
  12168. if (this._receiveShadows === value) {
  12169. return;
  12170. }
  12171. this._receiveShadows = value;
  12172. this._markSubMeshesAsLightDirty();
  12173. },
  12174. enumerable: true,
  12175. configurable: true
  12176. });
  12177. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12178. get: function () {
  12179. return this._hasVertexAlpha;
  12180. },
  12181. set: function (value) {
  12182. if (this._hasVertexAlpha === value) {
  12183. return;
  12184. }
  12185. this._hasVertexAlpha = value;
  12186. this._markSubMeshesAsAttributesDirty();
  12187. },
  12188. enumerable: true,
  12189. configurable: true
  12190. });
  12191. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12192. get: function () {
  12193. return this._useVertexColors;
  12194. },
  12195. set: function (value) {
  12196. if (this._useVertexColors === value) {
  12197. return;
  12198. }
  12199. this._useVertexColors = value;
  12200. this._markSubMeshesAsAttributesDirty();
  12201. },
  12202. enumerable: true,
  12203. configurable: true
  12204. });
  12205. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12206. get: function () {
  12207. return this._computeBonesUsingShaders;
  12208. },
  12209. set: function (value) {
  12210. if (this._computeBonesUsingShaders === value) {
  12211. return;
  12212. }
  12213. this._computeBonesUsingShaders = value;
  12214. this._markSubMeshesAsAttributesDirty();
  12215. },
  12216. enumerable: true,
  12217. configurable: true
  12218. });
  12219. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12220. get: function () {
  12221. return this._numBoneInfluencers;
  12222. },
  12223. set: function (value) {
  12224. if (this._numBoneInfluencers === value) {
  12225. return;
  12226. }
  12227. this._numBoneInfluencers = value;
  12228. this._markSubMeshesAsAttributesDirty();
  12229. },
  12230. enumerable: true,
  12231. configurable: true
  12232. });
  12233. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12234. get: function () {
  12235. return this._applyFog;
  12236. },
  12237. set: function (value) {
  12238. if (this._applyFog === value) {
  12239. return;
  12240. }
  12241. this._applyFog = value;
  12242. this._markSubMeshesAsMiscDirty();
  12243. },
  12244. enumerable: true,
  12245. configurable: true
  12246. });
  12247. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12248. get: function () {
  12249. return this._layerMask;
  12250. },
  12251. set: function (value) {
  12252. if (value === this._layerMask) {
  12253. return;
  12254. }
  12255. this._layerMask = value;
  12256. this._resyncLightSources();
  12257. },
  12258. enumerable: true,
  12259. configurable: true
  12260. });
  12261. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12262. get: function () {
  12263. return this._collisionMask;
  12264. },
  12265. set: function (mask) {
  12266. this._collisionMask = !isNaN(mask) ? mask : -1;
  12267. },
  12268. enumerable: true,
  12269. configurable: true
  12270. });
  12271. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12272. get: function () {
  12273. return this._collisionGroup;
  12274. },
  12275. set: function (mask) {
  12276. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12277. },
  12278. enumerable: true,
  12279. configurable: true
  12280. });
  12281. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12282. get: function () {
  12283. return null;
  12284. },
  12285. enumerable: true,
  12286. configurable: true
  12287. });
  12288. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12289. get: function () {
  12290. return this._skeleton;
  12291. },
  12292. set: function (value) {
  12293. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12294. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12295. }
  12296. if (value && value.needInitialSkinMatrix) {
  12297. value._registerMeshWithPoseMatrix(this);
  12298. }
  12299. this._skeleton = value;
  12300. if (!this._skeleton) {
  12301. this._bonesTransformMatrices = null;
  12302. }
  12303. this._markSubMeshesAsAttributesDirty();
  12304. },
  12305. enumerable: true,
  12306. configurable: true
  12307. });
  12308. /**
  12309. * Boolean : true if the mesh has been disposed.
  12310. */
  12311. AbstractMesh.prototype.isDisposed = function () {
  12312. return this._isDisposed;
  12313. };
  12314. /**
  12315. * Returns the string "AbstractMesh"
  12316. */
  12317. AbstractMesh.prototype.getClassName = function () {
  12318. return "AbstractMesh";
  12319. };
  12320. /**
  12321. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12322. */
  12323. AbstractMesh.prototype.toString = function (fullDetails) {
  12324. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12325. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12326. if (this._skeleton) {
  12327. ret += ", skeleton: " + this._skeleton.name;
  12328. }
  12329. if (fullDetails) {
  12330. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12331. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12332. }
  12333. return ret;
  12334. };
  12335. AbstractMesh.prototype._rebuild = function () {
  12336. if (this._occlusionQuery) {
  12337. this._occlusionQuery = null;
  12338. }
  12339. if (this._edgesRenderer) {
  12340. this._edgesRenderer._rebuild();
  12341. }
  12342. if (!this.subMeshes) {
  12343. return;
  12344. }
  12345. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12346. var subMesh = _a[_i];
  12347. subMesh._rebuild();
  12348. }
  12349. };
  12350. AbstractMesh.prototype._resyncLightSources = function () {
  12351. this._lightSources.length = 0;
  12352. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12353. var light = _a[_i];
  12354. if (!light.isEnabled()) {
  12355. continue;
  12356. }
  12357. if (light.canAffectMesh(this)) {
  12358. this._lightSources.push(light);
  12359. }
  12360. }
  12361. this._markSubMeshesAsLightDirty();
  12362. };
  12363. AbstractMesh.prototype._resyncLighSource = function (light) {
  12364. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12365. var index = this._lightSources.indexOf(light);
  12366. if (index === -1) {
  12367. if (!isIn) {
  12368. return;
  12369. }
  12370. this._lightSources.push(light);
  12371. }
  12372. else {
  12373. if (isIn) {
  12374. return;
  12375. }
  12376. this._lightSources.splice(index, 1);
  12377. }
  12378. this._markSubMeshesAsLightDirty();
  12379. };
  12380. AbstractMesh.prototype._removeLightSource = function (light) {
  12381. var index = this._lightSources.indexOf(light);
  12382. if (index === -1) {
  12383. return;
  12384. }
  12385. this._lightSources.splice(index, 1);
  12386. };
  12387. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12388. if (!this.subMeshes) {
  12389. return;
  12390. }
  12391. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12392. var subMesh = _a[_i];
  12393. if (subMesh._materialDefines) {
  12394. func(subMesh._materialDefines);
  12395. }
  12396. }
  12397. };
  12398. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12399. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12400. };
  12401. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12402. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12403. };
  12404. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12405. if (!this.subMeshes) {
  12406. return;
  12407. }
  12408. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12409. var subMesh = _a[_i];
  12410. var material = subMesh.getMaterial();
  12411. if (material) {
  12412. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12413. }
  12414. }
  12415. };
  12416. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12417. /**
  12418. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12419. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12420. * Default : (0.0, 0.0, 0.0)
  12421. */
  12422. get: function () {
  12423. return this._rotation;
  12424. },
  12425. set: function (newRotation) {
  12426. this._rotation = newRotation;
  12427. },
  12428. enumerable: true,
  12429. configurable: true
  12430. });
  12431. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12432. /**
  12433. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12434. * Default : (1.0, 1.0, 1.0)
  12435. */
  12436. get: function () {
  12437. return this._scaling;
  12438. },
  12439. set: function (newScaling) {
  12440. this._scaling = newScaling;
  12441. if (this.physicsImpostor) {
  12442. this.physicsImpostor.forceUpdate();
  12443. }
  12444. },
  12445. enumerable: true,
  12446. configurable: true
  12447. });
  12448. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12449. /**
  12450. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12451. * It's null by default.
  12452. * 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)
  12453. */
  12454. get: function () {
  12455. return this._rotationQuaternion;
  12456. },
  12457. set: function (quaternion) {
  12458. this._rotationQuaternion = quaternion;
  12459. //reset the rotation vector.
  12460. if (quaternion && this.rotation.length()) {
  12461. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12462. }
  12463. },
  12464. enumerable: true,
  12465. configurable: true
  12466. });
  12467. // Methods
  12468. /**
  12469. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12470. * Returns the AbstractMesh.
  12471. */
  12472. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12473. this._poseMatrix.copyFrom(matrix);
  12474. return this;
  12475. };
  12476. /**
  12477. * Returns the mesh Pose matrix.
  12478. * Returned object : Matrix
  12479. */
  12480. AbstractMesh.prototype.getPoseMatrix = function () {
  12481. return this._poseMatrix;
  12482. };
  12483. /**
  12484. * Disables the mesh edger rendering mode.
  12485. * Returns the AbstractMesh.
  12486. */
  12487. AbstractMesh.prototype.disableEdgesRendering = function () {
  12488. if (this._edgesRenderer !== undefined) {
  12489. this._edgesRenderer.dispose();
  12490. this._edgesRenderer = undefined;
  12491. }
  12492. return this;
  12493. };
  12494. /**
  12495. * Enables the edge rendering mode on the mesh.
  12496. * This mode makes the mesh edges visible.
  12497. * Returns the AbstractMesh.
  12498. */
  12499. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12500. if (epsilon === void 0) { epsilon = 0.95; }
  12501. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12502. this.disableEdgesRendering();
  12503. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12504. return this;
  12505. };
  12506. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12507. /**
  12508. * Returns true if the mesh is blocked. Used by the class Mesh.
  12509. * Returns the boolean `false` by default.
  12510. */
  12511. get: function () {
  12512. return false;
  12513. },
  12514. enumerable: true,
  12515. configurable: true
  12516. });
  12517. /**
  12518. * Returns the mesh itself by default, used by the class Mesh.
  12519. * Returned type : AbstractMesh
  12520. */
  12521. AbstractMesh.prototype.getLOD = function (camera) {
  12522. return this;
  12523. };
  12524. /**
  12525. * Returns 0 by default, used by the class Mesh.
  12526. * Returns an integer.
  12527. */
  12528. AbstractMesh.prototype.getTotalVertices = function () {
  12529. return 0;
  12530. };
  12531. /**
  12532. * Returns null by default, used by the class Mesh.
  12533. * Returned type : integer array
  12534. */
  12535. AbstractMesh.prototype.getIndices = function () {
  12536. return null;
  12537. };
  12538. /**
  12539. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12540. * Returned type : float array or Float32Array
  12541. */
  12542. AbstractMesh.prototype.getVerticesData = function (kind) {
  12543. return null;
  12544. };
  12545. /**
  12546. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12547. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12548. * The `data` are either a numeric array either a Float32Array.
  12549. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12550. * 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).
  12551. * Note that a new underlying VertexBuffer object is created each call.
  12552. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12553. *
  12554. * Possible `kind` values :
  12555. * - BABYLON.VertexBuffer.PositionKind
  12556. * - BABYLON.VertexBuffer.UVKind
  12557. * - BABYLON.VertexBuffer.UV2Kind
  12558. * - BABYLON.VertexBuffer.UV3Kind
  12559. * - BABYLON.VertexBuffer.UV4Kind
  12560. * - BABYLON.VertexBuffer.UV5Kind
  12561. * - BABYLON.VertexBuffer.UV6Kind
  12562. * - BABYLON.VertexBuffer.ColorKind
  12563. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12564. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12565. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12566. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12567. *
  12568. * Returns the Mesh.
  12569. */
  12570. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12571. return null;
  12572. };
  12573. /**
  12574. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12575. * If the mesh has no geometry, it is simply returned as it is.
  12576. * The `data` are either a numeric array either a Float32Array.
  12577. * No new underlying VertexBuffer object is created.
  12578. * 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.
  12579. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12580. *
  12581. * Possible `kind` values :
  12582. * - BABYLON.VertexBuffer.PositionKind
  12583. * - BABYLON.VertexBuffer.UVKind
  12584. * - BABYLON.VertexBuffer.UV2Kind
  12585. * - BABYLON.VertexBuffer.UV3Kind
  12586. * - BABYLON.VertexBuffer.UV4Kind
  12587. * - BABYLON.VertexBuffer.UV5Kind
  12588. * - BABYLON.VertexBuffer.UV6Kind
  12589. * - BABYLON.VertexBuffer.ColorKind
  12590. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12591. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12592. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12593. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12594. *
  12595. * Returns the Mesh.
  12596. */
  12597. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12598. return null;
  12599. };
  12600. /**
  12601. * Sets the mesh indices.
  12602. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12603. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12604. * This method creates a new index buffer each call.
  12605. * Returns the Mesh.
  12606. */
  12607. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12608. return null;
  12609. };
  12610. /** Returns false by default, used by the class Mesh.
  12611. * Returns a boolean
  12612. */
  12613. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12614. return false;
  12615. };
  12616. /**
  12617. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12618. * Returns a BoundingInfo
  12619. */
  12620. AbstractMesh.prototype.getBoundingInfo = function () {
  12621. if (this._masterMesh) {
  12622. return this._masterMesh.getBoundingInfo();
  12623. }
  12624. if (!this._boundingInfo) {
  12625. this._updateBoundingInfo();
  12626. }
  12627. return this._boundingInfo;
  12628. };
  12629. /**
  12630. * Sets a mesh new object BoundingInfo.
  12631. * Returns the AbstractMesh.
  12632. */
  12633. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12634. this._boundingInfo = boundingInfo;
  12635. return this;
  12636. };
  12637. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12638. get: function () {
  12639. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12640. },
  12641. enumerable: true,
  12642. configurable: true
  12643. });
  12644. AbstractMesh.prototype._preActivate = function () {
  12645. };
  12646. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12647. };
  12648. AbstractMesh.prototype._activate = function (renderId) {
  12649. this._renderId = renderId;
  12650. };
  12651. /**
  12652. * Returns the last update of the World matrix
  12653. * Returns a Matrix.
  12654. */
  12655. AbstractMesh.prototype.getWorldMatrix = function () {
  12656. if (this._masterMesh) {
  12657. return this._masterMesh.getWorldMatrix();
  12658. }
  12659. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12660. this.computeWorldMatrix();
  12661. }
  12662. return this._worldMatrix;
  12663. };
  12664. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12665. /**
  12666. * Returns directly the last state of the mesh World matrix.
  12667. * A Matrix is returned.
  12668. */
  12669. get: function () {
  12670. return this._worldMatrix;
  12671. },
  12672. enumerable: true,
  12673. configurable: true
  12674. });
  12675. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12676. /**
  12677. * Returns the current mesh absolute position.
  12678. * Retuns a Vector3.
  12679. */
  12680. get: function () {
  12681. return this._absolutePosition;
  12682. },
  12683. enumerable: true,
  12684. configurable: true
  12685. });
  12686. /**
  12687. * Prevents the World matrix to be computed any longer.
  12688. * Returns the AbstractMesh.
  12689. */
  12690. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12691. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12692. this.computeWorldMatrix(true);
  12693. this._isWorldMatrixFrozen = true;
  12694. return this;
  12695. };
  12696. /**
  12697. * Allows back the World matrix computation.
  12698. * Returns the AbstractMesh.
  12699. */
  12700. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12701. this._isWorldMatrixFrozen = false;
  12702. this.computeWorldMatrix(true);
  12703. return this;
  12704. };
  12705. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12706. /**
  12707. * True if the World matrix has been frozen.
  12708. * Returns a boolean.
  12709. */
  12710. get: function () {
  12711. return this._isWorldMatrixFrozen;
  12712. },
  12713. enumerable: true,
  12714. configurable: true
  12715. });
  12716. /**
  12717. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12718. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12719. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12720. * The passed axis is also normalized.
  12721. * Returns the AbstractMesh.
  12722. */
  12723. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12724. axis.normalize();
  12725. if (!this.rotationQuaternion) {
  12726. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12727. this.rotation = BABYLON.Vector3.Zero();
  12728. }
  12729. var rotationQuaternion;
  12730. if (!space || space === BABYLON.Space.LOCAL) {
  12731. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12732. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12733. }
  12734. else {
  12735. if (this.parent) {
  12736. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12737. invertParentWorldMatrix.invert();
  12738. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12739. }
  12740. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12741. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12742. }
  12743. return this;
  12744. };
  12745. /**
  12746. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12747. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12748. * The passed axis is also normalized.
  12749. * Returns the AbstractMesh.
  12750. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12751. */
  12752. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12753. axis.normalize();
  12754. if (!this.rotationQuaternion) {
  12755. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12756. this.rotation.copyFromFloats(0, 0, 0);
  12757. }
  12758. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12759. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12760. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12761. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12762. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12763. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12764. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12765. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12766. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12767. return this;
  12768. };
  12769. /**
  12770. * Translates the mesh along the axis vector for the passed distance in the given space.
  12771. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12772. * Returns the AbstractMesh.
  12773. */
  12774. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12775. var displacementVector = axis.scale(distance);
  12776. if (!space || space === BABYLON.Space.LOCAL) {
  12777. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12778. this.setPositionWithLocalVector(tempV3);
  12779. }
  12780. else {
  12781. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12782. }
  12783. return this;
  12784. };
  12785. /**
  12786. * Adds a rotation step to the mesh current rotation.
  12787. * x, y, z are Euler angles expressed in radians.
  12788. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12789. * This means this rotation is made in the mesh local space only.
  12790. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12791. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12792. * ```javascript
  12793. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12794. * ```
  12795. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12796. * 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.
  12797. * Returns the AbstractMesh.
  12798. */
  12799. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12800. var rotationQuaternion;
  12801. if (this.rotationQuaternion) {
  12802. rotationQuaternion = this.rotationQuaternion;
  12803. }
  12804. else {
  12805. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12806. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12807. }
  12808. var accumulation = BABYLON.Tmp.Quaternion[0];
  12809. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12810. rotationQuaternion.multiplyInPlace(accumulation);
  12811. if (!this.rotationQuaternion) {
  12812. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12813. }
  12814. return this;
  12815. };
  12816. /**
  12817. * Retuns the mesh absolute position in the World.
  12818. * Returns a Vector3.
  12819. */
  12820. AbstractMesh.prototype.getAbsolutePosition = function () {
  12821. this.computeWorldMatrix();
  12822. return this._absolutePosition;
  12823. };
  12824. /**
  12825. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12826. * Returns the AbstractMesh.
  12827. */
  12828. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12829. if (!absolutePosition) {
  12830. return;
  12831. }
  12832. var absolutePositionX;
  12833. var absolutePositionY;
  12834. var absolutePositionZ;
  12835. if (absolutePosition.x === undefined) {
  12836. if (arguments.length < 3) {
  12837. return;
  12838. }
  12839. absolutePositionX = arguments[0];
  12840. absolutePositionY = arguments[1];
  12841. absolutePositionZ = arguments[2];
  12842. }
  12843. else {
  12844. absolutePositionX = absolutePosition.x;
  12845. absolutePositionY = absolutePosition.y;
  12846. absolutePositionZ = absolutePosition.z;
  12847. }
  12848. if (this.parent) {
  12849. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12850. invertParentWorldMatrix.invert();
  12851. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12852. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12853. }
  12854. else {
  12855. this.position.x = absolutePositionX;
  12856. this.position.y = absolutePositionY;
  12857. this.position.z = absolutePositionZ;
  12858. }
  12859. return this;
  12860. };
  12861. // ================================== Point of View Movement =================================
  12862. /**
  12863. * Perform relative position change from the point of view of behind the front of the mesh.
  12864. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12865. * Supports definition of mesh facing forward or backward.
  12866. * @param {number} amountRight
  12867. * @param {number} amountUp
  12868. * @param {number} amountForward
  12869. *
  12870. * Returns the AbstractMesh.
  12871. */
  12872. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12873. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12874. return this;
  12875. };
  12876. /**
  12877. * Calculate relative position change from the point of view of behind the front of the mesh.
  12878. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12879. * Supports definition of mesh facing forward or backward.
  12880. * @param {number} amountRight
  12881. * @param {number} amountUp
  12882. * @param {number} amountForward
  12883. *
  12884. * Returns a new Vector3.
  12885. */
  12886. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12887. var rotMatrix = new BABYLON.Matrix();
  12888. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12889. rotQuaternion.toRotationMatrix(rotMatrix);
  12890. var translationDelta = BABYLON.Vector3.Zero();
  12891. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12892. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12893. return translationDelta;
  12894. };
  12895. // ================================== Point of View Rotation =================================
  12896. /**
  12897. * Perform 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 the AbstractMesh.
  12904. */
  12905. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12906. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12907. return this;
  12908. };
  12909. /**
  12910. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12911. * Supports definition of mesh facing forward or backward.
  12912. * @param {number} flipBack
  12913. * @param {number} twirlClockwise
  12914. * @param {number} tiltRight
  12915. *
  12916. * Returns a new Vector3.
  12917. */
  12918. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12919. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12920. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12921. };
  12922. /**
  12923. * Sets a new pivot matrix to the mesh.
  12924. * Returns the AbstractMesh.
  12925. */
  12926. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12927. this._pivotMatrix = matrix;
  12928. this._cache.pivotMatrixUpdated = true;
  12929. return this;
  12930. };
  12931. /**
  12932. * Returns the mesh pivot matrix.
  12933. * Default : Identity.
  12934. * A Matrix is returned.
  12935. */
  12936. AbstractMesh.prototype.getPivotMatrix = function () {
  12937. return this._pivotMatrix;
  12938. };
  12939. AbstractMesh.prototype._isSynchronized = function () {
  12940. if (this._isDirty) {
  12941. return false;
  12942. }
  12943. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12944. return false;
  12945. if (this._cache.pivotMatrixUpdated) {
  12946. return false;
  12947. }
  12948. if (this.infiniteDistance) {
  12949. return false;
  12950. }
  12951. if (!this._cache.position.equals(this.position))
  12952. return false;
  12953. if (this.rotationQuaternion) {
  12954. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12955. return false;
  12956. }
  12957. if (!this._cache.rotation.equals(this.rotation))
  12958. return false;
  12959. if (!this._cache.scaling.equals(this.scaling))
  12960. return false;
  12961. return true;
  12962. };
  12963. AbstractMesh.prototype._initCache = function () {
  12964. _super.prototype._initCache.call(this);
  12965. this._cache.localMatrixUpdated = false;
  12966. this._cache.position = BABYLON.Vector3.Zero();
  12967. this._cache.scaling = BABYLON.Vector3.Zero();
  12968. this._cache.rotation = BABYLON.Vector3.Zero();
  12969. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12970. this._cache.billboardMode = -1;
  12971. };
  12972. AbstractMesh.prototype.markAsDirty = function (property) {
  12973. if (property === "rotation") {
  12974. this.rotationQuaternion = null;
  12975. }
  12976. this._currentRenderId = Number.MAX_VALUE;
  12977. this._isDirty = true;
  12978. return this;
  12979. };
  12980. /**
  12981. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12982. * Returns the AbstractMesh.
  12983. */
  12984. AbstractMesh.prototype._updateBoundingInfo = function () {
  12985. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12986. this._boundingInfo.update(this.worldMatrixFromCache);
  12987. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12988. return this;
  12989. };
  12990. /**
  12991. * Update a mesh's children BoundingInfo objects only.
  12992. * Returns the AbstractMesh.
  12993. */
  12994. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12995. if (!this.subMeshes) {
  12996. return;
  12997. }
  12998. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12999. var subMesh = this.subMeshes[subIndex];
  13000. if (!subMesh.IsGlobal) {
  13001. subMesh.updateBoundingInfo(matrix);
  13002. }
  13003. }
  13004. return this;
  13005. };
  13006. /**
  13007. * Computes the mesh World matrix and returns it.
  13008. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13009. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13010. * If the parameter `force`is set to `true`, the actual computation is done.
  13011. * Returns the mesh World Matrix.
  13012. */
  13013. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13014. if (this._isWorldMatrixFrozen) {
  13015. return this._worldMatrix;
  13016. }
  13017. if (!force && this.isSynchronized(true)) {
  13018. this._currentRenderId = this.getScene().getRenderId();
  13019. return this._worldMatrix;
  13020. }
  13021. this._cache.position.copyFrom(this.position);
  13022. this._cache.scaling.copyFrom(this.scaling);
  13023. this._cache.pivotMatrixUpdated = false;
  13024. this._cache.billboardMode = this.billboardMode;
  13025. this._currentRenderId = this.getScene().getRenderId();
  13026. this._isDirty = false;
  13027. // Scaling
  13028. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13029. // Rotation
  13030. //rotate, if quaternion is set and rotation was used
  13031. if (this.rotationQuaternion) {
  13032. var len = this.rotation.length();
  13033. if (len) {
  13034. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13035. this.rotation.copyFromFloats(0, 0, 0);
  13036. }
  13037. }
  13038. if (this.rotationQuaternion) {
  13039. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13040. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13041. }
  13042. else {
  13043. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13044. this._cache.rotation.copyFrom(this.rotation);
  13045. }
  13046. // Translation
  13047. if (this.infiniteDistance && !this.parent) {
  13048. var camera = this.getScene().activeCamera;
  13049. if (camera) {
  13050. var cameraWorldMatrix = camera.getWorldMatrix();
  13051. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13052. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13053. }
  13054. }
  13055. else {
  13056. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13057. }
  13058. // Composing transformations
  13059. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13060. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13061. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13062. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13063. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13064. // Need to decompose each rotation here
  13065. var currentPosition = BABYLON.Tmp.Vector3[3];
  13066. if (this.parent && this.parent.getWorldMatrix) {
  13067. if (this._meshToBoneReferal) {
  13068. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13069. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13070. }
  13071. else {
  13072. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13073. }
  13074. }
  13075. else {
  13076. currentPosition.copyFrom(this.position);
  13077. }
  13078. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13079. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13080. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13081. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13082. }
  13083. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13084. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13085. }
  13086. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13087. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13088. }
  13089. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13090. }
  13091. else {
  13092. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13093. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13094. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13095. }
  13096. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13097. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13098. }
  13099. // Local world
  13100. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13101. // Parent
  13102. if (this.parent && this.parent.getWorldMatrix) {
  13103. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13104. if (this._meshToBoneReferal) {
  13105. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13106. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13107. }
  13108. else {
  13109. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13110. }
  13111. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13112. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13113. this._worldMatrix.copyFrom(this._localWorld);
  13114. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13115. }
  13116. else {
  13117. if (this._meshToBoneReferal) {
  13118. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13119. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13120. }
  13121. else {
  13122. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13123. }
  13124. }
  13125. this._markSyncedWithParent();
  13126. }
  13127. else {
  13128. this._worldMatrix.copyFrom(this._localWorld);
  13129. }
  13130. // Bounding info
  13131. this._updateBoundingInfo();
  13132. // Absolute position
  13133. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13134. // Callbacks
  13135. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13136. if (!this._poseMatrix) {
  13137. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13138. }
  13139. return this._worldMatrix;
  13140. };
  13141. /**
  13142. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13143. * @param func: callback function to add
  13144. *
  13145. * Returns the AbstractMesh.
  13146. */
  13147. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13148. this.onAfterWorldMatrixUpdateObservable.add(func);
  13149. return this;
  13150. };
  13151. /**
  13152. * Removes a registered callback function.
  13153. * Returns the AbstractMesh.
  13154. */
  13155. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13156. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13157. return this;
  13158. };
  13159. /**
  13160. * Sets the mesh position in its local space.
  13161. * Returns the AbstractMesh.
  13162. */
  13163. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13164. this.computeWorldMatrix();
  13165. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13166. return this;
  13167. };
  13168. /**
  13169. * Returns the mesh position in the local space from the current World matrix values.
  13170. * Returns a new Vector3.
  13171. */
  13172. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13173. this.computeWorldMatrix();
  13174. var invLocalWorldMatrix = this._localWorld.clone();
  13175. invLocalWorldMatrix.invert();
  13176. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13177. };
  13178. /**
  13179. * Translates the mesh along the passed Vector3 in its local space.
  13180. * Returns the AbstractMesh.
  13181. */
  13182. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13183. this.computeWorldMatrix(true);
  13184. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13185. return this;
  13186. };
  13187. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13188. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13189. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13190. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13191. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13192. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13193. /// <returns>Mesh oriented towards targetMesh</returns>
  13194. if (yawCor === void 0) { yawCor = 0; }
  13195. if (pitchCor === void 0) { pitchCor = 0; }
  13196. if (rollCor === void 0) { rollCor = 0; }
  13197. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13198. var dv = AbstractMesh._lookAtVectorCache;
  13199. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13200. targetPoint.subtractToRef(pos, dv);
  13201. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13202. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13203. var pitch = Math.atan2(dv.y, len);
  13204. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13205. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13206. return this;
  13207. };
  13208. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13209. this._meshToBoneReferal = affectedMesh;
  13210. this.parent = bone;
  13211. if (bone.getWorldMatrix().determinant() < 0) {
  13212. this.scalingDeterminant *= -1;
  13213. }
  13214. return this;
  13215. };
  13216. AbstractMesh.prototype.detachFromBone = function () {
  13217. if (this.parent.getWorldMatrix().determinant() < 0) {
  13218. this.scalingDeterminant *= -1;
  13219. }
  13220. this._meshToBoneReferal = null;
  13221. this.parent = null;
  13222. return this;
  13223. };
  13224. /**
  13225. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13226. * A mesh is in the frustum if its bounding box intersects the frustum.
  13227. * Boolean returned.
  13228. */
  13229. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13230. return this._boundingInfo.isInFrustum(frustumPlanes);
  13231. };
  13232. /**
  13233. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13234. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13235. * Boolean returned.
  13236. */
  13237. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13238. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13239. ;
  13240. };
  13241. /**
  13242. * True if the mesh intersects another mesh or a SolidParticle object.
  13243. * 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)
  13244. * Returns a boolean.
  13245. */
  13246. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13247. if (!this._boundingInfo || !mesh._boundingInfo) {
  13248. return false;
  13249. }
  13250. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13251. };
  13252. /**
  13253. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13254. * Returns a boolean.
  13255. */
  13256. AbstractMesh.prototype.intersectsPoint = function (point) {
  13257. if (!this._boundingInfo) {
  13258. return false;
  13259. }
  13260. return this._boundingInfo.intersectsPoint(point);
  13261. };
  13262. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13263. return this.physicsImpostor;
  13264. };
  13265. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13266. if (!camera) {
  13267. camera = this.getScene().activeCamera;
  13268. }
  13269. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13270. };
  13271. /**
  13272. * Returns the distance from the mesh to the active camera.
  13273. * Returns a float.
  13274. */
  13275. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13276. if (!camera) {
  13277. camera = this.getScene().activeCamera;
  13278. }
  13279. return this.absolutePosition.subtract(camera.position).length();
  13280. };
  13281. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13282. if (!this.physicsImpostor) {
  13283. return;
  13284. }
  13285. this.physicsImpostor.applyImpulse(force, contactPoint);
  13286. return this;
  13287. };
  13288. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13289. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13290. return;
  13291. }
  13292. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13293. mainPivot: pivot1,
  13294. connectedPivot: pivot2,
  13295. nativeParams: options
  13296. });
  13297. return this;
  13298. };
  13299. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13300. // Collisions
  13301. /**
  13302. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13303. * Default `false`.
  13304. */
  13305. get: function () {
  13306. return this._checkCollisions;
  13307. },
  13308. set: function (collisionEnabled) {
  13309. this._checkCollisions = collisionEnabled;
  13310. if (this.getScene().workerCollisions) {
  13311. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13312. }
  13313. },
  13314. enumerable: true,
  13315. configurable: true
  13316. });
  13317. AbstractMesh.prototype.moveWithCollisions = function (direction) {
  13318. var globalPosition = this.getAbsolutePosition();
  13319. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13320. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13321. if (!this._collider) {
  13322. this._collider = new BABYLON.Collider();
  13323. }
  13324. this._collider.radius = this.ellipsoid;
  13325. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, direction, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13326. return this;
  13327. };
  13328. // Submeshes octree
  13329. /**
  13330. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13331. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13332. * Returns an Octree of submeshes.
  13333. */
  13334. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13335. if (maxCapacity === void 0) { maxCapacity = 64; }
  13336. if (maxDepth === void 0) { maxDepth = 2; }
  13337. if (!this._submeshesOctree) {
  13338. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13339. }
  13340. this.computeWorldMatrix(true);
  13341. // Update octree
  13342. var bbox = this.getBoundingInfo().boundingBox;
  13343. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13344. return this._submeshesOctree;
  13345. };
  13346. // Collisions
  13347. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13348. this._generatePointsArray();
  13349. // Transformation
  13350. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13351. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13352. subMesh._lastColliderWorldVertices = [];
  13353. subMesh._trianglePlanes = [];
  13354. var start = subMesh.verticesStart;
  13355. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13356. for (var i = start; i < end; i++) {
  13357. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13358. }
  13359. }
  13360. // Collide
  13361. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13362. if (collider.collisionFound) {
  13363. collider.collidedMesh = this;
  13364. }
  13365. return this;
  13366. };
  13367. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13368. var subMeshes;
  13369. var len;
  13370. // Octrees
  13371. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13372. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13373. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13374. len = intersections.length;
  13375. subMeshes = intersections.data;
  13376. }
  13377. else {
  13378. subMeshes = this.subMeshes;
  13379. len = subMeshes.length;
  13380. }
  13381. for (var index = 0; index < len; index++) {
  13382. var subMesh = subMeshes[index];
  13383. // Bounding test
  13384. if (len > 1 && !subMesh._checkCollision(collider))
  13385. continue;
  13386. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13387. }
  13388. return this;
  13389. };
  13390. AbstractMesh.prototype._checkCollision = function (collider) {
  13391. // Bounding box test
  13392. if (!this._boundingInfo._checkCollision(collider))
  13393. return this;
  13394. // Transformation matrix
  13395. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13396. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13397. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13398. return this;
  13399. };
  13400. // Picking
  13401. AbstractMesh.prototype._generatePointsArray = function () {
  13402. return false;
  13403. };
  13404. /**
  13405. * Checks if the passed Ray intersects with the mesh.
  13406. * Returns an object PickingInfo.
  13407. */
  13408. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13409. var pickingInfo = new BABYLON.PickingInfo();
  13410. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13411. return pickingInfo;
  13412. }
  13413. if (!this._generatePointsArray()) {
  13414. return pickingInfo;
  13415. }
  13416. var intersectInfo = null;
  13417. // Octrees
  13418. var subMeshes;
  13419. var len;
  13420. if (this._submeshesOctree && this.useOctreeForPicking) {
  13421. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13422. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13423. len = intersections.length;
  13424. subMeshes = intersections.data;
  13425. }
  13426. else {
  13427. subMeshes = this.subMeshes;
  13428. len = subMeshes.length;
  13429. }
  13430. for (var index = 0; index < len; index++) {
  13431. var subMesh = subMeshes[index];
  13432. // Bounding test
  13433. if (len > 1 && !subMesh.canIntersects(ray))
  13434. continue;
  13435. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13436. if (currentIntersectInfo) {
  13437. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13438. intersectInfo = currentIntersectInfo;
  13439. intersectInfo.subMeshId = index;
  13440. if (fastCheck) {
  13441. break;
  13442. }
  13443. }
  13444. }
  13445. }
  13446. if (intersectInfo) {
  13447. // Get picked point
  13448. var world = this.getWorldMatrix();
  13449. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13450. var direction = ray.direction.clone();
  13451. direction = direction.scale(intersectInfo.distance);
  13452. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13453. var pickedPoint = worldOrigin.add(worldDirection);
  13454. // Return result
  13455. pickingInfo.hit = true;
  13456. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13457. pickingInfo.pickedPoint = pickedPoint;
  13458. pickingInfo.pickedMesh = this;
  13459. pickingInfo.bu = intersectInfo.bu;
  13460. pickingInfo.bv = intersectInfo.bv;
  13461. pickingInfo.faceId = intersectInfo.faceId;
  13462. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13463. return pickingInfo;
  13464. }
  13465. return pickingInfo;
  13466. };
  13467. /**
  13468. * Clones the mesh, used by the class Mesh.
  13469. * Just returns `null` for an AbstractMesh.
  13470. */
  13471. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13472. return null;
  13473. };
  13474. /**
  13475. * Disposes all the mesh submeshes.
  13476. * Returns the AbstractMesh.
  13477. */
  13478. AbstractMesh.prototype.releaseSubMeshes = function () {
  13479. if (this.subMeshes) {
  13480. while (this.subMeshes.length) {
  13481. this.subMeshes[0].dispose();
  13482. }
  13483. }
  13484. else {
  13485. this.subMeshes = new Array();
  13486. }
  13487. return this;
  13488. };
  13489. /**
  13490. * Disposes the AbstractMesh.
  13491. * Some internal references are kept for further use.
  13492. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13493. * Returns nothing.
  13494. */
  13495. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13496. var _this = this;
  13497. var index;
  13498. // Action manager
  13499. if (this.actionManager) {
  13500. this.actionManager.dispose();
  13501. this.actionManager = null;
  13502. }
  13503. // Skeleton
  13504. this.skeleton = null;
  13505. // Animations
  13506. this.getScene().stopAnimation(this);
  13507. // Physics
  13508. if (this.physicsImpostor) {
  13509. this.physicsImpostor.dispose();
  13510. }
  13511. // Intersections in progress
  13512. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13513. var other = this._intersectionsInProgress[index];
  13514. var pos = other._intersectionsInProgress.indexOf(this);
  13515. other._intersectionsInProgress.splice(pos, 1);
  13516. }
  13517. this._intersectionsInProgress = [];
  13518. // Lights
  13519. var lights = this.getScene().lights;
  13520. lights.forEach(function (light) {
  13521. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13522. if (meshIndex !== -1) {
  13523. light.includedOnlyMeshes.splice(meshIndex, 1);
  13524. }
  13525. meshIndex = light.excludedMeshes.indexOf(_this);
  13526. if (meshIndex !== -1) {
  13527. light.excludedMeshes.splice(meshIndex, 1);
  13528. }
  13529. // Shadow generators
  13530. var generator = light.getShadowGenerator();
  13531. if (generator) {
  13532. var shadowMap = generator.getShadowMap();
  13533. meshIndex = shadowMap.renderList.indexOf(_this);
  13534. if (meshIndex !== -1) {
  13535. shadowMap.renderList.splice(meshIndex, 1);
  13536. }
  13537. }
  13538. });
  13539. // Edges
  13540. if (this._edgesRenderer) {
  13541. this._edgesRenderer.dispose();
  13542. this._edgesRenderer = null;
  13543. }
  13544. // SubMeshes
  13545. if (this.getClassName() !== "InstancedMesh") {
  13546. this.releaseSubMeshes();
  13547. }
  13548. // Octree
  13549. var sceneOctree = this.getScene().selectionOctree;
  13550. if (sceneOctree) {
  13551. var index = sceneOctree.dynamicContent.indexOf(this);
  13552. if (index !== -1) {
  13553. sceneOctree.dynamicContent.splice(index, 1);
  13554. }
  13555. }
  13556. // Query
  13557. var engine = this.getScene().getEngine();
  13558. if (this._occlusionQuery) {
  13559. this._isOcclusionQueryInProgress = false;
  13560. engine.deleteQuery(this._occlusionQuery);
  13561. this._occlusionQuery = null;
  13562. }
  13563. // Engine
  13564. engine.wipeCaches();
  13565. // Remove from scene
  13566. this.getScene().removeMesh(this);
  13567. if (!doNotRecurse) {
  13568. // Particles
  13569. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13570. if (this.getScene().particleSystems[index].emitter === this) {
  13571. this.getScene().particleSystems[index].dispose();
  13572. index--;
  13573. }
  13574. }
  13575. // Children
  13576. var objects = this.getDescendants(true);
  13577. for (index = 0; index < objects.length; index++) {
  13578. objects[index].dispose();
  13579. }
  13580. }
  13581. else {
  13582. var childMeshes = this.getChildMeshes(true);
  13583. for (index = 0; index < childMeshes.length; index++) {
  13584. var child = childMeshes[index];
  13585. child.parent = null;
  13586. child.computeWorldMatrix(true);
  13587. }
  13588. }
  13589. // facet data
  13590. if (this._facetDataEnabled) {
  13591. this.disableFacetData();
  13592. }
  13593. this.onAfterWorldMatrixUpdateObservable.clear();
  13594. this.onCollideObservable.clear();
  13595. this.onCollisionPositionChangeObservable.clear();
  13596. this._isDisposed = true;
  13597. _super.prototype.dispose.call(this);
  13598. };
  13599. /**
  13600. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13601. * This Vector3 is expressed in the World space.
  13602. */
  13603. AbstractMesh.prototype.getDirection = function (localAxis) {
  13604. var result = BABYLON.Vector3.Zero();
  13605. this.getDirectionToRef(localAxis, result);
  13606. return result;
  13607. };
  13608. /**
  13609. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13610. * localAxis is expressed in the mesh local space.
  13611. * result is computed in the Wordl space from the mesh World matrix.
  13612. * Returns the AbstractMesh.
  13613. */
  13614. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13615. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13616. return this;
  13617. };
  13618. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13619. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13620. if (this.getScene().getRenderId() == 0) {
  13621. this.computeWorldMatrix(true);
  13622. }
  13623. var wm = this.getWorldMatrix();
  13624. if (space == BABYLON.Space.WORLD) {
  13625. var tmat = BABYLON.Tmp.Matrix[0];
  13626. wm.invertToRef(tmat);
  13627. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13628. }
  13629. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13630. this._pivotMatrix.m[12] = -point.x;
  13631. this._pivotMatrix.m[13] = -point.y;
  13632. this._pivotMatrix.m[14] = -point.z;
  13633. this._cache.pivotMatrixUpdated = true;
  13634. return this;
  13635. };
  13636. /**
  13637. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13638. */
  13639. AbstractMesh.prototype.getPivotPoint = function () {
  13640. var point = BABYLON.Vector3.Zero();
  13641. this.getPivotPointToRef(point);
  13642. return point;
  13643. };
  13644. /**
  13645. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13646. * Returns the AbstractMesh.
  13647. */
  13648. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13649. result.x = -this._pivotMatrix.m[12];
  13650. result.y = -this._pivotMatrix.m[13];
  13651. result.z = -this._pivotMatrix.m[14];
  13652. return this;
  13653. };
  13654. /**
  13655. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13656. */
  13657. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13658. var point = BABYLON.Vector3.Zero();
  13659. this.getAbsolutePivotPointToRef(point);
  13660. return point;
  13661. };
  13662. /**
  13663. * Defines the passed mesh as the parent of the current mesh.
  13664. * Returns the AbstractMesh.
  13665. */
  13666. AbstractMesh.prototype.setParent = function (mesh) {
  13667. var child = this;
  13668. var parent = mesh;
  13669. if (mesh == null) {
  13670. var rotation = BABYLON.Tmp.Quaternion[0];
  13671. var position = BABYLON.Tmp.Vector3[0];
  13672. var scale = BABYLON.Tmp.Vector3[1];
  13673. child.getWorldMatrix().decompose(scale, rotation, position);
  13674. if (child.rotationQuaternion) {
  13675. child.rotationQuaternion.copyFrom(rotation);
  13676. }
  13677. else {
  13678. rotation.toEulerAnglesToRef(child.rotation);
  13679. }
  13680. child.position.x = position.x;
  13681. child.position.y = position.y;
  13682. child.position.z = position.z;
  13683. }
  13684. else {
  13685. var rotation = BABYLON.Tmp.Quaternion[0];
  13686. var position = BABYLON.Tmp.Vector3[0];
  13687. var scale = BABYLON.Tmp.Vector3[1];
  13688. var m1 = BABYLON.Tmp.Matrix[0];
  13689. var m2 = BABYLON.Tmp.Matrix[1];
  13690. parent.getWorldMatrix().decompose(scale, rotation, position);
  13691. rotation.toRotationMatrix(m1);
  13692. m2.setTranslation(position);
  13693. m2.multiplyToRef(m1, m1);
  13694. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13695. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13696. m.decompose(scale, rotation, position);
  13697. if (child.rotationQuaternion) {
  13698. child.rotationQuaternion.copyFrom(rotation);
  13699. }
  13700. else {
  13701. rotation.toEulerAnglesToRef(child.rotation);
  13702. }
  13703. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13704. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13705. m.decompose(scale, rotation, position);
  13706. child.position.x = position.x;
  13707. child.position.y = position.y;
  13708. child.position.z = position.z;
  13709. }
  13710. child.parent = parent;
  13711. return this;
  13712. };
  13713. /**
  13714. * Adds the passed mesh as a child to the current mesh.
  13715. * Returns the AbstractMesh.
  13716. */
  13717. AbstractMesh.prototype.addChild = function (mesh) {
  13718. mesh.setParent(this);
  13719. return this;
  13720. };
  13721. /**
  13722. * Removes the passed mesh from the current mesh children list.
  13723. * Returns the AbstractMesh.
  13724. */
  13725. AbstractMesh.prototype.removeChild = function (mesh) {
  13726. mesh.setParent(null);
  13727. return this;
  13728. };
  13729. /**
  13730. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13731. * Returns the AbstractMesh.
  13732. */
  13733. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13734. result.x = this._pivotMatrix.m[12];
  13735. result.y = this._pivotMatrix.m[13];
  13736. result.z = this._pivotMatrix.m[14];
  13737. this.getPivotPointToRef(result);
  13738. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13739. return this;
  13740. };
  13741. // Facet data
  13742. /**
  13743. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13744. * Returns the AbstractMesh.
  13745. */
  13746. AbstractMesh.prototype._initFacetData = function () {
  13747. if (!this._facetNormals) {
  13748. this._facetNormals = new Array();
  13749. }
  13750. if (!this._facetPositions) {
  13751. this._facetPositions = new Array();
  13752. }
  13753. if (!this._facetPartitioning) {
  13754. this._facetPartitioning = new Array();
  13755. }
  13756. this._facetNb = this.getIndices().length / 3;
  13757. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13758. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13759. for (var f = 0; f < this._facetNb; f++) {
  13760. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13761. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13762. }
  13763. this._facetDataEnabled = true;
  13764. return this;
  13765. };
  13766. /**
  13767. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13768. * This method can be called within the render loop.
  13769. * 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.
  13770. * Returns the AbstractMesh.
  13771. */
  13772. AbstractMesh.prototype.updateFacetData = function () {
  13773. if (!this._facetDataEnabled) {
  13774. this._initFacetData();
  13775. }
  13776. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13777. var indices = this.getIndices();
  13778. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13779. var bInfo = this.getBoundingInfo();
  13780. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13781. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13782. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13783. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13784. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13785. this._subDiv.max = this._partitioningSubdivisions;
  13786. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13787. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13788. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13789. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13790. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13791. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13792. // set the parameters for ComputeNormals()
  13793. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13794. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13795. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13796. this._facetParameters.bInfo = bInfo;
  13797. this._facetParameters.bbSize = this._bbSize;
  13798. this._facetParameters.subDiv = this._subDiv;
  13799. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13800. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13801. return this;
  13802. };
  13803. /**
  13804. * Returns the facetLocalNormals array.
  13805. * The normals are expressed in the mesh local space.
  13806. */
  13807. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13808. if (!this._facetNormals) {
  13809. this.updateFacetData();
  13810. }
  13811. return this._facetNormals;
  13812. };
  13813. /**
  13814. * Returns the facetLocalPositions array.
  13815. * The facet positions are expressed in the mesh local space.
  13816. */
  13817. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13818. if (!this._facetPositions) {
  13819. this.updateFacetData();
  13820. }
  13821. return this._facetPositions;
  13822. };
  13823. /**
  13824. * Returns the facetLocalPartioning array.
  13825. */
  13826. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13827. if (!this._facetPartitioning) {
  13828. this.updateFacetData();
  13829. }
  13830. return this._facetPartitioning;
  13831. };
  13832. /**
  13833. * Returns the i-th facet position in the world system.
  13834. * This method allocates a new Vector3 per call.
  13835. */
  13836. AbstractMesh.prototype.getFacetPosition = function (i) {
  13837. var pos = BABYLON.Vector3.Zero();
  13838. this.getFacetPositionToRef(i, pos);
  13839. return pos;
  13840. };
  13841. /**
  13842. * Sets the reference Vector3 with the i-th facet position in the world system.
  13843. * Returns the AbstractMesh.
  13844. */
  13845. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13846. var localPos = (this.getFacetLocalPositions())[i];
  13847. var world = this.getWorldMatrix();
  13848. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13849. return this;
  13850. };
  13851. /**
  13852. * Returns the i-th facet normal in the world system.
  13853. * This method allocates a new Vector3 per call.
  13854. */
  13855. AbstractMesh.prototype.getFacetNormal = function (i) {
  13856. var norm = BABYLON.Vector3.Zero();
  13857. this.getFacetNormalToRef(i, norm);
  13858. return norm;
  13859. };
  13860. /**
  13861. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13862. * Returns the AbstractMesh.
  13863. */
  13864. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13865. var localNorm = (this.getFacetLocalNormals())[i];
  13866. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13867. return this;
  13868. };
  13869. /**
  13870. * 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).
  13871. */
  13872. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13873. var bInfo = this.getBoundingInfo();
  13874. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13875. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13876. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13877. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13878. return null;
  13879. }
  13880. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13881. };
  13882. /**
  13883. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13884. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13885. * 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.
  13886. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13887. * 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.
  13888. */
  13889. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13890. if (checkFace === void 0) { checkFace = false; }
  13891. if (facing === void 0) { facing = true; }
  13892. var world = this.getWorldMatrix();
  13893. var invMat = BABYLON.Tmp.Matrix[5];
  13894. world.invertToRef(invMat);
  13895. var invVect = BABYLON.Tmp.Vector3[8];
  13896. var closest = null;
  13897. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13898. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13899. if (projected) {
  13900. // tranform the local computed projected vector to world coordinates
  13901. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13902. }
  13903. return closest;
  13904. };
  13905. /**
  13906. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13907. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13908. * 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.
  13909. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13910. * 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.
  13911. */
  13912. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13913. if (checkFace === void 0) { checkFace = false; }
  13914. if (facing === void 0) { facing = true; }
  13915. var closest = null;
  13916. var tmpx = 0.0;
  13917. var tmpy = 0.0;
  13918. var tmpz = 0.0;
  13919. var d = 0.0; // tmp dot facet normal * facet position
  13920. var t0 = 0.0;
  13921. var projx = 0.0;
  13922. var projy = 0.0;
  13923. var projz = 0.0;
  13924. // Get all the facets in the same partitioning block than (x, y, z)
  13925. var facetPositions = this.getFacetLocalPositions();
  13926. var facetNormals = this.getFacetLocalNormals();
  13927. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13928. if (!facetsInBlock) {
  13929. return null;
  13930. }
  13931. // Get the closest facet to (x, y, z)
  13932. var shortest = Number.MAX_VALUE; // init distance vars
  13933. var tmpDistance = shortest;
  13934. var fib; // current facet in the block
  13935. var norm; // current facet normal
  13936. var p0; // current facet barycenter position
  13937. // loop on all the facets in the current partitioning block
  13938. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13939. fib = facetsInBlock[idx];
  13940. norm = facetNormals[fib];
  13941. p0 = facetPositions[fib];
  13942. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13943. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13944. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13945. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13946. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13947. projx = x + norm.x * t0;
  13948. projy = y + norm.y * t0;
  13949. projz = z + norm.z * t0;
  13950. tmpx = projx - x;
  13951. tmpy = projy - y;
  13952. tmpz = projz - z;
  13953. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13954. if (tmpDistance < shortest) {
  13955. shortest = tmpDistance;
  13956. closest = fib;
  13957. if (projected) {
  13958. projected.x = projx;
  13959. projected.y = projy;
  13960. projected.z = projz;
  13961. }
  13962. }
  13963. }
  13964. }
  13965. return closest;
  13966. };
  13967. /**
  13968. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13969. */
  13970. AbstractMesh.prototype.getFacetDataParameters = function () {
  13971. return this._facetParameters;
  13972. };
  13973. /**
  13974. * Disables the feature FacetData and frees the related memory.
  13975. * Returns the AbstractMesh.
  13976. */
  13977. AbstractMesh.prototype.disableFacetData = function () {
  13978. if (this._facetDataEnabled) {
  13979. this._facetDataEnabled = false;
  13980. this._facetPositions = null;
  13981. this._facetNormals = null;
  13982. this._facetPartitioning = null;
  13983. this._facetParameters = null;
  13984. }
  13985. return this;
  13986. };
  13987. /**
  13988. * Creates new normals data for the mesh.
  13989. * @param updatable.
  13990. */
  13991. AbstractMesh.prototype.createNormals = function (updatable) {
  13992. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13993. var indices = this.getIndices();
  13994. var normals;
  13995. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13996. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13997. }
  13998. else {
  13999. normals = [];
  14000. }
  14001. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14002. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14003. };
  14004. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14005. var engine = this.getEngine();
  14006. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14007. this._isOccluded = false;
  14008. return;
  14009. }
  14010. if (this.isOcclusionQueryInProgress) {
  14011. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14012. if (isOcclusionQueryAvailable) {
  14013. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14014. this._isOcclusionQueryInProgress = false;
  14015. this._occlusionInternalRetryCounter = 0;
  14016. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14017. }
  14018. else {
  14019. this._occlusionInternalRetryCounter++;
  14020. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14021. this._isOcclusionQueryInProgress = false;
  14022. this._occlusionInternalRetryCounter = 0;
  14023. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14024. // if strict continue the last state of the object.
  14025. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14026. }
  14027. else {
  14028. return;
  14029. }
  14030. }
  14031. }
  14032. var scene = this.getScene();
  14033. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14034. if (!this._occlusionQuery) {
  14035. this._occlusionQuery = engine.createQuery();
  14036. }
  14037. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14038. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14039. engine.endQuery(this.occlusionQueryAlgorithmType);
  14040. this._isOcclusionQueryInProgress = true;
  14041. };
  14042. // Statics
  14043. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14044. AbstractMesh._BILLBOARDMODE_X = 1;
  14045. AbstractMesh._BILLBOARDMODE_Y = 2;
  14046. AbstractMesh._BILLBOARDMODE_Z = 4;
  14047. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14048. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14049. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14050. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14051. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14052. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14053. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14054. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14055. return AbstractMesh;
  14056. }(BABYLON.Node));
  14057. BABYLON.AbstractMesh = AbstractMesh;
  14058. })(BABYLON || (BABYLON = {}));
  14059. //# sourceMappingURL=babylon.abstractMesh.js.map
  14060. var BABYLON;
  14061. (function (BABYLON) {
  14062. var Light = (function (_super) {
  14063. __extends(Light, _super);
  14064. /**
  14065. * Creates a Light object in the scene.
  14066. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14067. */
  14068. function Light(name, scene) {
  14069. var _this = _super.call(this, name, scene) || this;
  14070. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14071. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14072. _this.intensity = 1.0;
  14073. _this.range = Number.MAX_VALUE;
  14074. /**
  14075. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14076. * of light.
  14077. */
  14078. _this._photometricScale = 1.0;
  14079. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14080. _this._radius = 0.00001;
  14081. _this.renderPriority = 0;
  14082. /**
  14083. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14084. * the current shadow generator.
  14085. */
  14086. _this.shadowEnabled = true;
  14087. _this._excludeWithLayerMask = 0;
  14088. _this._includeOnlyWithLayerMask = 0;
  14089. _this._lightmapMode = 0;
  14090. _this._excludedMeshesIds = new Array();
  14091. _this._includedOnlyMeshesIds = new Array();
  14092. _this.getScene().addLight(_this);
  14093. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14094. _this._buildUniformLayout();
  14095. _this.includedOnlyMeshes = new Array();
  14096. _this.excludedMeshes = new Array();
  14097. _this._resyncMeshes();
  14098. return _this;
  14099. }
  14100. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14101. /**
  14102. * If every light affecting the material is in this lightmapMode,
  14103. * material.lightmapTexture adds or multiplies
  14104. * (depends on material.useLightmapAsShadowmap)
  14105. * after every other light calculations.
  14106. */
  14107. get: function () {
  14108. return Light._LIGHTMAP_DEFAULT;
  14109. },
  14110. enumerable: true,
  14111. configurable: true
  14112. });
  14113. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14114. /**
  14115. * material.lightmapTexture as only diffuse lighting from this light
  14116. * adds pnly specular lighting from this light
  14117. * adds dynamic shadows
  14118. */
  14119. get: function () {
  14120. return Light._LIGHTMAP_SPECULAR;
  14121. },
  14122. enumerable: true,
  14123. configurable: true
  14124. });
  14125. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14126. /**
  14127. * material.lightmapTexture as only lighting
  14128. * no light calculation from this light
  14129. * only adds dynamic shadows from this light
  14130. */
  14131. get: function () {
  14132. return Light._LIGHTMAP_SHADOWSONLY;
  14133. },
  14134. enumerable: true,
  14135. configurable: true
  14136. });
  14137. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14138. /**
  14139. * Each light type uses the default quantity according to its type:
  14140. * point/spot lights use luminous intensity
  14141. * directional lights use illuminance
  14142. */
  14143. get: function () {
  14144. return Light._INTENSITYMODE_AUTOMATIC;
  14145. },
  14146. enumerable: true,
  14147. configurable: true
  14148. });
  14149. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14150. /**
  14151. * lumen (lm)
  14152. */
  14153. get: function () {
  14154. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14155. },
  14156. enumerable: true,
  14157. configurable: true
  14158. });
  14159. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14160. /**
  14161. * candela (lm/sr)
  14162. */
  14163. get: function () {
  14164. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14165. },
  14166. enumerable: true,
  14167. configurable: true
  14168. });
  14169. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14170. /**
  14171. * lux (lm/m^2)
  14172. */
  14173. get: function () {
  14174. return Light._INTENSITYMODE_ILLUMINANCE;
  14175. },
  14176. enumerable: true,
  14177. configurable: true
  14178. });
  14179. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14180. /**
  14181. * nit (cd/m^2)
  14182. */
  14183. get: function () {
  14184. return Light._INTENSITYMODE_LUMINANCE;
  14185. },
  14186. enumerable: true,
  14187. configurable: true
  14188. });
  14189. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14190. /**
  14191. * Light type const id of the point light.
  14192. */
  14193. get: function () {
  14194. return Light._LIGHTTYPEID_POINTLIGHT;
  14195. },
  14196. enumerable: true,
  14197. configurable: true
  14198. });
  14199. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14200. /**
  14201. * Light type const id of the directional light.
  14202. */
  14203. get: function () {
  14204. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14205. },
  14206. enumerable: true,
  14207. configurable: true
  14208. });
  14209. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14210. /**
  14211. * Light type const id of the spot light.
  14212. */
  14213. get: function () {
  14214. return Light._LIGHTTYPEID_SPOTLIGHT;
  14215. },
  14216. enumerable: true,
  14217. configurable: true
  14218. });
  14219. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14220. /**
  14221. * Light type const id of the hemispheric light.
  14222. */
  14223. get: function () {
  14224. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14225. },
  14226. enumerable: true,
  14227. configurable: true
  14228. });
  14229. Object.defineProperty(Light.prototype, "intensityMode", {
  14230. /**
  14231. * Gets the photometric scale used to interpret the intensity.
  14232. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14233. */
  14234. get: function () {
  14235. return this._intensityMode;
  14236. },
  14237. /**
  14238. * Sets the photometric scale used to interpret the intensity.
  14239. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14240. */
  14241. set: function (value) {
  14242. this._intensityMode = value;
  14243. this._computePhotometricScale();
  14244. },
  14245. enumerable: true,
  14246. configurable: true
  14247. });
  14248. ;
  14249. ;
  14250. Object.defineProperty(Light.prototype, "radius", {
  14251. /**
  14252. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14253. */
  14254. get: function () {
  14255. return this._radius;
  14256. },
  14257. /**
  14258. * sets the light radius used by PBR Materials to simulate soft area lights.
  14259. */
  14260. set: function (value) {
  14261. this._radius = value;
  14262. this._computePhotometricScale();
  14263. },
  14264. enumerable: true,
  14265. configurable: true
  14266. });
  14267. ;
  14268. ;
  14269. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14270. get: function () {
  14271. return this._includedOnlyMeshes;
  14272. },
  14273. set: function (value) {
  14274. this._includedOnlyMeshes = value;
  14275. this._hookArrayForIncludedOnly(value);
  14276. },
  14277. enumerable: true,
  14278. configurable: true
  14279. });
  14280. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14281. get: function () {
  14282. return this._excludedMeshes;
  14283. },
  14284. set: function (value) {
  14285. this._excludedMeshes = value;
  14286. this._hookArrayForExcluded(value);
  14287. },
  14288. enumerable: true,
  14289. configurable: true
  14290. });
  14291. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14292. get: function () {
  14293. return this._excludeWithLayerMask;
  14294. },
  14295. set: function (value) {
  14296. this._excludeWithLayerMask = value;
  14297. this._resyncMeshes();
  14298. },
  14299. enumerable: true,
  14300. configurable: true
  14301. });
  14302. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14303. get: function () {
  14304. return this._includeOnlyWithLayerMask;
  14305. },
  14306. set: function (value) {
  14307. this._includeOnlyWithLayerMask = value;
  14308. this._resyncMeshes();
  14309. },
  14310. enumerable: true,
  14311. configurable: true
  14312. });
  14313. Object.defineProperty(Light.prototype, "lightmapMode", {
  14314. get: function () {
  14315. return this._lightmapMode;
  14316. },
  14317. set: function (value) {
  14318. if (this._lightmapMode === value) {
  14319. return;
  14320. }
  14321. this._lightmapMode = value;
  14322. this._markMeshesAsLightDirty();
  14323. },
  14324. enumerable: true,
  14325. configurable: true
  14326. });
  14327. Light.prototype._buildUniformLayout = function () {
  14328. // Overridden
  14329. };
  14330. /**
  14331. * Returns the string "Light".
  14332. */
  14333. Light.prototype.getClassName = function () {
  14334. return "Light";
  14335. };
  14336. /**
  14337. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14338. */
  14339. Light.prototype.toString = function (fullDetails) {
  14340. var ret = "Name: " + this.name;
  14341. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14342. if (this.animations) {
  14343. for (var i = 0; i < this.animations.length; i++) {
  14344. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14345. }
  14346. }
  14347. if (fullDetails) {
  14348. }
  14349. return ret;
  14350. };
  14351. /**
  14352. * Set the enabled state of this node.
  14353. * @param {boolean} value - the new enabled state
  14354. * @see isEnabled
  14355. */
  14356. Light.prototype.setEnabled = function (value) {
  14357. _super.prototype.setEnabled.call(this, value);
  14358. this._resyncMeshes();
  14359. };
  14360. /**
  14361. * Returns the Light associated shadow generator.
  14362. */
  14363. Light.prototype.getShadowGenerator = function () {
  14364. return this._shadowGenerator;
  14365. };
  14366. /**
  14367. * Returns a Vector3, the absolute light position in the World.
  14368. */
  14369. Light.prototype.getAbsolutePosition = function () {
  14370. return BABYLON.Vector3.Zero();
  14371. };
  14372. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14373. };
  14374. Light.prototype._getWorldMatrix = function () {
  14375. return BABYLON.Matrix.Identity();
  14376. };
  14377. /**
  14378. * Boolean : True if the light will affect the passed mesh.
  14379. */
  14380. Light.prototype.canAffectMesh = function (mesh) {
  14381. if (!mesh) {
  14382. return true;
  14383. }
  14384. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14385. return false;
  14386. }
  14387. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14388. return false;
  14389. }
  14390. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14391. return false;
  14392. }
  14393. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14394. return false;
  14395. }
  14396. return true;
  14397. };
  14398. /**
  14399. * Returns the light World matrix.
  14400. */
  14401. Light.prototype.getWorldMatrix = function () {
  14402. this._currentRenderId = this.getScene().getRenderId();
  14403. var worldMatrix = this._getWorldMatrix();
  14404. if (this.parent && this.parent.getWorldMatrix) {
  14405. if (!this._parentedWorldMatrix) {
  14406. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14407. }
  14408. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14409. this._markSyncedWithParent();
  14410. return this._parentedWorldMatrix;
  14411. }
  14412. return worldMatrix;
  14413. };
  14414. /**
  14415. * Sort function to order lights for rendering.
  14416. * @param a First Light object to compare to second.
  14417. * @param b Second Light object to compare first.
  14418. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14419. */
  14420. Light.compareLightsPriority = function (a, b) {
  14421. //shadow-casting lights have priority over non-shadow-casting lights
  14422. //the renderPrioirty is a secondary sort criterion
  14423. if (a.shadowEnabled !== b.shadowEnabled) {
  14424. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14425. }
  14426. return b.renderPriority - a.renderPriority;
  14427. };
  14428. /**
  14429. * Disposes the light.
  14430. */
  14431. Light.prototype.dispose = function () {
  14432. if (this._shadowGenerator) {
  14433. this._shadowGenerator.dispose();
  14434. this._shadowGenerator = null;
  14435. }
  14436. // Animations
  14437. this.getScene().stopAnimation(this);
  14438. // Remove from meshes
  14439. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14440. var mesh = _a[_i];
  14441. mesh._removeLightSource(this);
  14442. }
  14443. this._uniformBuffer.dispose();
  14444. // Remove from scene
  14445. this.getScene().removeLight(this);
  14446. _super.prototype.dispose.call(this);
  14447. };
  14448. /**
  14449. * Returns the light type ID (integer).
  14450. */
  14451. Light.prototype.getTypeID = function () {
  14452. return 0;
  14453. };
  14454. /**
  14455. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14456. */
  14457. Light.prototype.getScaledIntensity = function () {
  14458. return this._photometricScale * this.intensity;
  14459. };
  14460. /**
  14461. * Returns a new Light object, named "name", from the current one.
  14462. */
  14463. Light.prototype.clone = function (name) {
  14464. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14465. };
  14466. /**
  14467. * Serializes the current light into a Serialization object.
  14468. * Returns the serialized object.
  14469. */
  14470. Light.prototype.serialize = function () {
  14471. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14472. // Type
  14473. serializationObject.type = this.getTypeID();
  14474. // Parent
  14475. if (this.parent) {
  14476. serializationObject.parentId = this.parent.id;
  14477. }
  14478. // Inclusion / exclusions
  14479. if (this.excludedMeshes.length > 0) {
  14480. serializationObject.excludedMeshesIds = [];
  14481. this.excludedMeshes.forEach(function (mesh) {
  14482. serializationObject.excludedMeshesIds.push(mesh.id);
  14483. });
  14484. }
  14485. if (this.includedOnlyMeshes.length > 0) {
  14486. serializationObject.includedOnlyMeshesIds = [];
  14487. this.includedOnlyMeshes.forEach(function (mesh) {
  14488. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14489. });
  14490. }
  14491. // Animations
  14492. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14493. serializationObject.ranges = this.serializeAnimationRanges();
  14494. return serializationObject;
  14495. };
  14496. /**
  14497. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14498. * This new light is named "name" and added to the passed scene.
  14499. */
  14500. Light.GetConstructorFromName = function (type, name, scene) {
  14501. switch (type) {
  14502. case 0:
  14503. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14504. case 1:
  14505. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14506. case 2:
  14507. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14508. case 3:
  14509. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14510. }
  14511. };
  14512. /**
  14513. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14514. */
  14515. Light.Parse = function (parsedLight, scene) {
  14516. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14517. // Inclusion / exclusions
  14518. if (parsedLight.excludedMeshesIds) {
  14519. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14520. }
  14521. if (parsedLight.includedOnlyMeshesIds) {
  14522. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14523. }
  14524. // Parent
  14525. if (parsedLight.parentId) {
  14526. light._waitingParentId = parsedLight.parentId;
  14527. }
  14528. // Animations
  14529. if (parsedLight.animations) {
  14530. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14531. var parsedAnimation = parsedLight.animations[animationIndex];
  14532. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14533. }
  14534. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14535. }
  14536. if (parsedLight.autoAnimate) {
  14537. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14538. }
  14539. return light;
  14540. };
  14541. Light.prototype._hookArrayForExcluded = function (array) {
  14542. var _this = this;
  14543. var oldPush = array.push;
  14544. array.push = function () {
  14545. var items = [];
  14546. for (var _i = 0; _i < arguments.length; _i++) {
  14547. items[_i] = arguments[_i];
  14548. }
  14549. var result = oldPush.apply(array, items);
  14550. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14551. var item = items_1[_a];
  14552. item._resyncLighSource(_this);
  14553. }
  14554. return result;
  14555. };
  14556. var oldSplice = array.splice;
  14557. array.splice = function (index, deleteCount) {
  14558. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14559. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14560. var item = deleted_1[_i];
  14561. item._resyncLighSource(_this);
  14562. }
  14563. return deleted;
  14564. };
  14565. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14566. var item = array_1[_i];
  14567. item._resyncLighSource(this);
  14568. }
  14569. };
  14570. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14571. var _this = this;
  14572. var oldPush = array.push;
  14573. array.push = function () {
  14574. var items = [];
  14575. for (var _i = 0; _i < arguments.length; _i++) {
  14576. items[_i] = arguments[_i];
  14577. }
  14578. var result = oldPush.apply(array, items);
  14579. _this._resyncMeshes();
  14580. return result;
  14581. };
  14582. var oldSplice = array.splice;
  14583. array.splice = function (index, deleteCount) {
  14584. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14585. _this._resyncMeshes();
  14586. return deleted;
  14587. };
  14588. this._resyncMeshes();
  14589. };
  14590. Light.prototype._resyncMeshes = function () {
  14591. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14592. var mesh = _a[_i];
  14593. mesh._resyncLighSource(this);
  14594. }
  14595. };
  14596. Light.prototype._markMeshesAsLightDirty = function () {
  14597. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14598. var mesh = _a[_i];
  14599. if (mesh._lightSources.indexOf(this) !== -1) {
  14600. mesh._markSubMeshesAsLightDirty();
  14601. }
  14602. }
  14603. };
  14604. /**
  14605. * Recomputes the cached photometric scale if needed.
  14606. */
  14607. Light.prototype._computePhotometricScale = function () {
  14608. this._photometricScale = this._getPhotometricScale();
  14609. this.getScene().resetCachedMaterial();
  14610. };
  14611. /**
  14612. * Returns the Photometric Scale according to the light type and intensity mode.
  14613. */
  14614. Light.prototype._getPhotometricScale = function () {
  14615. var photometricScale = 0.0;
  14616. var lightTypeID = this.getTypeID();
  14617. //get photometric mode
  14618. var photometricMode = this.intensityMode;
  14619. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14620. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14621. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14622. }
  14623. else {
  14624. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14625. }
  14626. }
  14627. //compute photometric scale
  14628. switch (lightTypeID) {
  14629. case Light.LIGHTTYPEID_POINTLIGHT:
  14630. case Light.LIGHTTYPEID_SPOTLIGHT:
  14631. switch (photometricMode) {
  14632. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14633. photometricScale = 1.0 / (4.0 * Math.PI);
  14634. break;
  14635. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14636. photometricScale = 1.0;
  14637. break;
  14638. case Light.INTENSITYMODE_LUMINANCE:
  14639. photometricScale = this.radius * this.radius;
  14640. break;
  14641. }
  14642. break;
  14643. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14644. switch (photometricMode) {
  14645. case Light.INTENSITYMODE_ILLUMINANCE:
  14646. photometricScale = 1.0;
  14647. break;
  14648. case Light.INTENSITYMODE_LUMINANCE:
  14649. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14650. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14651. var apexAngleRadians = this.radius;
  14652. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14653. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14654. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14655. photometricScale = solidAngle;
  14656. break;
  14657. }
  14658. break;
  14659. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14660. // No fall off in hemisperic light.
  14661. photometricScale = 1.0;
  14662. break;
  14663. }
  14664. return photometricScale;
  14665. };
  14666. Light.prototype._reorderLightsInScene = function () {
  14667. var scene = this.getScene();
  14668. if (this.renderPriority != 0) {
  14669. scene.requireLightSorting = true;
  14670. }
  14671. this.getScene().sortLightsByPriority();
  14672. };
  14673. //lightmapMode Consts
  14674. Light._LIGHTMAP_DEFAULT = 0;
  14675. Light._LIGHTMAP_SPECULAR = 1;
  14676. Light._LIGHTMAP_SHADOWSONLY = 2;
  14677. // Intensity Mode Consts
  14678. Light._INTENSITYMODE_AUTOMATIC = 0;
  14679. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14680. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14681. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14682. Light._INTENSITYMODE_LUMINANCE = 4;
  14683. // Light types ids const.
  14684. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14685. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14686. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14687. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14688. __decorate([
  14689. BABYLON.serializeAsColor3()
  14690. ], Light.prototype, "diffuse", void 0);
  14691. __decorate([
  14692. BABYLON.serializeAsColor3()
  14693. ], Light.prototype, "specular", void 0);
  14694. __decorate([
  14695. BABYLON.serialize()
  14696. ], Light.prototype, "intensity", void 0);
  14697. __decorate([
  14698. BABYLON.serialize()
  14699. ], Light.prototype, "range", void 0);
  14700. __decorate([
  14701. BABYLON.serialize()
  14702. ], Light.prototype, "intensityMode", null);
  14703. __decorate([
  14704. BABYLON.serialize()
  14705. ], Light.prototype, "radius", null);
  14706. __decorate([
  14707. BABYLON.serialize()
  14708. ], Light.prototype, "_renderPriority", void 0);
  14709. __decorate([
  14710. BABYLON.expandToProperty("_reorderLightsInScene")
  14711. ], Light.prototype, "renderPriority", void 0);
  14712. __decorate([
  14713. BABYLON.serialize()
  14714. ], Light.prototype, "shadowEnabled", void 0);
  14715. __decorate([
  14716. BABYLON.serialize("excludeWithLayerMask")
  14717. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14718. __decorate([
  14719. BABYLON.serialize("includeOnlyWithLayerMask")
  14720. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14721. __decorate([
  14722. BABYLON.serialize("lightmapMode")
  14723. ], Light.prototype, "_lightmapMode", void 0);
  14724. return Light;
  14725. }(BABYLON.Node));
  14726. BABYLON.Light = Light;
  14727. })(BABYLON || (BABYLON = {}));
  14728. //# sourceMappingURL=babylon.light.js.map
  14729. var BABYLON;
  14730. (function (BABYLON) {
  14731. var Camera = (function (_super) {
  14732. __extends(Camera, _super);
  14733. function Camera(name, position, scene) {
  14734. var _this = _super.call(this, name, scene) || this;
  14735. _this.upVector = BABYLON.Vector3.Up();
  14736. _this.orthoLeft = null;
  14737. _this.orthoRight = null;
  14738. _this.orthoBottom = null;
  14739. _this.orthoTop = null;
  14740. _this.fov = 0.8;
  14741. _this.minZ = 1;
  14742. _this.maxZ = 10000.0;
  14743. _this.inertia = 0.9;
  14744. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14745. _this.isIntermediate = false;
  14746. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14747. _this.layerMask = 0x0FFFFFFF;
  14748. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14749. // Camera rig members
  14750. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14751. _this._rigCameras = new Array();
  14752. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14753. _this.customRenderTargets = new Array();
  14754. // Observables
  14755. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14756. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14757. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  14758. // Cache
  14759. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14760. _this._projectionMatrix = new BABYLON.Matrix();
  14761. _this._doNotComputeProjectionMatrix = false;
  14762. _this._postProcesses = new Array();
  14763. _this._transformMatrix = BABYLON.Matrix.Zero();
  14764. _this._activeMeshes = new BABYLON.SmartArray(256);
  14765. _this._globalPosition = BABYLON.Vector3.Zero();
  14766. _this._refreshFrustumPlanes = true;
  14767. _this.getScene().addCamera(_this);
  14768. if (!_this.getScene().activeCamera) {
  14769. _this.getScene().activeCamera = _this;
  14770. }
  14771. _this.position = position;
  14772. return _this;
  14773. }
  14774. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14775. get: function () {
  14776. return Camera._PERSPECTIVE_CAMERA;
  14777. },
  14778. enumerable: true,
  14779. configurable: true
  14780. });
  14781. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14782. get: function () {
  14783. return Camera._ORTHOGRAPHIC_CAMERA;
  14784. },
  14785. enumerable: true,
  14786. configurable: true
  14787. });
  14788. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14789. get: function () {
  14790. return Camera._FOVMODE_VERTICAL_FIXED;
  14791. },
  14792. enumerable: true,
  14793. configurable: true
  14794. });
  14795. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14796. get: function () {
  14797. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14798. },
  14799. enumerable: true,
  14800. configurable: true
  14801. });
  14802. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14803. get: function () {
  14804. return Camera._RIG_MODE_NONE;
  14805. },
  14806. enumerable: true,
  14807. configurable: true
  14808. });
  14809. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14810. get: function () {
  14811. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14812. },
  14813. enumerable: true,
  14814. configurable: true
  14815. });
  14816. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14817. get: function () {
  14818. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14819. },
  14820. enumerable: true,
  14821. configurable: true
  14822. });
  14823. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14824. get: function () {
  14825. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14826. },
  14827. enumerable: true,
  14828. configurable: true
  14829. });
  14830. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14831. get: function () {
  14832. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14833. },
  14834. enumerable: true,
  14835. configurable: true
  14836. });
  14837. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14838. get: function () {
  14839. return Camera._RIG_MODE_VR;
  14840. },
  14841. enumerable: true,
  14842. configurable: true
  14843. });
  14844. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14845. get: function () {
  14846. return Camera._RIG_MODE_WEBVR;
  14847. },
  14848. enumerable: true,
  14849. configurable: true
  14850. });
  14851. /**
  14852. * Store current camera state (fov, position, etc..)
  14853. */
  14854. Camera.prototype.storeState = function () {
  14855. this._stateStored = true;
  14856. this._storedFov = this.fov;
  14857. return this;
  14858. };
  14859. /**
  14860. * Restored camera state. You must call storeState() first
  14861. */
  14862. Camera.prototype.restoreState = function () {
  14863. if (!this._stateStored) {
  14864. return false;
  14865. }
  14866. this.fov = this._storedFov;
  14867. return true;
  14868. };
  14869. Camera.prototype.getClassName = function () {
  14870. return "Camera";
  14871. };
  14872. /**
  14873. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14874. */
  14875. Camera.prototype.toString = function (fullDetails) {
  14876. var ret = "Name: " + this.name;
  14877. ret += ", type: " + this.getClassName();
  14878. if (this.animations) {
  14879. for (var i = 0; i < this.animations.length; i++) {
  14880. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14881. }
  14882. }
  14883. if (fullDetails) {
  14884. }
  14885. return ret;
  14886. };
  14887. Object.defineProperty(Camera.prototype, "globalPosition", {
  14888. get: function () {
  14889. return this._globalPosition;
  14890. },
  14891. enumerable: true,
  14892. configurable: true
  14893. });
  14894. Camera.prototype.getActiveMeshes = function () {
  14895. return this._activeMeshes;
  14896. };
  14897. Camera.prototype.isActiveMesh = function (mesh) {
  14898. return (this._activeMeshes.indexOf(mesh) !== -1);
  14899. };
  14900. //Cache
  14901. Camera.prototype._initCache = function () {
  14902. _super.prototype._initCache.call(this);
  14903. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14904. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14905. this._cache.mode = undefined;
  14906. this._cache.minZ = undefined;
  14907. this._cache.maxZ = undefined;
  14908. this._cache.fov = undefined;
  14909. this._cache.fovMode = undefined;
  14910. this._cache.aspectRatio = undefined;
  14911. this._cache.orthoLeft = undefined;
  14912. this._cache.orthoRight = undefined;
  14913. this._cache.orthoBottom = undefined;
  14914. this._cache.orthoTop = undefined;
  14915. this._cache.renderWidth = undefined;
  14916. this._cache.renderHeight = undefined;
  14917. };
  14918. Camera.prototype._updateCache = function (ignoreParentClass) {
  14919. if (!ignoreParentClass) {
  14920. _super.prototype._updateCache.call(this);
  14921. }
  14922. var engine = this.getEngine();
  14923. this._cache.position.copyFrom(this.position);
  14924. this._cache.upVector.copyFrom(this.upVector);
  14925. this._cache.mode = this.mode;
  14926. this._cache.minZ = this.minZ;
  14927. this._cache.maxZ = this.maxZ;
  14928. this._cache.fov = this.fov;
  14929. this._cache.fovMode = this.fovMode;
  14930. this._cache.aspectRatio = engine.getAspectRatio(this);
  14931. this._cache.orthoLeft = this.orthoLeft;
  14932. this._cache.orthoRight = this.orthoRight;
  14933. this._cache.orthoBottom = this.orthoBottom;
  14934. this._cache.orthoTop = this.orthoTop;
  14935. this._cache.renderWidth = engine.getRenderWidth();
  14936. this._cache.renderHeight = engine.getRenderHeight();
  14937. };
  14938. Camera.prototype._updateFromScene = function () {
  14939. this.updateCache();
  14940. this.update();
  14941. };
  14942. // Synchronized
  14943. Camera.prototype._isSynchronized = function () {
  14944. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14945. };
  14946. Camera.prototype._isSynchronizedViewMatrix = function () {
  14947. if (!_super.prototype._isSynchronized.call(this))
  14948. return false;
  14949. return this._cache.position.equals(this.position)
  14950. && this._cache.upVector.equals(this.upVector)
  14951. && this.isSynchronizedWithParent();
  14952. };
  14953. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14954. var check = this._cache.mode === this.mode
  14955. && this._cache.minZ === this.minZ
  14956. && this._cache.maxZ === this.maxZ;
  14957. if (!check) {
  14958. return false;
  14959. }
  14960. var engine = this.getEngine();
  14961. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14962. check = this._cache.fov === this.fov
  14963. && this._cache.fovMode === this.fovMode
  14964. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14965. }
  14966. else {
  14967. check = this._cache.orthoLeft === this.orthoLeft
  14968. && this._cache.orthoRight === this.orthoRight
  14969. && this._cache.orthoBottom === this.orthoBottom
  14970. && this._cache.orthoTop === this.orthoTop
  14971. && this._cache.renderWidth === engine.getRenderWidth()
  14972. && this._cache.renderHeight === engine.getRenderHeight();
  14973. }
  14974. return check;
  14975. };
  14976. // Controls
  14977. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14978. };
  14979. Camera.prototype.detachControl = function (element) {
  14980. };
  14981. Camera.prototype.update = function () {
  14982. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14983. this._updateRigCameras();
  14984. }
  14985. this._checkInputs();
  14986. };
  14987. Camera.prototype._checkInputs = function () {
  14988. this.onAfterCheckInputsObservable.notifyObservers(this);
  14989. };
  14990. Object.defineProperty(Camera.prototype, "rigCameras", {
  14991. get: function () {
  14992. return this._rigCameras;
  14993. },
  14994. enumerable: true,
  14995. configurable: true
  14996. });
  14997. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14998. get: function () {
  14999. return this._rigPostProcess;
  15000. },
  15001. enumerable: true,
  15002. configurable: true
  15003. });
  15004. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15005. // invalidate framebuffer
  15006. if (this._postProcesses.length > 0) {
  15007. this._postProcesses[0].markTextureDirty();
  15008. }
  15009. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15010. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15011. var cam = this._rigCameras[i];
  15012. var rigPostProcess = cam._rigPostProcess;
  15013. // for VR rig, there does not have to be a post process
  15014. if (rigPostProcess) {
  15015. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15016. if (isPass) {
  15017. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15018. cam.isIntermediate = this._postProcesses.length === 0;
  15019. }
  15020. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15021. rigPostProcess.markTextureDirty();
  15022. }
  15023. else {
  15024. cam._postProcesses = this._postProcesses.slice(0);
  15025. }
  15026. }
  15027. };
  15028. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15029. if (insertAt === void 0) { insertAt = null; }
  15030. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15031. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15032. return 0;
  15033. }
  15034. if (insertAt == null || insertAt < 0) {
  15035. this._postProcesses.push(postProcess);
  15036. }
  15037. else {
  15038. this._postProcesses.splice(insertAt, 0, postProcess);
  15039. }
  15040. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15041. return this._postProcesses.indexOf(postProcess);
  15042. };
  15043. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15044. if (atIndices === void 0) { atIndices = null; }
  15045. var result = [];
  15046. var i;
  15047. var index;
  15048. if (!atIndices) {
  15049. var idx = this._postProcesses.indexOf(postProcess);
  15050. if (idx !== -1) {
  15051. this._postProcesses.splice(idx, 1);
  15052. }
  15053. }
  15054. else {
  15055. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15056. // iterate descending, so can just splice as we go
  15057. for (i = atIndices.length - 1; i >= 0; i--) {
  15058. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15059. result.push(i);
  15060. continue;
  15061. }
  15062. index = atIndices[i];
  15063. this._postProcesses.splice(index, 1);
  15064. }
  15065. }
  15066. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15067. return result;
  15068. };
  15069. Camera.prototype.getWorldMatrix = function () {
  15070. if (!this._worldMatrix) {
  15071. this._worldMatrix = BABYLON.Matrix.Identity();
  15072. }
  15073. var viewMatrix = this.getViewMatrix();
  15074. viewMatrix.invertToRef(this._worldMatrix);
  15075. return this._worldMatrix;
  15076. };
  15077. Camera.prototype._getViewMatrix = function () {
  15078. return BABYLON.Matrix.Identity();
  15079. };
  15080. Camera.prototype.getViewMatrix = function (force) {
  15081. if (!force && this._isSynchronizedViewMatrix()) {
  15082. return this._computedViewMatrix;
  15083. }
  15084. this._computedViewMatrix = this._getViewMatrix();
  15085. this._currentRenderId = this.getScene().getRenderId();
  15086. this._refreshFrustumPlanes = true;
  15087. if (!this.parent || !this.parent.getWorldMatrix) {
  15088. this._globalPosition.copyFrom(this.position);
  15089. }
  15090. else {
  15091. if (!this._worldMatrix) {
  15092. this._worldMatrix = BABYLON.Matrix.Identity();
  15093. }
  15094. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15095. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15096. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15097. this._computedViewMatrix.invert();
  15098. this._markSyncedWithParent();
  15099. }
  15100. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15101. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15102. }
  15103. this.onViewMatrixChangedObservable.notifyObservers(this);
  15104. return this._computedViewMatrix;
  15105. };
  15106. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15107. this._doNotComputeProjectionMatrix = true;
  15108. if (projection !== undefined) {
  15109. this._projectionMatrix = projection;
  15110. }
  15111. };
  15112. ;
  15113. Camera.prototype.unfreezeProjectionMatrix = function () {
  15114. this._doNotComputeProjectionMatrix = false;
  15115. };
  15116. ;
  15117. Camera.prototype.getProjectionMatrix = function (force) {
  15118. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15119. return this._projectionMatrix;
  15120. }
  15121. this._refreshFrustumPlanes = true;
  15122. var engine = this.getEngine();
  15123. var scene = this.getScene();
  15124. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15125. if (this.minZ <= 0) {
  15126. this.minZ = 0.1;
  15127. }
  15128. if (scene.useRightHandedSystem) {
  15129. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15130. }
  15131. else {
  15132. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15133. }
  15134. }
  15135. else {
  15136. var halfWidth = engine.getRenderWidth() / 2.0;
  15137. var halfHeight = engine.getRenderHeight() / 2.0;
  15138. if (scene.useRightHandedSystem) {
  15139. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15140. }
  15141. else {
  15142. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15143. }
  15144. }
  15145. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15146. return this._projectionMatrix;
  15147. };
  15148. Camera.prototype.getTranformationMatrix = function () {
  15149. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15150. return this._transformMatrix;
  15151. };
  15152. Camera.prototype.updateFrustumPlanes = function () {
  15153. if (!this._refreshFrustumPlanes) {
  15154. return;
  15155. }
  15156. this.getTranformationMatrix();
  15157. if (!this._frustumPlanes) {
  15158. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15159. }
  15160. else {
  15161. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15162. }
  15163. this._refreshFrustumPlanes = false;
  15164. };
  15165. Camera.prototype.isInFrustum = function (target) {
  15166. this.updateFrustumPlanes();
  15167. return target.isInFrustum(this._frustumPlanes);
  15168. };
  15169. Camera.prototype.isCompletelyInFrustum = function (target) {
  15170. this.updateFrustumPlanes();
  15171. return target.isCompletelyInFrustum(this._frustumPlanes);
  15172. };
  15173. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15174. if (length === void 0) { length = 100; }
  15175. if (!transform) {
  15176. transform = this.getWorldMatrix();
  15177. }
  15178. if (!origin) {
  15179. origin = this.position;
  15180. }
  15181. var forward = new BABYLON.Vector3(0, 0, 1);
  15182. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15183. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15184. return new BABYLON.Ray(origin, direction, length);
  15185. };
  15186. Camera.prototype.dispose = function () {
  15187. // Observables
  15188. this.onViewMatrixChangedObservable.clear();
  15189. this.onProjectionMatrixChangedObservable.clear();
  15190. this.onAfterCheckInputsObservable.clear();
  15191. // Inputs
  15192. if (this.inputs) {
  15193. this.inputs.clear();
  15194. }
  15195. // Animations
  15196. this.getScene().stopAnimation(this);
  15197. // Remove from scene
  15198. this.getScene().removeCamera(this);
  15199. while (this._rigCameras.length > 0) {
  15200. this._rigCameras.pop().dispose();
  15201. }
  15202. // Postprocesses
  15203. var i = this._postProcesses.length;
  15204. while (--i >= 0) {
  15205. this._postProcesses[i].dispose(this);
  15206. }
  15207. // Render targets
  15208. var i = this.customRenderTargets.length;
  15209. while (--i >= 0) {
  15210. this.customRenderTargets[i].dispose();
  15211. }
  15212. this.customRenderTargets = [];
  15213. // Active Meshes
  15214. this._activeMeshes.dispose();
  15215. _super.prototype.dispose.call(this);
  15216. };
  15217. Object.defineProperty(Camera.prototype, "leftCamera", {
  15218. // ---- Camera rigs section ----
  15219. get: function () {
  15220. if (this._rigCameras.length < 1) {
  15221. return undefined;
  15222. }
  15223. return this._rigCameras[0];
  15224. },
  15225. enumerable: true,
  15226. configurable: true
  15227. });
  15228. Object.defineProperty(Camera.prototype, "rightCamera", {
  15229. get: function () {
  15230. if (this._rigCameras.length < 2) {
  15231. return undefined;
  15232. }
  15233. return this._rigCameras[1];
  15234. },
  15235. enumerable: true,
  15236. configurable: true
  15237. });
  15238. Camera.prototype.getLeftTarget = function () {
  15239. if (this._rigCameras.length < 1) {
  15240. return undefined;
  15241. }
  15242. return this._rigCameras[0].getTarget();
  15243. };
  15244. Camera.prototype.getRightTarget = function () {
  15245. if (this._rigCameras.length < 2) {
  15246. return undefined;
  15247. }
  15248. return this._rigCameras[1].getTarget();
  15249. };
  15250. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15251. while (this._rigCameras.length > 0) {
  15252. this._rigCameras.pop().dispose();
  15253. }
  15254. this.cameraRigMode = mode;
  15255. this._cameraRigParams = {};
  15256. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15257. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15258. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15259. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15260. // create the rig cameras, unless none
  15261. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15262. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15263. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15264. }
  15265. switch (this.cameraRigMode) {
  15266. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15267. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15268. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15269. break;
  15270. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15271. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15272. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15273. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15274. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15275. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15276. break;
  15277. case Camera.RIG_MODE_VR:
  15278. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15279. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15280. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15281. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15282. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15283. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15284. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15285. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15286. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15287. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15288. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15289. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15290. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15291. if (metrics.compensateDistortion) {
  15292. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15293. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15294. }
  15295. break;
  15296. case Camera.RIG_MODE_WEBVR:
  15297. if (rigParams.vrDisplay) {
  15298. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15299. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15300. //Left eye
  15301. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15302. this._rigCameras[0].setCameraRigParameter("left", true);
  15303. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15304. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15305. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15306. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15307. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15308. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15309. this._rigCameras[0].parent = this;
  15310. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15311. //Right eye
  15312. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15313. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15314. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15315. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15316. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15317. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15318. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15319. this._rigCameras[1].parent = this;
  15320. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15321. }
  15322. break;
  15323. }
  15324. this._cascadePostProcessesToRigCams();
  15325. this.
  15326. update();
  15327. };
  15328. Camera.prototype._getVRProjectionMatrix = function () {
  15329. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15330. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15331. return this._projectionMatrix;
  15332. };
  15333. Camera.prototype._updateCameraRotationMatrix = function () {
  15334. //Here for WebVR
  15335. };
  15336. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15337. //Here for WebVR
  15338. };
  15339. /**
  15340. * This function MUST be overwritten by the different WebVR cameras available.
  15341. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15342. */
  15343. Camera.prototype._getWebVRProjectionMatrix = function () {
  15344. return BABYLON.Matrix.Identity();
  15345. };
  15346. /**
  15347. * This function MUST be overwritten by the different WebVR cameras available.
  15348. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15349. */
  15350. Camera.prototype._getWebVRViewMatrix = function () {
  15351. return BABYLON.Matrix.Identity();
  15352. };
  15353. Camera.prototype.setCameraRigParameter = function (name, value) {
  15354. if (!this._cameraRigParams) {
  15355. this._cameraRigParams = {};
  15356. }
  15357. this._cameraRigParams[name] = value;
  15358. //provisionnally:
  15359. if (name === "interaxialDistance") {
  15360. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15361. }
  15362. };
  15363. /**
  15364. * needs to be overridden by children so sub has required properties to be copied
  15365. */
  15366. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15367. return null;
  15368. };
  15369. /**
  15370. * May need to be overridden by children
  15371. */
  15372. Camera.prototype._updateRigCameras = function () {
  15373. for (var i = 0; i < this._rigCameras.length; i++) {
  15374. this._rigCameras[i].minZ = this.minZ;
  15375. this._rigCameras[i].maxZ = this.maxZ;
  15376. this._rigCameras[i].fov = this.fov;
  15377. }
  15378. // only update viewport when ANAGLYPH
  15379. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15380. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15381. }
  15382. };
  15383. Camera.prototype._setupInputs = function () {
  15384. };
  15385. Camera.prototype.serialize = function () {
  15386. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15387. // Type
  15388. serializationObject.type = this.getClassName();
  15389. // Parent
  15390. if (this.parent) {
  15391. serializationObject.parentId = this.parent.id;
  15392. }
  15393. if (this.inputs) {
  15394. this.inputs.serialize(serializationObject);
  15395. }
  15396. // Animations
  15397. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15398. serializationObject.ranges = this.serializeAnimationRanges();
  15399. return serializationObject;
  15400. };
  15401. Camera.prototype.clone = function (name) {
  15402. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15403. };
  15404. Camera.prototype.getDirection = function (localAxis) {
  15405. var result = BABYLON.Vector3.Zero();
  15406. this.getDirectionToRef(localAxis, result);
  15407. return result;
  15408. };
  15409. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15410. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15411. };
  15412. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15413. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15414. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15415. switch (type) {
  15416. case "ArcRotateCamera":
  15417. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15418. case "DeviceOrientationCamera":
  15419. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15420. case "FollowCamera":
  15421. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15422. case "ArcFollowCamera":
  15423. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15424. case "GamepadCamera":
  15425. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15426. case "TouchCamera":
  15427. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15428. case "VirtualJoysticksCamera":
  15429. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15430. case "WebVRFreeCamera":
  15431. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15432. case "WebVRGamepadCamera":
  15433. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15434. case "VRDeviceOrientationFreeCamera":
  15435. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15436. case "VRDeviceOrientationGamepadCamera":
  15437. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15438. case "AnaglyphArcRotateCamera":
  15439. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15440. case "AnaglyphFreeCamera":
  15441. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15442. case "AnaglyphGamepadCamera":
  15443. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15444. case "AnaglyphUniversalCamera":
  15445. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15446. case "StereoscopicArcRotateCamera":
  15447. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15448. case "StereoscopicFreeCamera":
  15449. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15450. case "StereoscopicGamepadCamera":
  15451. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15452. case "StereoscopicUniversalCamera":
  15453. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15454. case "FreeCamera":// Forcing Universal here
  15455. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15456. default:// Universal Camera is the default value
  15457. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15458. }
  15459. };
  15460. Camera.Parse = function (parsedCamera, scene) {
  15461. var type = parsedCamera.type;
  15462. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15463. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15464. // Parent
  15465. if (parsedCamera.parentId) {
  15466. camera._waitingParentId = parsedCamera.parentId;
  15467. }
  15468. //If camera has an input manager, let it parse inputs settings
  15469. if (camera.inputs) {
  15470. camera.inputs.parse(parsedCamera);
  15471. camera._setupInputs();
  15472. }
  15473. if (camera.setPosition) {
  15474. camera.position.copyFromFloats(0, 0, 0);
  15475. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15476. }
  15477. // Target
  15478. if (parsedCamera.target) {
  15479. if (camera.setTarget) {
  15480. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15481. }
  15482. }
  15483. // Apply 3d rig, when found
  15484. if (parsedCamera.cameraRigMode) {
  15485. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15486. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15487. }
  15488. // Animations
  15489. if (parsedCamera.animations) {
  15490. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15491. var parsedAnimation = parsedCamera.animations[animationIndex];
  15492. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15493. }
  15494. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15495. }
  15496. if (parsedCamera.autoAnimate) {
  15497. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15498. }
  15499. return camera;
  15500. };
  15501. // Statics
  15502. Camera._PERSPECTIVE_CAMERA = 0;
  15503. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15504. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15505. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15506. Camera._RIG_MODE_NONE = 0;
  15507. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15508. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15509. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15510. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15511. Camera._RIG_MODE_VR = 20;
  15512. Camera._RIG_MODE_WEBVR = 21;
  15513. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15514. __decorate([
  15515. BABYLON.serializeAsVector3()
  15516. ], Camera.prototype, "position", void 0);
  15517. __decorate([
  15518. BABYLON.serializeAsVector3()
  15519. ], Camera.prototype, "upVector", void 0);
  15520. __decorate([
  15521. BABYLON.serialize()
  15522. ], Camera.prototype, "orthoLeft", void 0);
  15523. __decorate([
  15524. BABYLON.serialize()
  15525. ], Camera.prototype, "orthoRight", void 0);
  15526. __decorate([
  15527. BABYLON.serialize()
  15528. ], Camera.prototype, "orthoBottom", void 0);
  15529. __decorate([
  15530. BABYLON.serialize()
  15531. ], Camera.prototype, "orthoTop", void 0);
  15532. __decorate([
  15533. BABYLON.serialize()
  15534. ], Camera.prototype, "fov", void 0);
  15535. __decorate([
  15536. BABYLON.serialize()
  15537. ], Camera.prototype, "minZ", void 0);
  15538. __decorate([
  15539. BABYLON.serialize()
  15540. ], Camera.prototype, "maxZ", void 0);
  15541. __decorate([
  15542. BABYLON.serialize()
  15543. ], Camera.prototype, "inertia", void 0);
  15544. __decorate([
  15545. BABYLON.serialize()
  15546. ], Camera.prototype, "mode", void 0);
  15547. __decorate([
  15548. BABYLON.serialize()
  15549. ], Camera.prototype, "layerMask", void 0);
  15550. __decorate([
  15551. BABYLON.serialize()
  15552. ], Camera.prototype, "fovMode", void 0);
  15553. __decorate([
  15554. BABYLON.serialize()
  15555. ], Camera.prototype, "cameraRigMode", void 0);
  15556. __decorate([
  15557. BABYLON.serialize()
  15558. ], Camera.prototype, "interaxialDistance", void 0);
  15559. __decorate([
  15560. BABYLON.serialize()
  15561. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15562. return Camera;
  15563. }(BABYLON.Node));
  15564. BABYLON.Camera = Camera;
  15565. })(BABYLON || (BABYLON = {}));
  15566. //# sourceMappingURL=babylon.camera.js.map
  15567. var BABYLON;
  15568. (function (BABYLON) {
  15569. var RenderingManager = (function () {
  15570. function RenderingManager(scene) {
  15571. this._renderingGroups = new Array();
  15572. this._autoClearDepthStencil = {};
  15573. this._customOpaqueSortCompareFn = {};
  15574. this._customAlphaTestSortCompareFn = {};
  15575. this._customTransparentSortCompareFn = {};
  15576. this._renderinGroupInfo = null;
  15577. this._scene = scene;
  15578. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15579. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15580. }
  15581. }
  15582. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15583. if (depth === void 0) { depth = true; }
  15584. if (stencil === void 0) { stencil = true; }
  15585. if (this._depthStencilBufferAlreadyCleaned) {
  15586. return;
  15587. }
  15588. this._scene.getEngine().clear(null, false, depth, stencil);
  15589. this._depthStencilBufferAlreadyCleaned = true;
  15590. };
  15591. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15592. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15593. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15594. var info = null;
  15595. if (observable) {
  15596. if (!this._renderinGroupInfo) {
  15597. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15598. }
  15599. info = this._renderinGroupInfo;
  15600. info.scene = this._scene;
  15601. info.camera = this._scene.activeCamera;
  15602. }
  15603. // Dispatch sprites
  15604. if (renderSprites) {
  15605. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15606. var manager = this._scene.spriteManagers[index];
  15607. this.dispatchSprites(manager);
  15608. }
  15609. }
  15610. // Render
  15611. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15612. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15613. var renderingGroup = this._renderingGroups[index];
  15614. if (!renderingGroup && !observable)
  15615. continue;
  15616. this._currentIndex = index;
  15617. var renderingGroupMask = 0;
  15618. // Fire PRECLEAR stage
  15619. if (observable) {
  15620. renderingGroupMask = Math.pow(2, index);
  15621. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15622. info.renderingGroupId = index;
  15623. observable.notifyObservers(info, renderingGroupMask);
  15624. }
  15625. // Clear depth/stencil if needed
  15626. if (RenderingManager.AUTOCLEAR) {
  15627. var autoClear = this._autoClearDepthStencil[index];
  15628. if (autoClear && autoClear.autoClear) {
  15629. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15630. }
  15631. }
  15632. if (observable) {
  15633. // Fire PREOPAQUE stage
  15634. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15635. observable.notifyObservers(info, renderingGroupMask);
  15636. // Fire PRETRANSPARENT stage
  15637. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15638. observable.notifyObservers(info, renderingGroupMask);
  15639. }
  15640. if (renderingGroup)
  15641. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15642. // Fire POSTTRANSPARENT stage
  15643. if (observable) {
  15644. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15645. observable.notifyObservers(info, renderingGroupMask);
  15646. }
  15647. }
  15648. };
  15649. RenderingManager.prototype.reset = function () {
  15650. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15651. var renderingGroup = this._renderingGroups[index];
  15652. if (renderingGroup) {
  15653. renderingGroup.prepare();
  15654. }
  15655. }
  15656. };
  15657. RenderingManager.prototype.dispose = function () {
  15658. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15659. var renderingGroup = this._renderingGroups[index];
  15660. if (renderingGroup) {
  15661. renderingGroup.dispose();
  15662. }
  15663. }
  15664. this._renderingGroups.length = 0;
  15665. };
  15666. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15667. if (!this._renderingGroups[renderingGroupId]) {
  15668. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15669. }
  15670. };
  15671. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15672. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15673. this._prepareRenderingGroup(renderingGroupId);
  15674. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15675. };
  15676. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15677. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15678. this._prepareRenderingGroup(renderingGroupId);
  15679. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15680. };
  15681. RenderingManager.prototype.dispatch = function (subMesh) {
  15682. var mesh = subMesh.getMesh();
  15683. var renderingGroupId = mesh.renderingGroupId || 0;
  15684. this._prepareRenderingGroup(renderingGroupId);
  15685. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15686. };
  15687. /**
  15688. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15689. * This allowed control for front to back rendering or reversly depending of the special needs.
  15690. *
  15691. * @param renderingGroupId The rendering group id corresponding to its index
  15692. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15693. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15694. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15695. */
  15696. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15697. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15698. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15699. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15700. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15701. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15702. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15703. if (this._renderingGroups[renderingGroupId]) {
  15704. var group = this._renderingGroups[renderingGroupId];
  15705. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15706. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15707. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15708. }
  15709. };
  15710. /**
  15711. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15712. *
  15713. * @param renderingGroupId The rendering group id corresponding to its index
  15714. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15715. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15716. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15717. */
  15718. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15719. if (depth === void 0) { depth = true; }
  15720. if (stencil === void 0) { stencil = true; }
  15721. this._autoClearDepthStencil[renderingGroupId] = {
  15722. autoClear: autoClearDepthStencil,
  15723. depth: depth,
  15724. stencil: stencil
  15725. };
  15726. };
  15727. /**
  15728. * The max id used for rendering groups (not included)
  15729. */
  15730. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15731. /**
  15732. * The min id used for rendering groups (included)
  15733. */
  15734. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15735. /**
  15736. * Used to globally prevent autoclearing scenes.
  15737. */
  15738. RenderingManager.AUTOCLEAR = true;
  15739. return RenderingManager;
  15740. }());
  15741. BABYLON.RenderingManager = RenderingManager;
  15742. })(BABYLON || (BABYLON = {}));
  15743. //# sourceMappingURL=babylon.renderingManager.js.map
  15744. var BABYLON;
  15745. (function (BABYLON) {
  15746. var RenderingGroup = (function () {
  15747. /**
  15748. * Creates a new rendering group.
  15749. * @param index The rendering group index
  15750. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15751. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15752. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15753. */
  15754. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15755. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15756. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15757. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15758. this.index = index;
  15759. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15760. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15761. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15762. this._particleSystems = new BABYLON.SmartArray(256);
  15763. this._spriteManagers = new BABYLON.SmartArray(256);
  15764. this._edgesRenderers = new BABYLON.SmartArray(16);
  15765. this._scene = scene;
  15766. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15767. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15768. this.transparentSortCompareFn = transparentSortCompareFn;
  15769. }
  15770. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15771. /**
  15772. * Set the opaque sort comparison function.
  15773. * If null the sub meshes will be render in the order they were created
  15774. */
  15775. set: function (value) {
  15776. this._opaqueSortCompareFn = value;
  15777. if (value) {
  15778. this._renderOpaque = this.renderOpaqueSorted;
  15779. }
  15780. else {
  15781. this._renderOpaque = RenderingGroup.renderUnsorted;
  15782. }
  15783. },
  15784. enumerable: true,
  15785. configurable: true
  15786. });
  15787. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15788. /**
  15789. * Set the alpha test sort comparison function.
  15790. * If null the sub meshes will be render in the order they were created
  15791. */
  15792. set: function (value) {
  15793. this._alphaTestSortCompareFn = value;
  15794. if (value) {
  15795. this._renderAlphaTest = this.renderAlphaTestSorted;
  15796. }
  15797. else {
  15798. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15799. }
  15800. },
  15801. enumerable: true,
  15802. configurable: true
  15803. });
  15804. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15805. /**
  15806. * Set the transparent sort comparison function.
  15807. * If null the sub meshes will be render in the order they were created
  15808. */
  15809. set: function (value) {
  15810. if (value) {
  15811. this._transparentSortCompareFn = value;
  15812. }
  15813. else {
  15814. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15815. }
  15816. this._renderTransparent = this.renderTransparentSorted;
  15817. },
  15818. enumerable: true,
  15819. configurable: true
  15820. });
  15821. /**
  15822. * Render all the sub meshes contained in the group.
  15823. * @param customRenderFunction Used to override the default render behaviour of the group.
  15824. * @returns true if rendered some submeshes.
  15825. */
  15826. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  15827. if (customRenderFunction) {
  15828. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15829. return;
  15830. }
  15831. var engine = this._scene.getEngine();
  15832. // Opaque
  15833. if (this._opaqueSubMeshes.length !== 0) {
  15834. this._renderOpaque(this._opaqueSubMeshes);
  15835. }
  15836. // Alpha test
  15837. if (this._alphaTestSubMeshes.length !== 0) {
  15838. engine.setAlphaTesting(true);
  15839. this._renderAlphaTest(this._alphaTestSubMeshes);
  15840. engine.setAlphaTesting(false);
  15841. }
  15842. var stencilState = engine.getStencilBuffer();
  15843. engine.setStencilBuffer(false);
  15844. // Sprites
  15845. if (renderSprites) {
  15846. this._renderSprites();
  15847. }
  15848. // Particles
  15849. if (renderParticles) {
  15850. this._renderParticles(activeMeshes);
  15851. }
  15852. if (this.onBeforeTransparentRendering) {
  15853. this.onBeforeTransparentRendering();
  15854. }
  15855. // Transparent
  15856. if (this._transparentSubMeshes.length !== 0) {
  15857. this._renderTransparent(this._transparentSubMeshes);
  15858. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15859. }
  15860. // Set back stencil to false in case it changes before the edge renderer.
  15861. engine.setStencilBuffer(false);
  15862. // Edges
  15863. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15864. this._edgesRenderers.data[edgesRendererIndex].render();
  15865. }
  15866. // Restore Stencil state.
  15867. engine.setStencilBuffer(stencilState);
  15868. };
  15869. /**
  15870. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15871. * @param subMeshes The submeshes to render
  15872. */
  15873. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15874. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15875. };
  15876. /**
  15877. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15878. * @param subMeshes The submeshes to render
  15879. */
  15880. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15881. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15882. };
  15883. /**
  15884. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15885. * @param subMeshes The submeshes to render
  15886. */
  15887. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15888. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15889. };
  15890. /**
  15891. * Renders the submeshes in a specified order.
  15892. * @param subMeshes The submeshes to sort before render
  15893. * @param sortCompareFn The comparison function use to sort
  15894. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15895. * @param transparent Specifies to activate blending if true
  15896. */
  15897. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15898. var subIndex = 0;
  15899. var subMesh;
  15900. for (; subIndex < subMeshes.length; subIndex++) {
  15901. subMesh = subMeshes.data[subIndex];
  15902. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15903. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15904. }
  15905. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15906. sortedArray.sort(sortCompareFn);
  15907. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15908. subMesh = sortedArray[subIndex];
  15909. subMesh.render(transparent);
  15910. }
  15911. };
  15912. /**
  15913. * Renders the submeshes in the order they were dispatched (no sort applied).
  15914. * @param subMeshes The submeshes to render
  15915. */
  15916. RenderingGroup.renderUnsorted = function (subMeshes) {
  15917. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15918. var submesh = subMeshes.data[subIndex];
  15919. submesh.render(false);
  15920. }
  15921. };
  15922. /**
  15923. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15924. * are rendered back to front if in the same alpha index.
  15925. *
  15926. * @param a The first submesh
  15927. * @param b The second submesh
  15928. * @returns The result of the comparison
  15929. */
  15930. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15931. // Alpha index first
  15932. if (a._alphaIndex > b._alphaIndex) {
  15933. return 1;
  15934. }
  15935. if (a._alphaIndex < b._alphaIndex) {
  15936. return -1;
  15937. }
  15938. // Then distance to camera
  15939. return RenderingGroup.backToFrontSortCompare(a, b);
  15940. };
  15941. /**
  15942. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15943. * are rendered back to front.
  15944. *
  15945. * @param a The first submesh
  15946. * @param b The second submesh
  15947. * @returns The result of the comparison
  15948. */
  15949. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15950. // Then distance to camera
  15951. if (a._distanceToCamera < b._distanceToCamera) {
  15952. return 1;
  15953. }
  15954. if (a._distanceToCamera > b._distanceToCamera) {
  15955. return -1;
  15956. }
  15957. return 0;
  15958. };
  15959. /**
  15960. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15961. * are rendered front to back (prevent overdraw).
  15962. *
  15963. * @param a The first submesh
  15964. * @param b The second submesh
  15965. * @returns The result of the comparison
  15966. */
  15967. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15968. // Then distance to camera
  15969. if (a._distanceToCamera < b._distanceToCamera) {
  15970. return -1;
  15971. }
  15972. if (a._distanceToCamera > b._distanceToCamera) {
  15973. return 1;
  15974. }
  15975. return 0;
  15976. };
  15977. /**
  15978. * Resets the different lists of submeshes to prepare a new frame.
  15979. */
  15980. RenderingGroup.prototype.prepare = function () {
  15981. this._opaqueSubMeshes.reset();
  15982. this._transparentSubMeshes.reset();
  15983. this._alphaTestSubMeshes.reset();
  15984. this._particleSystems.reset();
  15985. this._spriteManagers.reset();
  15986. this._edgesRenderers.reset();
  15987. };
  15988. RenderingGroup.prototype.dispose = function () {
  15989. this._opaqueSubMeshes.dispose();
  15990. this._transparentSubMeshes.dispose();
  15991. this._alphaTestSubMeshes.dispose();
  15992. this._particleSystems.dispose();
  15993. this._spriteManagers.dispose();
  15994. this._edgesRenderers.dispose();
  15995. };
  15996. /**
  15997. * Inserts the submesh in its correct queue depending on its material.
  15998. * @param subMesh The submesh to dispatch
  15999. */
  16000. RenderingGroup.prototype.dispatch = function (subMesh) {
  16001. var material = subMesh.getMaterial();
  16002. var mesh = subMesh.getMesh();
  16003. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16004. this._transparentSubMeshes.push(subMesh);
  16005. }
  16006. else if (material.needAlphaTesting()) {
  16007. this._alphaTestSubMeshes.push(subMesh);
  16008. }
  16009. else {
  16010. this._opaqueSubMeshes.push(subMesh); // Opaque
  16011. }
  16012. if (mesh._edgesRenderer) {
  16013. this._edgesRenderers.push(mesh._edgesRenderer);
  16014. }
  16015. };
  16016. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16017. this._spriteManagers.push(spriteManager);
  16018. };
  16019. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16020. this._particleSystems.push(particleSystem);
  16021. };
  16022. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16023. if (this._particleSystems.length === 0) {
  16024. return;
  16025. }
  16026. // Particles
  16027. var activeCamera = this._scene.activeCamera;
  16028. this._scene._particlesDuration.beginMonitoring();
  16029. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16030. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16031. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16032. continue;
  16033. }
  16034. var emitter = particleSystem.emitter;
  16035. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16036. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16037. }
  16038. }
  16039. this._scene._particlesDuration.endMonitoring(false);
  16040. };
  16041. RenderingGroup.prototype._renderSprites = function () {
  16042. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16043. return;
  16044. }
  16045. // Sprites
  16046. var activeCamera = this._scene.activeCamera;
  16047. this._scene._spritesDuration.beginMonitoring();
  16048. for (var id = 0; id < this._spriteManagers.length; id++) {
  16049. var spriteManager = this._spriteManagers.data[id];
  16050. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16051. spriteManager.render();
  16052. }
  16053. }
  16054. this._scene._spritesDuration.endMonitoring(false);
  16055. };
  16056. return RenderingGroup;
  16057. }());
  16058. BABYLON.RenderingGroup = RenderingGroup;
  16059. })(BABYLON || (BABYLON = {}));
  16060. //# sourceMappingURL=babylon.renderingGroup.js.map
  16061. var BABYLON;
  16062. (function (BABYLON) {
  16063. var ClickInfo = (function () {
  16064. function ClickInfo() {
  16065. this._singleClick = false;
  16066. this._doubleClick = false;
  16067. this._hasSwiped = false;
  16068. this._ignore = false;
  16069. }
  16070. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16071. get: function () {
  16072. return this._singleClick;
  16073. },
  16074. set: function (b) {
  16075. this._singleClick = b;
  16076. },
  16077. enumerable: true,
  16078. configurable: true
  16079. });
  16080. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16081. get: function () {
  16082. return this._doubleClick;
  16083. },
  16084. set: function (b) {
  16085. this._doubleClick = b;
  16086. },
  16087. enumerable: true,
  16088. configurable: true
  16089. });
  16090. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16091. get: function () {
  16092. return this._hasSwiped;
  16093. },
  16094. set: function (b) {
  16095. this._hasSwiped = b;
  16096. },
  16097. enumerable: true,
  16098. configurable: true
  16099. });
  16100. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16101. get: function () {
  16102. return this._ignore;
  16103. },
  16104. set: function (b) {
  16105. this._ignore = b;
  16106. },
  16107. enumerable: true,
  16108. configurable: true
  16109. });
  16110. return ClickInfo;
  16111. }());
  16112. var PointerEventTypes = (function () {
  16113. function PointerEventTypes() {
  16114. }
  16115. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16116. get: function () {
  16117. return PointerEventTypes._POINTERDOWN;
  16118. },
  16119. enumerable: true,
  16120. configurable: true
  16121. });
  16122. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16123. get: function () {
  16124. return PointerEventTypes._POINTERUP;
  16125. },
  16126. enumerable: true,
  16127. configurable: true
  16128. });
  16129. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16130. get: function () {
  16131. return PointerEventTypes._POINTERMOVE;
  16132. },
  16133. enumerable: true,
  16134. configurable: true
  16135. });
  16136. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16137. get: function () {
  16138. return PointerEventTypes._POINTERWHEEL;
  16139. },
  16140. enumerable: true,
  16141. configurable: true
  16142. });
  16143. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16144. get: function () {
  16145. return PointerEventTypes._POINTERPICK;
  16146. },
  16147. enumerable: true,
  16148. configurable: true
  16149. });
  16150. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  16151. get: function () {
  16152. return PointerEventTypes._POINTERTAP;
  16153. },
  16154. enumerable: true,
  16155. configurable: true
  16156. });
  16157. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  16158. get: function () {
  16159. return PointerEventTypes._POINTERDOUBLETAP;
  16160. },
  16161. enumerable: true,
  16162. configurable: true
  16163. });
  16164. PointerEventTypes._POINTERDOWN = 0x01;
  16165. PointerEventTypes._POINTERUP = 0x02;
  16166. PointerEventTypes._POINTERMOVE = 0x04;
  16167. PointerEventTypes._POINTERWHEEL = 0x08;
  16168. PointerEventTypes._POINTERPICK = 0x10;
  16169. PointerEventTypes._POINTERTAP = 0x20;
  16170. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  16171. return PointerEventTypes;
  16172. }());
  16173. BABYLON.PointerEventTypes = PointerEventTypes;
  16174. var PointerInfoBase = (function () {
  16175. function PointerInfoBase(type, event) {
  16176. this.type = type;
  16177. this.event = event;
  16178. }
  16179. return PointerInfoBase;
  16180. }());
  16181. BABYLON.PointerInfoBase = PointerInfoBase;
  16182. /**
  16183. * This class is used to store pointer related info for the onPrePointerObservable event.
  16184. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16185. */
  16186. var PointerInfoPre = (function (_super) {
  16187. __extends(PointerInfoPre, _super);
  16188. function PointerInfoPre(type, event, localX, localY) {
  16189. var _this = _super.call(this, type, event) || this;
  16190. _this.skipOnPointerObservable = false;
  16191. _this.localPosition = new BABYLON.Vector2(localX, localY);
  16192. return _this;
  16193. }
  16194. return PointerInfoPre;
  16195. }(PointerInfoBase));
  16196. BABYLON.PointerInfoPre = PointerInfoPre;
  16197. /**
  16198. * This type contains all the data related to a pointer event in Babylon.js.
  16199. * 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.
  16200. */
  16201. var PointerInfo = (function (_super) {
  16202. __extends(PointerInfo, _super);
  16203. function PointerInfo(type, event, pickInfo) {
  16204. var _this = _super.call(this, type, event) || this;
  16205. _this.pickInfo = pickInfo;
  16206. return _this;
  16207. }
  16208. return PointerInfo;
  16209. }(PointerInfoBase));
  16210. BABYLON.PointerInfo = PointerInfo;
  16211. /**
  16212. * This class is used by the onRenderingGroupObservable
  16213. */
  16214. var RenderingGroupInfo = (function () {
  16215. function RenderingGroupInfo() {
  16216. }
  16217. /**
  16218. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16219. * This stage will be fired no matter what
  16220. */
  16221. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16222. /**
  16223. * Called before opaque object are rendered.
  16224. * This stage will be fired only if there's 3D Opaque content to render
  16225. */
  16226. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16227. /**
  16228. * Called after the opaque objects are rendered and before the transparent ones
  16229. * This stage will be fired only if there's 3D transparent content to render
  16230. */
  16231. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16232. /**
  16233. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16234. * This stage will be fired no matter what
  16235. */
  16236. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16237. return RenderingGroupInfo;
  16238. }());
  16239. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16240. /**
  16241. * Represents a scene to be rendered by the engine.
  16242. * @see http://doc.babylonjs.com/page.php?p=21911
  16243. */
  16244. var Scene = (function () {
  16245. /**
  16246. * @constructor
  16247. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16248. */
  16249. function Scene(engine) {
  16250. // Members
  16251. this.autoClear = true;
  16252. this.autoClearDepthAndStencil = true;
  16253. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16254. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16255. this.forceWireframe = false;
  16256. this._forcePointsCloud = false;
  16257. this.forceShowBoundingBoxes = false;
  16258. this.animationsEnabled = true;
  16259. this.constantlyUpdateMeshUnderPointer = false;
  16260. this.hoverCursor = "pointer";
  16261. this.defaultCursor = "";
  16262. // Metadata
  16263. this.metadata = null;
  16264. // Events
  16265. /**
  16266. * An event triggered when the scene is disposed.
  16267. * @type {BABYLON.Observable}
  16268. */
  16269. this.onDisposeObservable = new BABYLON.Observable();
  16270. /**
  16271. * An event triggered before rendering the scene
  16272. * @type {BABYLON.Observable}
  16273. */
  16274. this.onBeforeRenderObservable = new BABYLON.Observable();
  16275. /**
  16276. * An event triggered after rendering the scene
  16277. * @type {BABYLON.Observable}
  16278. */
  16279. this.onAfterRenderObservable = new BABYLON.Observable();
  16280. /**
  16281. * An event triggered when the scene is ready
  16282. * @type {BABYLON.Observable}
  16283. */
  16284. this.onReadyObservable = new BABYLON.Observable();
  16285. /**
  16286. * An event triggered before rendering a camera
  16287. * @type {BABYLON.Observable}
  16288. */
  16289. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16290. /**
  16291. * An event triggered after rendering a camera
  16292. * @type {BABYLON.Observable}
  16293. */
  16294. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16295. /**
  16296. * An event triggered when a camera is created
  16297. * @type {BABYLON.Observable}
  16298. */
  16299. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16300. /**
  16301. * An event triggered when a camera is removed
  16302. * @type {BABYLON.Observable}
  16303. */
  16304. this.onCameraRemovedObservable = new BABYLON.Observable();
  16305. /**
  16306. * An event triggered when a light is created
  16307. * @type {BABYLON.Observable}
  16308. */
  16309. this.onNewLightAddedObservable = new BABYLON.Observable();
  16310. /**
  16311. * An event triggered when a light is removed
  16312. * @type {BABYLON.Observable}
  16313. */
  16314. this.onLightRemovedObservable = new BABYLON.Observable();
  16315. /**
  16316. * An event triggered when a geometry is created
  16317. * @type {BABYLON.Observable}
  16318. */
  16319. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16320. /**
  16321. * An event triggered when a geometry is removed
  16322. * @type {BABYLON.Observable}
  16323. */
  16324. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16325. /**
  16326. * An event triggered when a mesh is created
  16327. * @type {BABYLON.Observable}
  16328. */
  16329. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16330. /**
  16331. * An event triggered when a mesh is removed
  16332. * @type {BABYLON.Observable}
  16333. */
  16334. this.onMeshRemovedObservable = new BABYLON.Observable();
  16335. /**
  16336. * An event triggered before calculating deterministic simulation step
  16337. * @type {BABYLON.Observable}
  16338. */
  16339. this.onBeforeStepObservable = new BABYLON.Observable();
  16340. /**
  16341. * An event triggered after calculating deterministic simulation step
  16342. * @type {BABYLON.Observable}
  16343. */
  16344. this.onAfterStepObservable = new BABYLON.Observable();
  16345. /**
  16346. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16347. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16348. * 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)
  16349. */
  16350. this.onRenderingGroupObservable = new BABYLON.Observable();
  16351. // Animations
  16352. this.animations = [];
  16353. /**
  16354. * 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).
  16355. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16356. */
  16357. this.onPrePointerObservable = new BABYLON.Observable();
  16358. /**
  16359. * Observable event triggered each time an input event is received from the rendering canvas
  16360. */
  16361. this.onPointerObservable = new BABYLON.Observable();
  16362. this._meshPickProceed = false;
  16363. this._previousHasSwiped = false;
  16364. this._currentPickResult = null;
  16365. this._previousPickResult = null;
  16366. this._isButtonPressed = false;
  16367. this._doubleClickOccured = false;
  16368. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16369. this.cameraToUseForPointers = null;
  16370. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16371. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16372. this._startingPointerTime = 0;
  16373. this._previousStartingPointerTime = 0;
  16374. // Deterministic lockstep
  16375. this._timeAccumulator = 0;
  16376. this._currentStepId = 0;
  16377. this._currentInternalStep = 0;
  16378. // Coordinate system
  16379. /**
  16380. * use right-handed coordinate system on this scene.
  16381. * @type {boolean}
  16382. */
  16383. this._useRightHandedSystem = false;
  16384. // Fog
  16385. this._fogEnabled = true;
  16386. this._fogMode = Scene.FOGMODE_NONE;
  16387. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16388. this.fogDensity = 0.1;
  16389. this.fogStart = 0;
  16390. this.fogEnd = 1000.0;
  16391. // Lights
  16392. /**
  16393. * is shadow enabled on this scene.
  16394. * @type {boolean}
  16395. */
  16396. this._shadowsEnabled = true;
  16397. /**
  16398. * is light enabled on this scene.
  16399. * @type {boolean}
  16400. */
  16401. this._lightsEnabled = true;
  16402. /**
  16403. * All of the lights added to this scene.
  16404. * @see BABYLON.Light
  16405. * @type {BABYLON.Light[]}
  16406. */
  16407. this.lights = new Array();
  16408. // Cameras
  16409. /** All of the cameras added to this scene. */
  16410. this.cameras = new Array();
  16411. /** All of the active cameras added to this scene. */
  16412. this.activeCameras = new Array();
  16413. // Meshes
  16414. /**
  16415. * All of the (abstract) meshes added to this scene.
  16416. * @see BABYLON.AbstractMesh
  16417. * @type {BABYLON.AbstractMesh[]}
  16418. */
  16419. this.meshes = new Array();
  16420. // Geometries
  16421. this._geometries = new Array();
  16422. this.materials = new Array();
  16423. this.multiMaterials = new Array();
  16424. // Textures
  16425. this._texturesEnabled = true;
  16426. this.textures = new Array();
  16427. // Particles
  16428. this.particlesEnabled = true;
  16429. this.particleSystems = new Array();
  16430. // Sprites
  16431. this.spritesEnabled = true;
  16432. this.spriteManagers = new Array();
  16433. // Layers
  16434. this.layers = new Array();
  16435. this.highlightLayers = new Array();
  16436. // Skeletons
  16437. this._skeletonsEnabled = true;
  16438. this.skeletons = new Array();
  16439. // Morph targets
  16440. this.morphTargetManagers = new Array();
  16441. // Lens flares
  16442. this.lensFlaresEnabled = true;
  16443. this.lensFlareSystems = new Array();
  16444. // Collisions
  16445. this.collisionsEnabled = true;
  16446. /** Defines the gravity applied to this scene */
  16447. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16448. // Postprocesses
  16449. this.postProcesses = new Array();
  16450. this.postProcessesEnabled = true;
  16451. // Customs render targets
  16452. this.renderTargetsEnabled = true;
  16453. this.dumpNextRenderTargets = false;
  16454. this.customRenderTargets = new Array();
  16455. // Imported meshes
  16456. this.importedMeshesFiles = new Array();
  16457. // Probes
  16458. this.probesEnabled = true;
  16459. this.reflectionProbes = new Array();
  16460. this._actionManagers = new Array();
  16461. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16462. // Procedural textures
  16463. this.proceduralTexturesEnabled = true;
  16464. this._proceduralTextures = new Array();
  16465. this.soundTracks = new Array();
  16466. this._audioEnabled = true;
  16467. this._headphone = false;
  16468. // Performance counters
  16469. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16470. this._totalLightsCounter = new BABYLON.PerfCounter();
  16471. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16472. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16473. this._totalVertices = new BABYLON.PerfCounter();
  16474. this._activeIndices = new BABYLON.PerfCounter();
  16475. this._activeParticles = new BABYLON.PerfCounter();
  16476. this._lastFrameDuration = new BABYLON.PerfCounter();
  16477. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16478. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16479. this._particlesDuration = new BABYLON.PerfCounter();
  16480. this._renderDuration = new BABYLON.PerfCounter();
  16481. this._spritesDuration = new BABYLON.PerfCounter();
  16482. this._activeBones = new BABYLON.PerfCounter();
  16483. this._animationTime = 0;
  16484. this.animationTimeScale = 1;
  16485. this._renderId = 0;
  16486. this._executeWhenReadyTimeoutId = -1;
  16487. this._intermediateRendering = false;
  16488. this._viewUpdateFlag = -1;
  16489. this._projectionUpdateFlag = -1;
  16490. this._toBeDisposed = new BABYLON.SmartArray(256);
  16491. this._pendingData = []; //ANY
  16492. this._activeMeshes = new BABYLON.SmartArray(256);
  16493. this._processedMaterials = new BABYLON.SmartArray(256);
  16494. this._renderTargets = new BABYLON.SmartArray(256);
  16495. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16496. this._activeSkeletons = new BABYLON.SmartArray(32);
  16497. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16498. this._activeAnimatables = new Array();
  16499. this._transformMatrix = BABYLON.Matrix.Zero();
  16500. this.requireLightSorting = false;
  16501. this._uniqueIdCounter = 0;
  16502. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16503. this._engine.scenes.push(this);
  16504. this._uid = null;
  16505. this._renderingManager = new BABYLON.RenderingManager(this);
  16506. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16507. if (BABYLON.OutlineRenderer) {
  16508. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16509. }
  16510. this.attachControl();
  16511. if (BABYLON.SoundTrack) {
  16512. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16513. }
  16514. //simplification queue
  16515. if (BABYLON.SimplificationQueue) {
  16516. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16517. }
  16518. //collision coordinator initialization. For now legacy per default.
  16519. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16520. // Uniform Buffer
  16521. this._createUbo();
  16522. // Default Image processing definition.
  16523. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16524. }
  16525. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16526. /** The fog is deactivated */
  16527. get: function () {
  16528. return Scene._FOGMODE_NONE;
  16529. },
  16530. enumerable: true,
  16531. configurable: true
  16532. });
  16533. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16534. /** The fog density is following an exponential function */
  16535. get: function () {
  16536. return Scene._FOGMODE_EXP;
  16537. },
  16538. enumerable: true,
  16539. configurable: true
  16540. });
  16541. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16542. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16543. get: function () {
  16544. return Scene._FOGMODE_EXP2;
  16545. },
  16546. enumerable: true,
  16547. configurable: true
  16548. });
  16549. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16550. /** The fog density is following a linear function. */
  16551. get: function () {
  16552. return Scene._FOGMODE_LINEAR;
  16553. },
  16554. enumerable: true,
  16555. configurable: true
  16556. });
  16557. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16558. /**
  16559. * Texture used in all pbr material as the reflection texture.
  16560. * As in the majority of the scene they are the same (exception for multi room and so on),
  16561. * this is easier to reference from here than from all the materials.
  16562. */
  16563. get: function () {
  16564. return this._environmentTexture;
  16565. },
  16566. /**
  16567. * Texture used in all pbr material as the reflection texture.
  16568. * As in the majority of the scene they are the same (exception for multi room and so on),
  16569. * this is easier to set here than in all the materials.
  16570. */
  16571. set: function (value) {
  16572. this._environmentTexture = value;
  16573. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16574. },
  16575. enumerable: true,
  16576. configurable: true
  16577. });
  16578. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16579. /**
  16580. * Default image processing configuration used either in the rendering
  16581. * Forward main pass or through the imageProcessingPostProcess if present.
  16582. * As in the majority of the scene they are the same (exception for multi camera),
  16583. * this is easier to reference from here than from all the materials and post process.
  16584. *
  16585. * No setter as we it is a shared configuration, you can set the values instead.
  16586. */
  16587. get: function () {
  16588. return this._imageProcessingConfiguration;
  16589. },
  16590. enumerable: true,
  16591. configurable: true
  16592. });
  16593. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16594. get: function () {
  16595. return this._forcePointsCloud;
  16596. },
  16597. set: function (value) {
  16598. if (this._forcePointsCloud === value) {
  16599. return;
  16600. }
  16601. this._forcePointsCloud = value;
  16602. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16603. },
  16604. enumerable: true,
  16605. configurable: true
  16606. });
  16607. Object.defineProperty(Scene.prototype, "onDispose", {
  16608. /** A function to be executed when this scene is disposed. */
  16609. set: function (callback) {
  16610. if (this._onDisposeObserver) {
  16611. this.onDisposeObservable.remove(this._onDisposeObserver);
  16612. }
  16613. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16614. },
  16615. enumerable: true,
  16616. configurable: true
  16617. });
  16618. Object.defineProperty(Scene.prototype, "beforeRender", {
  16619. /** A function to be executed before rendering this scene */
  16620. set: function (callback) {
  16621. if (this._onBeforeRenderObserver) {
  16622. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16623. }
  16624. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16625. },
  16626. enumerable: true,
  16627. configurable: true
  16628. });
  16629. Object.defineProperty(Scene.prototype, "afterRender", {
  16630. /** A function to be executed after rendering this scene */
  16631. set: function (callback) {
  16632. if (this._onAfterRenderObserver) {
  16633. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16634. }
  16635. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16636. },
  16637. enumerable: true,
  16638. configurable: true
  16639. });
  16640. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16641. set: function (callback) {
  16642. if (this._onBeforeCameraRenderObserver) {
  16643. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16644. }
  16645. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16646. },
  16647. enumerable: true,
  16648. configurable: true
  16649. });
  16650. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16651. set: function (callback) {
  16652. if (this._onAfterCameraRenderObserver) {
  16653. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16654. }
  16655. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16656. },
  16657. enumerable: true,
  16658. configurable: true
  16659. });
  16660. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16661. get: function () {
  16662. if (!this._gamepadManager) {
  16663. this._gamepadManager = new BABYLON.GamepadManager();
  16664. }
  16665. return this._gamepadManager;
  16666. },
  16667. enumerable: true,
  16668. configurable: true
  16669. });
  16670. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16671. get: function () {
  16672. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16673. },
  16674. enumerable: true,
  16675. configurable: true
  16676. });
  16677. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16678. get: function () {
  16679. return this._useRightHandedSystem;
  16680. },
  16681. set: function (value) {
  16682. if (this._useRightHandedSystem === value) {
  16683. return;
  16684. }
  16685. this._useRightHandedSystem = value;
  16686. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16687. },
  16688. enumerable: true,
  16689. configurable: true
  16690. });
  16691. Scene.prototype.setStepId = function (newStepId) {
  16692. this._currentStepId = newStepId;
  16693. };
  16694. ;
  16695. Scene.prototype.getStepId = function () {
  16696. return this._currentStepId;
  16697. };
  16698. ;
  16699. Scene.prototype.getInternalStep = function () {
  16700. return this._currentInternalStep;
  16701. };
  16702. ;
  16703. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16704. get: function () {
  16705. return this._fogEnabled;
  16706. },
  16707. /**
  16708. * is fog enabled on this scene.
  16709. */
  16710. set: function (value) {
  16711. if (this._fogEnabled === value) {
  16712. return;
  16713. }
  16714. this._fogEnabled = value;
  16715. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16716. },
  16717. enumerable: true,
  16718. configurable: true
  16719. });
  16720. Object.defineProperty(Scene.prototype, "fogMode", {
  16721. get: function () {
  16722. return this._fogMode;
  16723. },
  16724. set: function (value) {
  16725. if (this._fogMode === value) {
  16726. return;
  16727. }
  16728. this._fogMode = value;
  16729. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16730. },
  16731. enumerable: true,
  16732. configurable: true
  16733. });
  16734. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16735. get: function () {
  16736. return this._shadowsEnabled;
  16737. },
  16738. set: function (value) {
  16739. if (this._shadowsEnabled === value) {
  16740. return;
  16741. }
  16742. this._shadowsEnabled = value;
  16743. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16744. },
  16745. enumerable: true,
  16746. configurable: true
  16747. });
  16748. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16749. get: function () {
  16750. return this._lightsEnabled;
  16751. },
  16752. set: function (value) {
  16753. if (this._lightsEnabled === value) {
  16754. return;
  16755. }
  16756. this._lightsEnabled = value;
  16757. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16758. },
  16759. enumerable: true,
  16760. configurable: true
  16761. });
  16762. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16763. /** The default material used on meshes when no material is affected */
  16764. get: function () {
  16765. if (!this._defaultMaterial) {
  16766. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16767. }
  16768. return this._defaultMaterial;
  16769. },
  16770. /** The default material used on meshes when no material is affected */
  16771. set: function (value) {
  16772. this._defaultMaterial = value;
  16773. },
  16774. enumerable: true,
  16775. configurable: true
  16776. });
  16777. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16778. get: function () {
  16779. return this._texturesEnabled;
  16780. },
  16781. set: function (value) {
  16782. if (this._texturesEnabled === value) {
  16783. return;
  16784. }
  16785. this._texturesEnabled = value;
  16786. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16787. },
  16788. enumerable: true,
  16789. configurable: true
  16790. });
  16791. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16792. get: function () {
  16793. return this._skeletonsEnabled;
  16794. },
  16795. set: function (value) {
  16796. if (this._skeletonsEnabled === value) {
  16797. return;
  16798. }
  16799. this._skeletonsEnabled = value;
  16800. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16801. },
  16802. enumerable: true,
  16803. configurable: true
  16804. });
  16805. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16806. get: function () {
  16807. if (!this._postProcessRenderPipelineManager) {
  16808. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16809. }
  16810. return this._postProcessRenderPipelineManager;
  16811. },
  16812. enumerable: true,
  16813. configurable: true
  16814. });
  16815. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16816. get: function () {
  16817. return this._frustumPlanes;
  16818. },
  16819. enumerable: true,
  16820. configurable: true
  16821. });
  16822. Object.defineProperty(Scene.prototype, "debugLayer", {
  16823. // Properties
  16824. get: function () {
  16825. if (!this._debugLayer) {
  16826. this._debugLayer = new BABYLON.DebugLayer(this);
  16827. }
  16828. return this._debugLayer;
  16829. },
  16830. enumerable: true,
  16831. configurable: true
  16832. });
  16833. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16834. get: function () {
  16835. return this._workerCollisions;
  16836. },
  16837. set: function (enabled) {
  16838. if (!BABYLON.CollisionCoordinatorLegacy) {
  16839. return;
  16840. }
  16841. enabled = (enabled && !!Worker);
  16842. this._workerCollisions = enabled;
  16843. if (this.collisionCoordinator) {
  16844. this.collisionCoordinator.destroy();
  16845. }
  16846. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16847. this.collisionCoordinator.init(this);
  16848. },
  16849. enumerable: true,
  16850. configurable: true
  16851. });
  16852. Object.defineProperty(Scene.prototype, "selectionOctree", {
  16853. get: function () {
  16854. return this._selectionOctree;
  16855. },
  16856. enumerable: true,
  16857. configurable: true
  16858. });
  16859. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16860. /**
  16861. * The mesh that is currently under the pointer.
  16862. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16863. */
  16864. get: function () {
  16865. return this._pointerOverMesh;
  16866. },
  16867. enumerable: true,
  16868. configurable: true
  16869. });
  16870. Object.defineProperty(Scene.prototype, "pointerX", {
  16871. /**
  16872. * Current on-screen X position of the pointer
  16873. * @return {number} X position of the pointer
  16874. */
  16875. get: function () {
  16876. return this._pointerX;
  16877. },
  16878. enumerable: true,
  16879. configurable: true
  16880. });
  16881. Object.defineProperty(Scene.prototype, "pointerY", {
  16882. /**
  16883. * Current on-screen Y position of the pointer
  16884. * @return {number} Y position of the pointer
  16885. */
  16886. get: function () {
  16887. return this._pointerY;
  16888. },
  16889. enumerable: true,
  16890. configurable: true
  16891. });
  16892. Scene.prototype.getCachedMaterial = function () {
  16893. return this._cachedMaterial;
  16894. };
  16895. Scene.prototype.getCachedEffect = function () {
  16896. return this._cachedEffect;
  16897. };
  16898. Scene.prototype.getCachedVisibility = function () {
  16899. return this._cachedVisibility;
  16900. };
  16901. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  16902. if (visibility === void 0) { visibility = 1; }
  16903. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16904. };
  16905. Scene.prototype.getBoundingBoxRenderer = function () {
  16906. if (!this._boundingBoxRenderer) {
  16907. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16908. }
  16909. return this._boundingBoxRenderer;
  16910. };
  16911. Scene.prototype.getOutlineRenderer = function () {
  16912. return this._outlineRenderer;
  16913. };
  16914. Scene.prototype.getEngine = function () {
  16915. return this._engine;
  16916. };
  16917. Scene.prototype.getTotalVertices = function () {
  16918. return this._totalVertices.current;
  16919. };
  16920. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16921. get: function () {
  16922. return this._totalVertices;
  16923. },
  16924. enumerable: true,
  16925. configurable: true
  16926. });
  16927. Scene.prototype.getActiveIndices = function () {
  16928. return this._activeIndices.current;
  16929. };
  16930. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16931. get: function () {
  16932. return this._activeIndices;
  16933. },
  16934. enumerable: true,
  16935. configurable: true
  16936. });
  16937. Scene.prototype.getActiveParticles = function () {
  16938. return this._activeParticles.current;
  16939. };
  16940. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16941. get: function () {
  16942. return this._activeParticles;
  16943. },
  16944. enumerable: true,
  16945. configurable: true
  16946. });
  16947. Scene.prototype.getActiveBones = function () {
  16948. return this._activeBones.current;
  16949. };
  16950. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16951. get: function () {
  16952. return this._activeBones;
  16953. },
  16954. enumerable: true,
  16955. configurable: true
  16956. });
  16957. // Stats
  16958. Scene.prototype.getLastFrameDuration = function () {
  16959. return this._lastFrameDuration.current;
  16960. };
  16961. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16962. get: function () {
  16963. return this._lastFrameDuration;
  16964. },
  16965. enumerable: true,
  16966. configurable: true
  16967. });
  16968. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16969. return this._evaluateActiveMeshesDuration.current;
  16970. };
  16971. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16972. get: function () {
  16973. return this._evaluateActiveMeshesDuration;
  16974. },
  16975. enumerable: true,
  16976. configurable: true
  16977. });
  16978. Scene.prototype.getActiveMeshes = function () {
  16979. return this._activeMeshes;
  16980. };
  16981. Scene.prototype.getRenderTargetsDuration = function () {
  16982. return this._renderTargetsDuration.current;
  16983. };
  16984. Scene.prototype.getRenderDuration = function () {
  16985. return this._renderDuration.current;
  16986. };
  16987. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16988. get: function () {
  16989. return this._renderDuration;
  16990. },
  16991. enumerable: true,
  16992. configurable: true
  16993. });
  16994. Scene.prototype.getParticlesDuration = function () {
  16995. return this._particlesDuration.current;
  16996. };
  16997. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16998. get: function () {
  16999. return this._particlesDuration;
  17000. },
  17001. enumerable: true,
  17002. configurable: true
  17003. });
  17004. Scene.prototype.getSpritesDuration = function () {
  17005. return this._spritesDuration.current;
  17006. };
  17007. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17008. get: function () {
  17009. return this._spritesDuration;
  17010. },
  17011. enumerable: true,
  17012. configurable: true
  17013. });
  17014. Scene.prototype.getAnimationRatio = function () {
  17015. return this._animationRatio;
  17016. };
  17017. Scene.prototype.getRenderId = function () {
  17018. return this._renderId;
  17019. };
  17020. Scene.prototype.incrementRenderId = function () {
  17021. this._renderId++;
  17022. };
  17023. Scene.prototype._updatePointerPosition = function (evt) {
  17024. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17025. this._pointerX = evt.clientX - canvasRect.left;
  17026. this._pointerY = evt.clientY - canvasRect.top;
  17027. this._unTranslatedPointerX = this._pointerX;
  17028. this._unTranslatedPointerY = this._pointerY;
  17029. };
  17030. Scene.prototype._createUbo = function () {
  17031. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17032. this._sceneUbo.addUniform("viewProjection", 16);
  17033. this._sceneUbo.addUniform("view", 16);
  17034. };
  17035. // Pointers handling
  17036. /**
  17037. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17038. * @param attachUp defines if you want to attach events to pointerup
  17039. * @param attachDown defines if you want to attach events to pointerdown
  17040. * @param attachMove defines if you want to attach events to pointermove
  17041. */
  17042. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17043. var _this = this;
  17044. if (attachUp === void 0) { attachUp = true; }
  17045. if (attachDown === void 0) { attachDown = true; }
  17046. if (attachMove === void 0) { attachMove = true; }
  17047. this._initActionManager = function (act, clickInfo) {
  17048. if (!_this._meshPickProceed) {
  17049. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17050. _this._currentPickResult = pickResult;
  17051. if (pickResult) {
  17052. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17053. }
  17054. _this._meshPickProceed = true;
  17055. }
  17056. return act;
  17057. };
  17058. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17059. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17060. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17061. btn !== _this._previousButtonPressed) {
  17062. _this._doubleClickOccured = false;
  17063. clickInfo.singleClick = true;
  17064. clickInfo.ignore = false;
  17065. cb(clickInfo, _this._currentPickResult);
  17066. }
  17067. };
  17068. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17069. var clickInfo = new ClickInfo();
  17070. _this._currentPickResult = null;
  17071. var act;
  17072. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  17073. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  17074. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17075. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17076. act = _this._initActionManager(act, clickInfo);
  17077. if (act)
  17078. checkPicking = act.hasPickTriggers;
  17079. }
  17080. if (checkPicking) {
  17081. var btn = evt.button;
  17082. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17083. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17084. if (!clickInfo.hasSwiped) {
  17085. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17086. if (!checkSingleClickImmediately) {
  17087. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  17088. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17089. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17090. act = _this._initActionManager(act, clickInfo);
  17091. if (act)
  17092. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17093. }
  17094. }
  17095. if (checkSingleClickImmediately) {
  17096. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17097. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17098. btn !== _this._previousButtonPressed) {
  17099. clickInfo.singleClick = true;
  17100. cb(clickInfo, _this._currentPickResult);
  17101. }
  17102. }
  17103. else {
  17104. // wait that no double click has been raised during the double click delay
  17105. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17106. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17107. }
  17108. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  17109. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17110. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17111. act = _this._initActionManager(act, clickInfo);
  17112. if (act)
  17113. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17114. }
  17115. if (checkDoubleClick) {
  17116. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17117. if (btn === _this._previousButtonPressed &&
  17118. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17119. !_this._doubleClickOccured) {
  17120. // pointer has not moved for 2 clicks, it's a double click
  17121. if (!clickInfo.hasSwiped &&
  17122. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17123. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17124. _this._previousStartingPointerTime = 0;
  17125. _this._doubleClickOccured = true;
  17126. clickInfo.doubleClick = true;
  17127. clickInfo.ignore = false;
  17128. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17129. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17130. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17131. cb(clickInfo, _this._currentPickResult);
  17132. }
  17133. else {
  17134. _this._doubleClickOccured = false;
  17135. _this._previousStartingPointerTime = _this._startingPointerTime;
  17136. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17137. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17138. _this._previousButtonPressed = btn;
  17139. _this._previousHasSwiped = clickInfo.hasSwiped;
  17140. if (Scene.ExclusiveDoubleClickMode) {
  17141. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17142. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17143. }
  17144. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17145. cb(clickInfo, _this._previousPickResult);
  17146. }
  17147. else {
  17148. cb(clickInfo, _this._currentPickResult);
  17149. }
  17150. }
  17151. }
  17152. else {
  17153. _this._doubleClickOccured = false;
  17154. _this._previousStartingPointerTime = _this._startingPointerTime;
  17155. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17156. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17157. _this._previousButtonPressed = btn;
  17158. _this._previousHasSwiped = clickInfo.hasSwiped;
  17159. }
  17160. }
  17161. }
  17162. }
  17163. clickInfo.ignore = true;
  17164. cb(clickInfo, _this._currentPickResult);
  17165. };
  17166. var spritePredicate = function (sprite) {
  17167. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17168. };
  17169. this._onPointerMove = function (evt) {
  17170. _this._updatePointerPosition(evt);
  17171. // PreObservable support
  17172. if (_this.onPrePointerObservable.hasObservers()) {
  17173. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17174. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17175. _this.onPrePointerObservable.notifyObservers(pi, type);
  17176. if (pi.skipOnPointerObservable) {
  17177. return;
  17178. }
  17179. }
  17180. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17181. return;
  17182. }
  17183. var canvas = _this._engine.getRenderingCanvas();
  17184. if (!_this.pointerMovePredicate) {
  17185. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17186. }
  17187. // Meshes
  17188. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17189. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17190. _this.setPointerOverSprite(null);
  17191. _this.setPointerOverMesh(pickResult.pickedMesh);
  17192. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17193. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17194. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17195. }
  17196. else {
  17197. canvas.style.cursor = _this.hoverCursor;
  17198. }
  17199. }
  17200. else {
  17201. canvas.style.cursor = _this.defaultCursor;
  17202. }
  17203. }
  17204. else {
  17205. _this.setPointerOverMesh(null);
  17206. // Sprites
  17207. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17208. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17209. _this.setPointerOverSprite(pickResult.pickedSprite);
  17210. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17211. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17212. }
  17213. else {
  17214. canvas.style.cursor = _this.hoverCursor;
  17215. }
  17216. }
  17217. else {
  17218. _this.setPointerOverSprite(null);
  17219. // Restore pointer
  17220. canvas.style.cursor = _this.defaultCursor;
  17221. }
  17222. }
  17223. if (_this.onPointerMove) {
  17224. _this.onPointerMove(evt, pickResult);
  17225. }
  17226. if (_this.onPointerObservable.hasObservers()) {
  17227. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17228. var pi = new PointerInfo(type, evt, pickResult);
  17229. _this.onPointerObservable.notifyObservers(pi, type);
  17230. }
  17231. };
  17232. this._onPointerDown = function (evt) {
  17233. _this._isButtonPressed = true;
  17234. _this._pickedDownMesh = null;
  17235. _this._meshPickProceed = false;
  17236. _this._updatePointerPosition(evt);
  17237. // PreObservable support
  17238. if (_this.onPrePointerObservable.hasObservers()) {
  17239. var type = PointerEventTypes.POINTERDOWN;
  17240. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17241. _this.onPrePointerObservable.notifyObservers(pi, type);
  17242. if (pi.skipOnPointerObservable) {
  17243. return;
  17244. }
  17245. }
  17246. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17247. return;
  17248. }
  17249. _this._startingPointerPosition.x = _this._pointerX;
  17250. _this._startingPointerPosition.y = _this._pointerY;
  17251. _this._startingPointerTime = new Date().getTime();
  17252. if (!_this.pointerDownPredicate) {
  17253. _this.pointerDownPredicate = function (mesh) {
  17254. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17255. };
  17256. }
  17257. // Meshes
  17258. _this._pickedDownMesh = null;
  17259. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17260. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17261. _this._pickedDownMesh = pickResult.pickedMesh;
  17262. var actionManager = pickResult.pickedMesh.actionManager;
  17263. if (actionManager) {
  17264. if (actionManager.hasPickTriggers) {
  17265. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17266. switch (evt.button) {
  17267. case 0:
  17268. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17269. break;
  17270. case 1:
  17271. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17272. break;
  17273. case 2:
  17274. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17275. break;
  17276. }
  17277. }
  17278. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17279. window.setTimeout((function () {
  17280. var _this = this;
  17281. 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);
  17282. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17283. if (this._isButtonPressed &&
  17284. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17285. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17286. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17287. this._startingPointerTime = 0;
  17288. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17289. }
  17290. }
  17291. }).bind(_this), Scene.LongPressDelay);
  17292. }
  17293. }
  17294. }
  17295. if (_this.onPointerDown) {
  17296. _this.onPointerDown(evt, pickResult);
  17297. }
  17298. if (_this.onPointerObservable.hasObservers()) {
  17299. var type = PointerEventTypes.POINTERDOWN;
  17300. var pi = new PointerInfo(type, evt, pickResult);
  17301. _this.onPointerObservable.notifyObservers(pi, type);
  17302. }
  17303. // Sprites
  17304. _this._pickedDownSprite = null;
  17305. if (_this.spriteManagers.length > 0) {
  17306. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17307. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17308. if (pickResult.pickedSprite.actionManager) {
  17309. _this._pickedDownSprite = pickResult.pickedSprite;
  17310. switch (evt.button) {
  17311. case 0:
  17312. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17313. break;
  17314. case 1:
  17315. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17316. break;
  17317. case 2:
  17318. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17319. break;
  17320. }
  17321. if (pickResult.pickedSprite.actionManager) {
  17322. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17323. }
  17324. }
  17325. }
  17326. }
  17327. };
  17328. this._onPointerUp = function (evt) {
  17329. _this._isButtonPressed = false;
  17330. _this._pickedUpMesh = null;
  17331. _this._meshPickProceed = false;
  17332. _this._updatePointerPosition(evt);
  17333. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17334. // PreObservable support
  17335. if (this.onPrePointerObservable.hasObservers()) {
  17336. if (!clickInfo.ignore) {
  17337. if (!clickInfo.hasSwiped) {
  17338. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17339. var type = PointerEventTypes.POINTERTAP;
  17340. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17341. this.onPrePointerObservable.notifyObservers(pi, type);
  17342. if (pi.skipOnPointerObservable) {
  17343. return;
  17344. }
  17345. }
  17346. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17347. var type = PointerEventTypes.POINTERDOUBLETAP;
  17348. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17349. this.onPrePointerObservable.notifyObservers(pi, type);
  17350. if (pi.skipOnPointerObservable) {
  17351. return;
  17352. }
  17353. }
  17354. }
  17355. }
  17356. else {
  17357. var type = PointerEventTypes.POINTERUP;
  17358. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17359. this.onPrePointerObservable.notifyObservers(pi, type);
  17360. if (pi.skipOnPointerObservable) {
  17361. return;
  17362. }
  17363. }
  17364. }
  17365. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17366. return;
  17367. }
  17368. if (!this.pointerUpPredicate) {
  17369. this.pointerUpPredicate = function (mesh) {
  17370. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17371. };
  17372. }
  17373. // Meshes
  17374. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17375. this._initActionManager(null, clickInfo);
  17376. }
  17377. if (!pickResult) {
  17378. pickResult = this._currentPickResult;
  17379. }
  17380. if (pickResult && pickResult && pickResult.pickedMesh) {
  17381. this._pickedUpMesh = pickResult.pickedMesh;
  17382. if (this._pickedDownMesh === this._pickedUpMesh) {
  17383. if (this.onPointerPick) {
  17384. this.onPointerPick(evt, pickResult);
  17385. }
  17386. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17387. var type = PointerEventTypes.POINTERPICK;
  17388. var pi = new PointerInfo(type, evt, pickResult);
  17389. this.onPointerObservable.notifyObservers(pi, type);
  17390. }
  17391. }
  17392. if (pickResult.pickedMesh.actionManager) {
  17393. if (clickInfo.ignore) {
  17394. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17395. }
  17396. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17397. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17398. }
  17399. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17400. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17401. }
  17402. }
  17403. }
  17404. if (this._pickedDownMesh &&
  17405. this._pickedDownMesh.actionManager &&
  17406. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17407. this._pickedDownMesh !== this._pickedUpMesh) {
  17408. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17409. }
  17410. if (this.onPointerUp) {
  17411. this.onPointerUp(evt, pickResult);
  17412. }
  17413. if (this.onPointerObservable.hasObservers()) {
  17414. if (!clickInfo.ignore) {
  17415. if (!clickInfo.hasSwiped) {
  17416. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17417. var type = PointerEventTypes.POINTERTAP;
  17418. var pi = new PointerInfo(type, evt, pickResult);
  17419. this.onPointerObservable.notifyObservers(pi, type);
  17420. }
  17421. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17422. var type = PointerEventTypes.POINTERDOUBLETAP;
  17423. var pi = new PointerInfo(type, evt, pickResult);
  17424. this.onPointerObservable.notifyObservers(pi, type);
  17425. }
  17426. }
  17427. }
  17428. else {
  17429. var type = PointerEventTypes.POINTERUP;
  17430. var pi = new PointerInfo(type, evt, pickResult);
  17431. this.onPointerObservable.notifyObservers(pi, type);
  17432. }
  17433. }
  17434. // Sprites
  17435. if (this.spriteManagers.length > 0) {
  17436. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  17437. if (pickResult.hit && pickResult.pickedSprite) {
  17438. if (pickResult.pickedSprite.actionManager) {
  17439. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17440. if (pickResult.pickedSprite.actionManager) {
  17441. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17442. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17443. }
  17444. }
  17445. }
  17446. }
  17447. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17448. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17449. }
  17450. }
  17451. this._previousPickResult = this._currentPickResult;
  17452. }).bind(_this));
  17453. };
  17454. this._onKeyDown = function (evt) {
  17455. if (_this.actionManager) {
  17456. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17457. }
  17458. };
  17459. this._onKeyUp = function (evt) {
  17460. if (_this.actionManager) {
  17461. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17462. }
  17463. };
  17464. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17465. var canvas = this._engine.getRenderingCanvas();
  17466. if (attachMove) {
  17467. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17468. // Wheel
  17469. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17470. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17471. }
  17472. if (attachDown) {
  17473. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17474. }
  17475. if (attachUp) {
  17476. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17477. }
  17478. canvas.tabIndex = 1;
  17479. canvas.addEventListener("keydown", this._onKeyDown, false);
  17480. canvas.addEventListener("keyup", this._onKeyUp, false);
  17481. };
  17482. Scene.prototype.detachControl = function () {
  17483. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17484. var canvas = this._engine.getRenderingCanvas();
  17485. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17486. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17487. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17488. // Wheel
  17489. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17490. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17491. canvas.removeEventListener("keydown", this._onKeyDown);
  17492. canvas.removeEventListener("keyup", this._onKeyUp);
  17493. };
  17494. // Ready
  17495. Scene.prototype.isReady = function () {
  17496. if (this._pendingData.length > 0) {
  17497. return false;
  17498. }
  17499. var index;
  17500. // Geometries
  17501. for (index = 0; index < this._geometries.length; index++) {
  17502. var geometry = this._geometries[index];
  17503. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17504. return false;
  17505. }
  17506. }
  17507. // Meshes
  17508. for (index = 0; index < this.meshes.length; index++) {
  17509. var mesh = this.meshes[index];
  17510. if (!mesh.isEnabled()) {
  17511. continue;
  17512. }
  17513. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17514. continue;
  17515. }
  17516. if (!mesh.isReady()) {
  17517. return false;
  17518. }
  17519. var mat = mesh.material;
  17520. if (mat) {
  17521. if (!mat.isReady(mesh)) {
  17522. return false;
  17523. }
  17524. }
  17525. }
  17526. return true;
  17527. };
  17528. Scene.prototype.resetCachedMaterial = function () {
  17529. this._cachedMaterial = null;
  17530. this._cachedEffect = null;
  17531. this._cachedVisibility = null;
  17532. };
  17533. Scene.prototype.registerBeforeRender = function (func) {
  17534. this.onBeforeRenderObservable.add(func);
  17535. };
  17536. Scene.prototype.unregisterBeforeRender = function (func) {
  17537. this.onBeforeRenderObservable.removeCallback(func);
  17538. };
  17539. Scene.prototype.registerAfterRender = function (func) {
  17540. this.onAfterRenderObservable.add(func);
  17541. };
  17542. Scene.prototype.unregisterAfterRender = function (func) {
  17543. this.onAfterRenderObservable.removeCallback(func);
  17544. };
  17545. Scene.prototype._addPendingData = function (data) {
  17546. this._pendingData.push(data);
  17547. };
  17548. Scene.prototype._removePendingData = function (data) {
  17549. var index = this._pendingData.indexOf(data);
  17550. if (index !== -1) {
  17551. this._pendingData.splice(index, 1);
  17552. }
  17553. };
  17554. Scene.prototype.getWaitingItemsCount = function () {
  17555. return this._pendingData.length;
  17556. };
  17557. /**
  17558. * Registers a function to be executed when the scene is ready.
  17559. * @param {Function} func - the function to be executed.
  17560. */
  17561. Scene.prototype.executeWhenReady = function (func) {
  17562. var _this = this;
  17563. this.onReadyObservable.add(func);
  17564. if (this._executeWhenReadyTimeoutId !== -1) {
  17565. return;
  17566. }
  17567. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17568. _this._checkIsReady();
  17569. }, 150);
  17570. };
  17571. Scene.prototype._checkIsReady = function () {
  17572. var _this = this;
  17573. if (this.isReady()) {
  17574. this.onReadyObservable.notifyObservers(this);
  17575. this.onReadyObservable.clear();
  17576. this._executeWhenReadyTimeoutId = -1;
  17577. return;
  17578. }
  17579. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17580. _this._checkIsReady();
  17581. }, 150);
  17582. };
  17583. // Animations
  17584. /**
  17585. * Will start the animation sequence of a given target
  17586. * @param target - the target
  17587. * @param {number} from - from which frame should animation start
  17588. * @param {number} to - till which frame should animation run.
  17589. * @param {boolean} [loop] - should the animation loop
  17590. * @param {number} [speedRatio] - the speed in which to run the animation
  17591. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17592. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17593. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17594. * See BABYLON.Animatable
  17595. */
  17596. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17597. if (speedRatio === void 0) { speedRatio = 1.0; }
  17598. if (from > to && speedRatio > 0) {
  17599. speedRatio *= -1;
  17600. }
  17601. this.stopAnimation(target);
  17602. if (!animatable) {
  17603. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17604. }
  17605. // Local animations
  17606. if (target.animations) {
  17607. animatable.appendAnimations(target, target.animations);
  17608. }
  17609. // Children animations
  17610. if (target.getAnimatables) {
  17611. var animatables = target.getAnimatables();
  17612. for (var index = 0; index < animatables.length; index++) {
  17613. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17614. }
  17615. }
  17616. animatable.reset();
  17617. return animatable;
  17618. };
  17619. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17620. if (speedRatio === undefined) {
  17621. speedRatio = 1.0;
  17622. }
  17623. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17624. return animatable;
  17625. };
  17626. Scene.prototype.getAnimatableByTarget = function (target) {
  17627. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17628. if (this._activeAnimatables[index].target === target) {
  17629. return this._activeAnimatables[index];
  17630. }
  17631. }
  17632. return null;
  17633. };
  17634. Object.defineProperty(Scene.prototype, "Animatables", {
  17635. get: function () {
  17636. return this._activeAnimatables;
  17637. },
  17638. enumerable: true,
  17639. configurable: true
  17640. });
  17641. /**
  17642. * Will stop the animation of the given target
  17643. * @param target - the target
  17644. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17645. * @see beginAnimation
  17646. */
  17647. Scene.prototype.stopAnimation = function (target, animationName) {
  17648. var animatable = this.getAnimatableByTarget(target);
  17649. if (animatable) {
  17650. animatable.stop(animationName);
  17651. }
  17652. };
  17653. Scene.prototype._animate = function () {
  17654. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17655. return;
  17656. }
  17657. // Getting time
  17658. var now = BABYLON.Tools.Now;
  17659. if (!this._animationTimeLast) {
  17660. if (this._pendingData.length > 0) {
  17661. return;
  17662. }
  17663. this._animationTimeLast = now;
  17664. }
  17665. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17666. this._animationTime += deltaTime;
  17667. this._animationTimeLast = now;
  17668. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17669. this._activeAnimatables[index]._animate(this._animationTime);
  17670. }
  17671. };
  17672. // Matrix
  17673. Scene.prototype.getViewMatrix = function () {
  17674. return this._viewMatrix;
  17675. };
  17676. Scene.prototype.getProjectionMatrix = function () {
  17677. return this._projectionMatrix;
  17678. };
  17679. Scene.prototype.getTransformMatrix = function () {
  17680. return this._transformMatrix;
  17681. };
  17682. Scene.prototype.setTransformMatrix = function (view, projection) {
  17683. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17684. return;
  17685. }
  17686. this._viewUpdateFlag = view.updateFlag;
  17687. this._projectionUpdateFlag = projection.updateFlag;
  17688. this._viewMatrix = view;
  17689. this._projectionMatrix = projection;
  17690. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17691. // Update frustum
  17692. if (!this._frustumPlanes) {
  17693. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17694. }
  17695. else {
  17696. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17697. }
  17698. if (this._sceneUbo.useUbo) {
  17699. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17700. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17701. this._sceneUbo.update();
  17702. }
  17703. };
  17704. Scene.prototype.getSceneUniformBuffer = function () {
  17705. return this._sceneUbo;
  17706. };
  17707. // Methods
  17708. Scene.prototype.getUniqueId = function () {
  17709. var result = this._uniqueIdCounter;
  17710. this._uniqueIdCounter++;
  17711. return result;
  17712. };
  17713. Scene.prototype.addMesh = function (newMesh) {
  17714. newMesh.uniqueId = this.getUniqueId();
  17715. var position = this.meshes.push(newMesh);
  17716. //notify the collision coordinator
  17717. if (this.collisionCoordinator) {
  17718. this.collisionCoordinator.onMeshAdded(newMesh);
  17719. }
  17720. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17721. };
  17722. Scene.prototype.removeMesh = function (toRemove) {
  17723. var index = this.meshes.indexOf(toRemove);
  17724. if (index !== -1) {
  17725. // Remove from the scene if mesh found
  17726. this.meshes.splice(index, 1);
  17727. }
  17728. //notify the collision coordinator
  17729. if (this.collisionCoordinator) {
  17730. this.collisionCoordinator.onMeshRemoved(toRemove);
  17731. }
  17732. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17733. return index;
  17734. };
  17735. Scene.prototype.removeSkeleton = function (toRemove) {
  17736. var index = this.skeletons.indexOf(toRemove);
  17737. if (index !== -1) {
  17738. // Remove from the scene if found
  17739. this.skeletons.splice(index, 1);
  17740. }
  17741. return index;
  17742. };
  17743. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17744. var index = this.morphTargetManagers.indexOf(toRemove);
  17745. if (index !== -1) {
  17746. // Remove from the scene if found
  17747. this.morphTargetManagers.splice(index, 1);
  17748. }
  17749. return index;
  17750. };
  17751. Scene.prototype.removeLight = function (toRemove) {
  17752. var index = this.lights.indexOf(toRemove);
  17753. if (index !== -1) {
  17754. // Remove from the scene if mesh found
  17755. this.lights.splice(index, 1);
  17756. this.sortLightsByPriority();
  17757. }
  17758. this.onLightRemovedObservable.notifyObservers(toRemove);
  17759. return index;
  17760. };
  17761. Scene.prototype.removeCamera = function (toRemove) {
  17762. var index = this.cameras.indexOf(toRemove);
  17763. if (index !== -1) {
  17764. // Remove from the scene if mesh found
  17765. this.cameras.splice(index, 1);
  17766. }
  17767. // Remove from activeCameras
  17768. var index2 = this.activeCameras.indexOf(toRemove);
  17769. if (index2 !== -1) {
  17770. // Remove from the scene if mesh found
  17771. this.activeCameras.splice(index2, 1);
  17772. }
  17773. // Reset the activeCamera
  17774. if (this.activeCamera === toRemove) {
  17775. if (this.cameras.length > 0) {
  17776. this.activeCamera = this.cameras[0];
  17777. }
  17778. else {
  17779. this.activeCamera = null;
  17780. }
  17781. }
  17782. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17783. return index;
  17784. };
  17785. Scene.prototype.addLight = function (newLight) {
  17786. newLight.uniqueId = this.getUniqueId();
  17787. this.lights.push(newLight);
  17788. this.sortLightsByPriority();
  17789. this.onNewLightAddedObservable.notifyObservers(newLight);
  17790. };
  17791. Scene.prototype.sortLightsByPriority = function () {
  17792. if (this.requireLightSorting) {
  17793. this.lights.sort(BABYLON.Light.compareLightsPriority);
  17794. }
  17795. };
  17796. Scene.prototype.addCamera = function (newCamera) {
  17797. newCamera.uniqueId = this.getUniqueId();
  17798. var position = this.cameras.push(newCamera);
  17799. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17800. };
  17801. /**
  17802. * Switch active camera
  17803. * @param {Camera} newCamera - new active camera
  17804. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17805. */
  17806. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17807. if (attachControl === void 0) { attachControl = true; }
  17808. var canvas = this._engine.getRenderingCanvas();
  17809. this.activeCamera.detachControl(canvas);
  17810. this.activeCamera = newCamera;
  17811. if (attachControl) {
  17812. newCamera.attachControl(canvas);
  17813. }
  17814. };
  17815. /**
  17816. * sets the active camera of the scene using its ID
  17817. * @param {string} id - the camera's ID
  17818. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17819. * @see activeCamera
  17820. */
  17821. Scene.prototype.setActiveCameraByID = function (id) {
  17822. var camera = this.getCameraByID(id);
  17823. if (camera) {
  17824. this.activeCamera = camera;
  17825. return camera;
  17826. }
  17827. return null;
  17828. };
  17829. /**
  17830. * sets the active camera of the scene using its name
  17831. * @param {string} name - the camera's name
  17832. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17833. * @see activeCamera
  17834. */
  17835. Scene.prototype.setActiveCameraByName = function (name) {
  17836. var camera = this.getCameraByName(name);
  17837. if (camera) {
  17838. this.activeCamera = camera;
  17839. return camera;
  17840. }
  17841. return null;
  17842. };
  17843. /**
  17844. * get a material using its id
  17845. * @param {string} the material's ID
  17846. * @return {BABYLON.Material|null} the material or null if none found.
  17847. */
  17848. Scene.prototype.getMaterialByID = function (id) {
  17849. for (var index = 0; index < this.materials.length; index++) {
  17850. if (this.materials[index].id === id) {
  17851. return this.materials[index];
  17852. }
  17853. }
  17854. return null;
  17855. };
  17856. /**
  17857. * get a material using its name
  17858. * @param {string} the material's name
  17859. * @return {BABYLON.Material|null} the material or null if none found.
  17860. */
  17861. Scene.prototype.getMaterialByName = function (name) {
  17862. for (var index = 0; index < this.materials.length; index++) {
  17863. if (this.materials[index].name === name) {
  17864. return this.materials[index];
  17865. }
  17866. }
  17867. return null;
  17868. };
  17869. Scene.prototype.getLensFlareSystemByName = function (name) {
  17870. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17871. if (this.lensFlareSystems[index].name === name) {
  17872. return this.lensFlareSystems[index];
  17873. }
  17874. }
  17875. return null;
  17876. };
  17877. Scene.prototype.getLensFlareSystemByID = function (id) {
  17878. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17879. if (this.lensFlareSystems[index].id === id) {
  17880. return this.lensFlareSystems[index];
  17881. }
  17882. }
  17883. return null;
  17884. };
  17885. Scene.prototype.getCameraByID = function (id) {
  17886. for (var index = 0; index < this.cameras.length; index++) {
  17887. if (this.cameras[index].id === id) {
  17888. return this.cameras[index];
  17889. }
  17890. }
  17891. return null;
  17892. };
  17893. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17894. for (var index = 0; index < this.cameras.length; index++) {
  17895. if (this.cameras[index].uniqueId === uniqueId) {
  17896. return this.cameras[index];
  17897. }
  17898. }
  17899. return null;
  17900. };
  17901. /**
  17902. * get a camera using its name
  17903. * @param {string} the camera's name
  17904. * @return {BABYLON.Camera|null} the camera or null if none found.
  17905. */
  17906. Scene.prototype.getCameraByName = function (name) {
  17907. for (var index = 0; index < this.cameras.length; index++) {
  17908. if (this.cameras[index].name === name) {
  17909. return this.cameras[index];
  17910. }
  17911. }
  17912. return null;
  17913. };
  17914. /**
  17915. * get a bone using its id
  17916. * @param {string} the bone's id
  17917. * @return {BABYLON.Bone|null} the bone or null if not found
  17918. */
  17919. Scene.prototype.getBoneByID = function (id) {
  17920. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17921. var skeleton = this.skeletons[skeletonIndex];
  17922. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17923. if (skeleton.bones[boneIndex].id === id) {
  17924. return skeleton.bones[boneIndex];
  17925. }
  17926. }
  17927. }
  17928. return null;
  17929. };
  17930. /**
  17931. * get a bone using its id
  17932. * @param {string} the bone's name
  17933. * @return {BABYLON.Bone|null} the bone or null if not found
  17934. */
  17935. Scene.prototype.getBoneByName = function (name) {
  17936. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17937. var skeleton = this.skeletons[skeletonIndex];
  17938. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17939. if (skeleton.bones[boneIndex].name === name) {
  17940. return skeleton.bones[boneIndex];
  17941. }
  17942. }
  17943. }
  17944. return null;
  17945. };
  17946. /**
  17947. * get a light node using its name
  17948. * @param {string} the light's name
  17949. * @return {BABYLON.Light|null} the light or null if none found.
  17950. */
  17951. Scene.prototype.getLightByName = function (name) {
  17952. for (var index = 0; index < this.lights.length; index++) {
  17953. if (this.lights[index].name === name) {
  17954. return this.lights[index];
  17955. }
  17956. }
  17957. return null;
  17958. };
  17959. /**
  17960. * get a light node using its ID
  17961. * @param {string} the light's id
  17962. * @return {BABYLON.Light|null} the light or null if none found.
  17963. */
  17964. Scene.prototype.getLightByID = function (id) {
  17965. for (var index = 0; index < this.lights.length; index++) {
  17966. if (this.lights[index].id === id) {
  17967. return this.lights[index];
  17968. }
  17969. }
  17970. return null;
  17971. };
  17972. /**
  17973. * get a light node using its scene-generated unique ID
  17974. * @param {number} the light's unique id
  17975. * @return {BABYLON.Light|null} the light or null if none found.
  17976. */
  17977. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17978. for (var index = 0; index < this.lights.length; index++) {
  17979. if (this.lights[index].uniqueId === uniqueId) {
  17980. return this.lights[index];
  17981. }
  17982. }
  17983. return null;
  17984. };
  17985. /**
  17986. * get a particle system by id
  17987. * @param id {number} the particle system id
  17988. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  17989. */
  17990. Scene.prototype.getParticleSystemByID = function (id) {
  17991. for (var index = 0; index < this.particleSystems.length; index++) {
  17992. if (this.particleSystems[index].id === id) {
  17993. return this.particleSystems[index];
  17994. }
  17995. }
  17996. return null;
  17997. };
  17998. /**
  17999. * get a geometry using its ID
  18000. * @param {string} the geometry's id
  18001. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18002. */
  18003. Scene.prototype.getGeometryByID = function (id) {
  18004. for (var index = 0; index < this._geometries.length; index++) {
  18005. if (this._geometries[index].id === id) {
  18006. return this._geometries[index];
  18007. }
  18008. }
  18009. return null;
  18010. };
  18011. /**
  18012. * add a new geometry to this scene.
  18013. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18014. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18015. * @return {boolean} was the geometry added or not
  18016. */
  18017. Scene.prototype.pushGeometry = function (geometry, force) {
  18018. if (!force && this.getGeometryByID(geometry.id)) {
  18019. return false;
  18020. }
  18021. this._geometries.push(geometry);
  18022. //notify the collision coordinator
  18023. if (this.collisionCoordinator) {
  18024. this.collisionCoordinator.onGeometryAdded(geometry);
  18025. }
  18026. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18027. return true;
  18028. };
  18029. /**
  18030. * Removes an existing geometry
  18031. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18032. * @return {boolean} was the geometry removed or not
  18033. */
  18034. Scene.prototype.removeGeometry = function (geometry) {
  18035. var index = this._geometries.indexOf(geometry);
  18036. if (index > -1) {
  18037. this._geometries.splice(index, 1);
  18038. //notify the collision coordinator
  18039. if (this.collisionCoordinator) {
  18040. this.collisionCoordinator.onGeometryDeleted(geometry);
  18041. }
  18042. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18043. return true;
  18044. }
  18045. return false;
  18046. };
  18047. Scene.prototype.getGeometries = function () {
  18048. return this._geometries;
  18049. };
  18050. /**
  18051. * Get the first 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.getMeshByID = function (id) {
  18056. for (var index = 0; index < this.meshes.length; index++) {
  18057. if (this.meshes[index].id === id) {
  18058. return this.meshes[index];
  18059. }
  18060. }
  18061. return null;
  18062. };
  18063. Scene.prototype.getMeshesByID = function (id) {
  18064. return this.meshes.filter(function (m) {
  18065. return m.id === id;
  18066. });
  18067. };
  18068. /**
  18069. * Get a mesh with its auto-generated unique id
  18070. * @param {number} uniqueId - the unique id to search for
  18071. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18072. */
  18073. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18074. for (var index = 0; index < this.meshes.length; index++) {
  18075. if (this.meshes[index].uniqueId === uniqueId) {
  18076. return this.meshes[index];
  18077. }
  18078. }
  18079. return null;
  18080. };
  18081. /**
  18082. * Get a the last added mesh found of a given ID
  18083. * @param {string} id - the id to search for
  18084. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18085. */
  18086. Scene.prototype.getLastMeshByID = function (id) {
  18087. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18088. if (this.meshes[index].id === id) {
  18089. return this.meshes[index];
  18090. }
  18091. }
  18092. return null;
  18093. };
  18094. /**
  18095. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18096. * @param {string} id - the id to search for
  18097. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18098. */
  18099. Scene.prototype.getLastEntryByID = function (id) {
  18100. var index;
  18101. for (index = this.meshes.length - 1; index >= 0; index--) {
  18102. if (this.meshes[index].id === id) {
  18103. return this.meshes[index];
  18104. }
  18105. }
  18106. for (index = this.cameras.length - 1; index >= 0; index--) {
  18107. if (this.cameras[index].id === id) {
  18108. return this.cameras[index];
  18109. }
  18110. }
  18111. for (index = this.lights.length - 1; index >= 0; index--) {
  18112. if (this.lights[index].id === id) {
  18113. return this.lights[index];
  18114. }
  18115. }
  18116. return null;
  18117. };
  18118. Scene.prototype.getNodeByID = function (id) {
  18119. var mesh = this.getMeshByID(id);
  18120. if (mesh) {
  18121. return mesh;
  18122. }
  18123. var light = this.getLightByID(id);
  18124. if (light) {
  18125. return light;
  18126. }
  18127. var camera = this.getCameraByID(id);
  18128. if (camera) {
  18129. return camera;
  18130. }
  18131. var bone = this.getBoneByID(id);
  18132. return bone;
  18133. };
  18134. Scene.prototype.getNodeByName = function (name) {
  18135. var mesh = this.getMeshByName(name);
  18136. if (mesh) {
  18137. return mesh;
  18138. }
  18139. var light = this.getLightByName(name);
  18140. if (light) {
  18141. return light;
  18142. }
  18143. var camera = this.getCameraByName(name);
  18144. if (camera) {
  18145. return camera;
  18146. }
  18147. var bone = this.getBoneByName(name);
  18148. return bone;
  18149. };
  18150. Scene.prototype.getMeshByName = function (name) {
  18151. for (var index = 0; index < this.meshes.length; index++) {
  18152. if (this.meshes[index].name === name) {
  18153. return this.meshes[index];
  18154. }
  18155. }
  18156. return null;
  18157. };
  18158. Scene.prototype.getSoundByName = function (name) {
  18159. var index;
  18160. if (BABYLON.AudioEngine) {
  18161. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18162. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18163. return this.mainSoundTrack.soundCollection[index];
  18164. }
  18165. }
  18166. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18167. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18168. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18169. return this.soundTracks[sdIndex].soundCollection[index];
  18170. }
  18171. }
  18172. }
  18173. }
  18174. return null;
  18175. };
  18176. Scene.prototype.getLastSkeletonByID = function (id) {
  18177. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18178. if (this.skeletons[index].id === id) {
  18179. return this.skeletons[index];
  18180. }
  18181. }
  18182. return null;
  18183. };
  18184. Scene.prototype.getSkeletonById = function (id) {
  18185. for (var index = 0; index < this.skeletons.length; index++) {
  18186. if (this.skeletons[index].id === id) {
  18187. return this.skeletons[index];
  18188. }
  18189. }
  18190. return null;
  18191. };
  18192. Scene.prototype.getSkeletonByName = function (name) {
  18193. for (var index = 0; index < this.skeletons.length; index++) {
  18194. if (this.skeletons[index].name === name) {
  18195. return this.skeletons[index];
  18196. }
  18197. }
  18198. return null;
  18199. };
  18200. Scene.prototype.getMorphTargetManagerById = function (id) {
  18201. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18202. if (this.morphTargetManagers[index].uniqueId === id) {
  18203. return this.morphTargetManagers[index];
  18204. }
  18205. }
  18206. return null;
  18207. };
  18208. Scene.prototype.isActiveMesh = function (mesh) {
  18209. return (this._activeMeshes.indexOf(mesh) !== -1);
  18210. };
  18211. /**
  18212. * Return a the first highlight layer of the scene with a given name.
  18213. * @param name The name of the highlight layer to look for.
  18214. * @return The highlight layer if found otherwise null.
  18215. */
  18216. Scene.prototype.getHighlightLayerByName = function (name) {
  18217. for (var index = 0; index < this.highlightLayers.length; index++) {
  18218. if (this.highlightLayers[index].name === name) {
  18219. return this.highlightLayers[index];
  18220. }
  18221. }
  18222. return null;
  18223. };
  18224. Object.defineProperty(Scene.prototype, "uid", {
  18225. /**
  18226. * Return a unique id as a string which can serve as an identifier for the scene
  18227. */
  18228. get: function () {
  18229. if (!this._uid) {
  18230. this._uid = BABYLON.Tools.RandomId();
  18231. }
  18232. return this._uid;
  18233. },
  18234. enumerable: true,
  18235. configurable: true
  18236. });
  18237. /**
  18238. * Add an externaly attached data from its key.
  18239. * This method call will fail and return false, if such key already exists.
  18240. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18241. * @param key the unique key that identifies the data
  18242. * @param data the data object to associate to the key for this Engine instance
  18243. * @return true if no such key were already present and the data was added successfully, false otherwise
  18244. */
  18245. Scene.prototype.addExternalData = function (key, data) {
  18246. if (!this._externalData) {
  18247. this._externalData = new BABYLON.StringDictionary();
  18248. }
  18249. return this._externalData.add(key, data);
  18250. };
  18251. /**
  18252. * Get an externaly attached data from its key
  18253. * @param key the unique key that identifies the data
  18254. * @return the associated data, if present (can be null), or undefined if not present
  18255. */
  18256. Scene.prototype.getExternalData = function (key) {
  18257. if (!this._externalData) {
  18258. return null;
  18259. }
  18260. return this._externalData.get(key);
  18261. };
  18262. /**
  18263. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18264. * @param key the unique key that identifies the data
  18265. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18266. * @return the associated data, can be null if the factory returned null.
  18267. */
  18268. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18269. if (!this._externalData) {
  18270. this._externalData = new BABYLON.StringDictionary();
  18271. }
  18272. return this._externalData.getOrAddWithFactory(key, factory);
  18273. };
  18274. /**
  18275. * Remove an externaly attached data from the Engine instance
  18276. * @param key the unique key that identifies the data
  18277. * @return true if the data was successfully removed, false if it doesn't exist
  18278. */
  18279. Scene.prototype.removeExternalData = function (key) {
  18280. return this._externalData.remove(key);
  18281. };
  18282. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18283. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18284. var material = subMesh.getMaterial();
  18285. if (mesh.showSubMeshesBoundingBox) {
  18286. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18287. }
  18288. if (material) {
  18289. // Render targets
  18290. if (material.getRenderTargetTextures) {
  18291. if (this._processedMaterials.indexOf(material) === -1) {
  18292. this._processedMaterials.push(material);
  18293. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18294. }
  18295. }
  18296. // Dispatch
  18297. this._activeIndices.addCount(subMesh.indexCount, false);
  18298. this._renderingManager.dispatch(subMesh);
  18299. }
  18300. }
  18301. };
  18302. Scene.prototype._isInIntermediateRendering = function () {
  18303. return this._intermediateRendering;
  18304. };
  18305. Scene.prototype._evaluateActiveMeshes = function () {
  18306. this.activeCamera._activeMeshes.reset();
  18307. this._activeMeshes.reset();
  18308. this._renderingManager.reset();
  18309. this._processedMaterials.reset();
  18310. this._activeParticleSystems.reset();
  18311. this._activeSkeletons.reset();
  18312. this._softwareSkinnedMeshes.reset();
  18313. if (this._boundingBoxRenderer) {
  18314. this._boundingBoxRenderer.reset();
  18315. }
  18316. // Meshes
  18317. var meshes;
  18318. var len;
  18319. if (this._selectionOctree) {
  18320. var selection = this._selectionOctree.select(this._frustumPlanes);
  18321. meshes = selection.data;
  18322. len = selection.length;
  18323. }
  18324. else {
  18325. len = this.meshes.length;
  18326. meshes = this.meshes;
  18327. }
  18328. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18329. var mesh = meshes[meshIndex];
  18330. if (mesh.isBlocked) {
  18331. continue;
  18332. }
  18333. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18334. if (!mesh.isReady() || !mesh.isEnabled()) {
  18335. continue;
  18336. }
  18337. mesh.computeWorldMatrix();
  18338. // Intersections
  18339. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18340. this._meshesForIntersections.pushNoDuplicate(mesh);
  18341. }
  18342. // Switch to current LOD
  18343. var meshLOD = mesh.getLOD(this.activeCamera);
  18344. if (!meshLOD) {
  18345. continue;
  18346. }
  18347. mesh._preActivate();
  18348. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18349. this._activeMeshes.push(mesh);
  18350. this.activeCamera._activeMeshes.push(mesh);
  18351. mesh._activate(this._renderId);
  18352. if (meshLOD !== mesh) {
  18353. meshLOD._activate(this._renderId);
  18354. }
  18355. this._activeMesh(mesh, meshLOD);
  18356. }
  18357. }
  18358. // Particle systems
  18359. this._particlesDuration.beginMonitoring();
  18360. var beforeParticlesDate = BABYLON.Tools.Now;
  18361. if (this.particlesEnabled) {
  18362. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18363. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18364. var particleSystem = this.particleSystems[particleIndex];
  18365. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18366. continue;
  18367. }
  18368. var emitter = particleSystem.emitter;
  18369. if (!emitter.position || emitter.isEnabled()) {
  18370. this._activeParticleSystems.push(particleSystem);
  18371. particleSystem.animate();
  18372. this._renderingManager.dispatchParticles(particleSystem);
  18373. }
  18374. }
  18375. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18376. }
  18377. this._particlesDuration.endMonitoring(false);
  18378. };
  18379. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18380. if (mesh.skeleton && this.skeletonsEnabled) {
  18381. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18382. mesh.skeleton.prepare();
  18383. }
  18384. if (!mesh.computeBonesUsingShaders) {
  18385. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18386. }
  18387. }
  18388. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18389. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18390. }
  18391. if (mesh && mesh.subMeshes) {
  18392. // Submeshes Octrees
  18393. var len;
  18394. var subMeshes;
  18395. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18396. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18397. len = intersections.length;
  18398. subMeshes = intersections.data;
  18399. }
  18400. else {
  18401. subMeshes = mesh.subMeshes;
  18402. len = subMeshes.length;
  18403. }
  18404. for (var subIndex = 0; subIndex < len; subIndex++) {
  18405. var subMesh = subMeshes[subIndex];
  18406. this._evaluateSubMesh(subMesh, mesh);
  18407. }
  18408. }
  18409. };
  18410. Scene.prototype.updateTransformMatrix = function (force) {
  18411. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18412. };
  18413. Scene.prototype._renderForCamera = function (camera) {
  18414. var engine = this._engine;
  18415. var startTime = BABYLON.Tools.Now;
  18416. this.activeCamera = camera;
  18417. if (!this.activeCamera)
  18418. throw new Error("Active camera not set");
  18419. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18420. // Viewport
  18421. engine.setViewport(this.activeCamera.viewport);
  18422. // Camera
  18423. this.resetCachedMaterial();
  18424. this._renderId++;
  18425. this.updateTransformMatrix();
  18426. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18427. // Meshes
  18428. this._evaluateActiveMeshesDuration.beginMonitoring();
  18429. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18430. this._evaluateActiveMeshes();
  18431. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18432. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18433. // Software skinning
  18434. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18435. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18436. mesh.applySkeleton(mesh.skeleton);
  18437. }
  18438. // Render targets
  18439. this._renderTargetsDuration.beginMonitoring();
  18440. var needsRestoreFrameBuffer = false;
  18441. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18442. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18443. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18444. }
  18445. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18446. this._intermediateRendering = true;
  18447. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18448. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18449. var renderTarget = this._renderTargets.data[renderIndex];
  18450. if (renderTarget._shouldRender()) {
  18451. this._renderId++;
  18452. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18453. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18454. }
  18455. }
  18456. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18457. this._intermediateRendering = false;
  18458. this._renderId++;
  18459. needsRestoreFrameBuffer = true; // Restore back buffer
  18460. }
  18461. // Render HighlightLayer Texture
  18462. var stencilState = this._engine.getStencilBuffer();
  18463. var renderhighlights = false;
  18464. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18465. this._intermediateRendering = true;
  18466. for (var i = 0; i < this.highlightLayers.length; i++) {
  18467. var highlightLayer = this.highlightLayers[i];
  18468. if (highlightLayer.shouldRender() &&
  18469. (!highlightLayer.camera ||
  18470. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18471. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18472. renderhighlights = true;
  18473. var renderTarget = highlightLayer._mainTexture;
  18474. if (renderTarget._shouldRender()) {
  18475. this._renderId++;
  18476. renderTarget.render(false, false);
  18477. needsRestoreFrameBuffer = true;
  18478. }
  18479. }
  18480. }
  18481. this._intermediateRendering = false;
  18482. this._renderId++;
  18483. }
  18484. if (needsRestoreFrameBuffer) {
  18485. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18486. }
  18487. this._renderTargetsDuration.endMonitoring(false);
  18488. // Prepare Frame
  18489. this.postProcessManager._prepareFrame();
  18490. this._renderDuration.beginMonitoring();
  18491. // Backgrounds
  18492. var layerIndex;
  18493. var layer;
  18494. if (this.layers.length) {
  18495. engine.setDepthBuffer(false);
  18496. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18497. layer = this.layers[layerIndex];
  18498. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18499. layer.render();
  18500. }
  18501. }
  18502. engine.setDepthBuffer(true);
  18503. }
  18504. // Render
  18505. BABYLON.Tools.StartPerformanceCounter("Main render");
  18506. // Activate HighlightLayer stencil
  18507. if (renderhighlights) {
  18508. this._engine.setStencilBuffer(true);
  18509. }
  18510. this._renderingManager.render(null, null, true, true);
  18511. // Restore HighlightLayer stencil
  18512. if (renderhighlights) {
  18513. this._engine.setStencilBuffer(stencilState);
  18514. }
  18515. BABYLON.Tools.EndPerformanceCounter("Main render");
  18516. // Bounding boxes
  18517. if (this._boundingBoxRenderer) {
  18518. this._boundingBoxRenderer.render();
  18519. }
  18520. // Lens flares
  18521. if (this.lensFlaresEnabled) {
  18522. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18523. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18524. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18525. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18526. lensFlareSystem.render();
  18527. }
  18528. }
  18529. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18530. }
  18531. // Foregrounds
  18532. if (this.layers.length) {
  18533. engine.setDepthBuffer(false);
  18534. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18535. layer = this.layers[layerIndex];
  18536. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18537. layer.render();
  18538. }
  18539. }
  18540. engine.setDepthBuffer(true);
  18541. }
  18542. // Highlight Layer
  18543. if (renderhighlights) {
  18544. engine.setDepthBuffer(false);
  18545. for (var i = 0; i < this.highlightLayers.length; i++) {
  18546. if (this.highlightLayers[i].shouldRender()) {
  18547. this.highlightLayers[i].render();
  18548. }
  18549. }
  18550. engine.setDepthBuffer(true);
  18551. }
  18552. this._renderDuration.endMonitoring(false);
  18553. // Finalize frame
  18554. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18555. // Update camera
  18556. this.activeCamera._updateFromScene();
  18557. // Reset some special arrays
  18558. this._renderTargets.reset();
  18559. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18560. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18561. };
  18562. Scene.prototype._processSubCameras = function (camera) {
  18563. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18564. this._renderForCamera(camera);
  18565. return;
  18566. }
  18567. // rig cameras
  18568. for (var index = 0; index < camera._rigCameras.length; index++) {
  18569. this._renderForCamera(camera._rigCameras[index]);
  18570. }
  18571. this.activeCamera = camera;
  18572. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18573. // Update camera
  18574. this.activeCamera._updateFromScene();
  18575. };
  18576. Scene.prototype._checkIntersections = function () {
  18577. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18578. var sourceMesh = this._meshesForIntersections.data[index];
  18579. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18580. var action = sourceMesh.actionManager.actions[actionIndex];
  18581. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18582. var parameters = action.getTriggerParameter();
  18583. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18584. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18585. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18586. if (areIntersecting && currentIntersectionInProgress === -1) {
  18587. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18588. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18589. sourceMesh._intersectionsInProgress.push(otherMesh);
  18590. }
  18591. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18592. sourceMesh._intersectionsInProgress.push(otherMesh);
  18593. }
  18594. }
  18595. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18596. //They intersected, and now they don't.
  18597. //is this trigger an exit trigger? execute an event.
  18598. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18599. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18600. }
  18601. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18602. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18603. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18604. }
  18605. }
  18606. }
  18607. }
  18608. }
  18609. };
  18610. Scene.prototype.render = function () {
  18611. if (this.isDisposed) {
  18612. return;
  18613. }
  18614. this._lastFrameDuration.beginMonitoring();
  18615. this._particlesDuration.fetchNewFrame();
  18616. this._spritesDuration.fetchNewFrame();
  18617. this._activeParticles.fetchNewFrame();
  18618. this._renderDuration.fetchNewFrame();
  18619. this._renderTargetsDuration.fetchNewFrame();
  18620. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18621. this._totalVertices.fetchNewFrame();
  18622. this._activeIndices.fetchNewFrame();
  18623. this._activeBones.fetchNewFrame();
  18624. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18625. this._meshesForIntersections.reset();
  18626. this.resetCachedMaterial();
  18627. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18628. // Actions
  18629. if (this.actionManager) {
  18630. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18631. }
  18632. //Simplification Queue
  18633. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18634. this.simplificationQueue.executeNext();
  18635. }
  18636. if (this._engine.isDeterministicLockStep()) {
  18637. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18638. var defaultTimeStep = (60.0 / 1000.0);
  18639. if (this._physicsEngine) {
  18640. defaultTimeStep = this._physicsEngine.getTimeStep();
  18641. }
  18642. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18643. this._timeAccumulator += deltaTime;
  18644. // compute the amount of fixed steps we should have taken since the last step
  18645. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18646. internalSteps = Math.min(internalSteps, maxSubSteps);
  18647. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  18648. this.onBeforeStepObservable.notifyObservers(this);
  18649. // Animations
  18650. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  18651. this._animate();
  18652. // Physics
  18653. if (this._physicsEngine) {
  18654. BABYLON.Tools.StartPerformanceCounter("Physics");
  18655. this._physicsEngine._step(defaultTimeStep);
  18656. BABYLON.Tools.EndPerformanceCounter("Physics");
  18657. }
  18658. this._timeAccumulator -= defaultTimeStep;
  18659. this.onAfterStepObservable.notifyObservers(this);
  18660. this._currentStepId++;
  18661. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  18662. // Q: can this be optimized by putting some code in the afterStep callback?
  18663. // I had to put this code here, otherwise mesh attached to bones of another mesh skeleton,
  18664. // would return incorrect positions for internal stepIds (non-rendered steps)
  18665. this._evaluateActiveMeshes();
  18666. }
  18667. }
  18668. }
  18669. else {
  18670. // Animations
  18671. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18672. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18673. this._animate();
  18674. // Physics
  18675. if (this._physicsEngine) {
  18676. BABYLON.Tools.StartPerformanceCounter("Physics");
  18677. this._physicsEngine._step(deltaTime / 1000.0);
  18678. BABYLON.Tools.EndPerformanceCounter("Physics");
  18679. }
  18680. }
  18681. // Before render
  18682. this.onBeforeRenderObservable.notifyObservers(this);
  18683. // Customs render targets
  18684. this._renderTargetsDuration.beginMonitoring();
  18685. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18686. var engine = this.getEngine();
  18687. var currentActiveCamera = this.activeCamera;
  18688. if (this.renderTargetsEnabled) {
  18689. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18690. this._intermediateRendering = true;
  18691. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18692. var renderTarget = this.customRenderTargets[customIndex];
  18693. if (renderTarget._shouldRender()) {
  18694. this._renderId++;
  18695. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18696. if (!this.activeCamera)
  18697. throw new Error("Active camera not set");
  18698. // Viewport
  18699. engine.setViewport(this.activeCamera.viewport);
  18700. // Camera
  18701. this.updateTransformMatrix();
  18702. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18703. }
  18704. }
  18705. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18706. this._intermediateRendering = false;
  18707. this._renderId++;
  18708. }
  18709. // Restore back buffer
  18710. if (this.customRenderTargets.length > 0) {
  18711. engine.restoreDefaultFramebuffer();
  18712. }
  18713. this._renderTargetsDuration.endMonitoring();
  18714. this.activeCamera = currentActiveCamera;
  18715. // Procedural textures
  18716. if (this.proceduralTexturesEnabled) {
  18717. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18718. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18719. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18720. if (proceduralTexture._shouldRender()) {
  18721. proceduralTexture.render();
  18722. }
  18723. }
  18724. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18725. }
  18726. // Clear
  18727. if (this.autoClearDepthAndStencil || this.autoClear) {
  18728. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18729. }
  18730. // Shadows
  18731. if (this.shadowsEnabled) {
  18732. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18733. var light = this.lights[lightIndex];
  18734. var shadowGenerator = light.getShadowGenerator();
  18735. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18736. var shadowMap = shadowGenerator.getShadowMap();
  18737. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18738. this._renderTargets.push(shadowMap);
  18739. }
  18740. }
  18741. }
  18742. }
  18743. // Depth renderer
  18744. if (this._depthRenderer) {
  18745. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18746. }
  18747. // Geometry renderer
  18748. if (this._geometryBufferRenderer) {
  18749. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  18750. }
  18751. // RenderPipeline
  18752. if (this._postProcessRenderPipelineManager) {
  18753. this._postProcessRenderPipelineManager.update();
  18754. }
  18755. // Multi-cameras?
  18756. if (this.activeCameras.length > 0) {
  18757. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18758. if (cameraIndex > 0) {
  18759. this._engine.clear(null, false, true, true);
  18760. }
  18761. this._processSubCameras(this.activeCameras[cameraIndex]);
  18762. }
  18763. }
  18764. else {
  18765. if (!this.activeCamera) {
  18766. throw new Error("No camera defined");
  18767. }
  18768. this._processSubCameras(this.activeCamera);
  18769. }
  18770. // Intersection checks
  18771. this._checkIntersections();
  18772. // Update the audio listener attached to the camera
  18773. if (BABYLON.AudioEngine) {
  18774. this._updateAudioParameters();
  18775. }
  18776. // After render
  18777. if (this.afterRender) {
  18778. this.afterRender();
  18779. }
  18780. this.onAfterRenderObservable.notifyObservers(this);
  18781. // Cleaning
  18782. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18783. this._toBeDisposed.data[index].dispose();
  18784. this._toBeDisposed[index] = null;
  18785. }
  18786. this._toBeDisposed.reset();
  18787. if (this.dumpNextRenderTargets) {
  18788. this.dumpNextRenderTargets = false;
  18789. }
  18790. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18791. this._lastFrameDuration.endMonitoring();
  18792. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18793. this._totalLightsCounter.addCount(this.lights.length, true);
  18794. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18795. this._totalTexturesCounter.addCount(this.textures.length, true);
  18796. this._activeBones.addCount(0, true);
  18797. this._activeIndices.addCount(0, true);
  18798. this._activeParticles.addCount(0, true);
  18799. };
  18800. Scene.prototype._updateAudioParameters = function () {
  18801. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18802. return;
  18803. }
  18804. var listeningCamera;
  18805. var audioEngine = BABYLON.Engine.audioEngine;
  18806. if (this.activeCameras.length > 0) {
  18807. listeningCamera = this.activeCameras[0];
  18808. }
  18809. else {
  18810. listeningCamera = this.activeCamera;
  18811. }
  18812. if (listeningCamera && audioEngine.canUseWebAudio) {
  18813. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18814. // for VR cameras
  18815. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  18816. listeningCamera = listeningCamera.rigCameras[0];
  18817. }
  18818. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18819. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18820. cameraDirection.normalize();
  18821. // To avoid some errors on GearVR
  18822. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  18823. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18824. }
  18825. var i;
  18826. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18827. var sound = this.mainSoundTrack.soundCollection[i];
  18828. if (sound.useCustomAttenuation) {
  18829. sound.updateDistanceFromListener();
  18830. }
  18831. }
  18832. for (i = 0; i < this.soundTracks.length; i++) {
  18833. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18834. sound = this.soundTracks[i].soundCollection[j];
  18835. if (sound.useCustomAttenuation) {
  18836. sound.updateDistanceFromListener();
  18837. }
  18838. }
  18839. }
  18840. }
  18841. };
  18842. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18843. // Audio
  18844. get: function () {
  18845. return this._audioEnabled;
  18846. },
  18847. set: function (value) {
  18848. this._audioEnabled = value;
  18849. if (BABYLON.AudioEngine) {
  18850. if (this._audioEnabled) {
  18851. this._enableAudio();
  18852. }
  18853. else {
  18854. this._disableAudio();
  18855. }
  18856. }
  18857. },
  18858. enumerable: true,
  18859. configurable: true
  18860. });
  18861. Scene.prototype._disableAudio = function () {
  18862. var i;
  18863. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18864. this.mainSoundTrack.soundCollection[i].pause();
  18865. }
  18866. for (i = 0; i < this.soundTracks.length; i++) {
  18867. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18868. this.soundTracks[i].soundCollection[j].pause();
  18869. }
  18870. }
  18871. };
  18872. Scene.prototype._enableAudio = function () {
  18873. var i;
  18874. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18875. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18876. this.mainSoundTrack.soundCollection[i].play();
  18877. }
  18878. }
  18879. for (i = 0; i < this.soundTracks.length; i++) {
  18880. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18881. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18882. this.soundTracks[i].soundCollection[j].play();
  18883. }
  18884. }
  18885. }
  18886. };
  18887. Object.defineProperty(Scene.prototype, "headphone", {
  18888. get: function () {
  18889. return this._headphone;
  18890. },
  18891. set: function (value) {
  18892. this._headphone = value;
  18893. if (BABYLON.AudioEngine) {
  18894. if (this._headphone) {
  18895. this._switchAudioModeForHeadphones();
  18896. }
  18897. else {
  18898. this._switchAudioModeForNormalSpeakers();
  18899. }
  18900. }
  18901. },
  18902. enumerable: true,
  18903. configurable: true
  18904. });
  18905. Scene.prototype._switchAudioModeForHeadphones = function () {
  18906. this.mainSoundTrack.switchPanningModelToHRTF();
  18907. for (var i = 0; i < this.soundTracks.length; i++) {
  18908. this.soundTracks[i].switchPanningModelToHRTF();
  18909. }
  18910. };
  18911. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18912. this.mainSoundTrack.switchPanningModelToEqualPower();
  18913. for (var i = 0; i < this.soundTracks.length; i++) {
  18914. this.soundTracks[i].switchPanningModelToEqualPower();
  18915. }
  18916. };
  18917. Scene.prototype.enableDepthRenderer = function () {
  18918. if (this._depthRenderer) {
  18919. return this._depthRenderer;
  18920. }
  18921. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18922. return this._depthRenderer;
  18923. };
  18924. Scene.prototype.disableDepthRenderer = function () {
  18925. if (!this._depthRenderer) {
  18926. return;
  18927. }
  18928. this._depthRenderer.dispose();
  18929. this._depthRenderer = null;
  18930. };
  18931. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  18932. if (ratio === void 0) { ratio = 1; }
  18933. if (this._geometryBufferRenderer) {
  18934. return this._geometryBufferRenderer;
  18935. }
  18936. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18937. if (!this._geometryBufferRenderer.isSupported) {
  18938. this._geometryBufferRenderer = null;
  18939. }
  18940. return this._geometryBufferRenderer;
  18941. };
  18942. Scene.prototype.disableGeometryBufferRenderer = function () {
  18943. if (!this._geometryBufferRenderer) {
  18944. return;
  18945. }
  18946. this._geometryBufferRenderer.dispose();
  18947. this._geometryBufferRenderer = null;
  18948. };
  18949. Scene.prototype.freezeMaterials = function () {
  18950. for (var i = 0; i < this.materials.length; i++) {
  18951. this.materials[i].freeze();
  18952. }
  18953. };
  18954. Scene.prototype.unfreezeMaterials = function () {
  18955. for (var i = 0; i < this.materials.length; i++) {
  18956. this.materials[i].unfreeze();
  18957. }
  18958. };
  18959. Scene.prototype.dispose = function () {
  18960. this.beforeRender = null;
  18961. this.afterRender = null;
  18962. this.skeletons = [];
  18963. this.morphTargetManagers = [];
  18964. this.importedMeshesFiles = new Array();
  18965. this.resetCachedMaterial();
  18966. if (this._depthRenderer) {
  18967. this._depthRenderer.dispose();
  18968. }
  18969. if (this._gamepadManager) {
  18970. this._gamepadManager.dispose();
  18971. this._gamepadManager = null;
  18972. }
  18973. // Smart arrays
  18974. if (this.activeCamera) {
  18975. this.activeCamera._activeMeshes.dispose();
  18976. this.activeCamera = null;
  18977. }
  18978. this._activeMeshes.dispose();
  18979. this._renderingManager.dispose();
  18980. this._processedMaterials.dispose();
  18981. this._activeParticleSystems.dispose();
  18982. this._activeSkeletons.dispose();
  18983. this._softwareSkinnedMeshes.dispose();
  18984. this._renderTargets.dispose();
  18985. if (this._boundingBoxRenderer) {
  18986. this._boundingBoxRenderer.dispose();
  18987. }
  18988. this._meshesForIntersections.dispose();
  18989. this._toBeDisposed.dispose();
  18990. // Debug layer
  18991. if (this._debugLayer) {
  18992. this._debugLayer.hide();
  18993. }
  18994. // Events
  18995. this.onDisposeObservable.notifyObservers(this);
  18996. this.onDisposeObservable.clear();
  18997. this.onBeforeRenderObservable.clear();
  18998. this.onAfterRenderObservable.clear();
  18999. this.detachControl();
  19000. // Release sounds & sounds tracks
  19001. if (BABYLON.AudioEngine) {
  19002. this.disposeSounds();
  19003. }
  19004. // VR Helper
  19005. if (this.VRHelper) {
  19006. this.VRHelper.dispose();
  19007. }
  19008. // Detach cameras
  19009. var canvas = this._engine.getRenderingCanvas();
  19010. var index;
  19011. for (index = 0; index < this.cameras.length; index++) {
  19012. this.cameras[index].detachControl(canvas);
  19013. }
  19014. // Release lights
  19015. while (this.lights.length) {
  19016. this.lights[0].dispose();
  19017. }
  19018. // Release meshes
  19019. while (this.meshes.length) {
  19020. this.meshes[0].dispose(true);
  19021. }
  19022. // Release cameras
  19023. while (this.cameras.length) {
  19024. this.cameras[0].dispose();
  19025. }
  19026. // Release materials
  19027. if (this.defaultMaterial) {
  19028. this.defaultMaterial.dispose();
  19029. }
  19030. while (this.multiMaterials.length) {
  19031. this.multiMaterials[0].dispose();
  19032. }
  19033. while (this.materials.length) {
  19034. this.materials[0].dispose();
  19035. }
  19036. // Release particles
  19037. while (this.particleSystems.length) {
  19038. this.particleSystems[0].dispose();
  19039. }
  19040. // Release sprites
  19041. while (this.spriteManagers.length) {
  19042. this.spriteManagers[0].dispose();
  19043. }
  19044. // Release postProcesses
  19045. while (this.postProcesses.length) {
  19046. this.postProcesses[0].dispose();
  19047. }
  19048. // Release layers
  19049. while (this.layers.length) {
  19050. this.layers[0].dispose();
  19051. }
  19052. while (this.highlightLayers.length) {
  19053. this.highlightLayers[0].dispose();
  19054. }
  19055. // Release textures
  19056. while (this.textures.length) {
  19057. this.textures[0].dispose();
  19058. }
  19059. // Release UBO
  19060. this._sceneUbo.dispose();
  19061. // Post-processes
  19062. this.postProcessManager.dispose();
  19063. if (this._postProcessRenderPipelineManager) {
  19064. this._postProcessRenderPipelineManager.dispose();
  19065. }
  19066. // Physics
  19067. if (this._physicsEngine) {
  19068. this.disablePhysicsEngine();
  19069. }
  19070. // Remove from engine
  19071. index = this._engine.scenes.indexOf(this);
  19072. if (index > -1) {
  19073. this._engine.scenes.splice(index, 1);
  19074. }
  19075. this._engine.wipeCaches();
  19076. this._engine = null;
  19077. this.defaultMaterial = null;
  19078. this.multiMaterials = null;
  19079. this.materials = null;
  19080. };
  19081. Object.defineProperty(Scene.prototype, "isDisposed", {
  19082. get: function () {
  19083. return !this._engine;
  19084. },
  19085. enumerable: true,
  19086. configurable: true
  19087. });
  19088. // Release sounds & sounds tracks
  19089. Scene.prototype.disposeSounds = function () {
  19090. this.mainSoundTrack.dispose();
  19091. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19092. this.soundTracks[scIndex].dispose();
  19093. }
  19094. };
  19095. // Octrees
  19096. Scene.prototype.getWorldExtends = function () {
  19097. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19098. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19099. for (var index = 0; index < this.meshes.length; index++) {
  19100. var mesh = this.meshes[index];
  19101. mesh.computeWorldMatrix(true);
  19102. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19103. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19104. BABYLON.Tools.CheckExtends(minBox, min, max);
  19105. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19106. }
  19107. return {
  19108. min: min,
  19109. max: max
  19110. };
  19111. };
  19112. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19113. if (maxCapacity === void 0) { maxCapacity = 64; }
  19114. if (maxDepth === void 0) { maxDepth = 2; }
  19115. if (!this._selectionOctree) {
  19116. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19117. }
  19118. var worldExtends = this.getWorldExtends();
  19119. // Update octree
  19120. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19121. return this._selectionOctree;
  19122. };
  19123. // Picking
  19124. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19125. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19126. var engine = this._engine;
  19127. if (!camera) {
  19128. if (!this.activeCamera)
  19129. throw new Error("Active camera not set");
  19130. camera = this.activeCamera;
  19131. }
  19132. var cameraViewport = camera.viewport;
  19133. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19134. // Moving coordinates to local viewport world
  19135. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19136. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19137. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19138. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19139. };
  19140. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19141. if (!BABYLON.PickingInfo) {
  19142. return null;
  19143. }
  19144. var engine = this._engine;
  19145. if (!camera) {
  19146. if (!this.activeCamera)
  19147. throw new Error("Active camera not set");
  19148. camera = this.activeCamera;
  19149. }
  19150. var cameraViewport = camera.viewport;
  19151. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19152. var identity = BABYLON.Matrix.Identity();
  19153. // Moving coordinates to local viewport world
  19154. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19155. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19156. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19157. };
  19158. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19159. if (!BABYLON.PickingInfo) {
  19160. return null;
  19161. }
  19162. var pickingInfo = null;
  19163. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19164. var mesh = this.meshes[meshIndex];
  19165. if (predicate) {
  19166. if (!predicate(mesh)) {
  19167. continue;
  19168. }
  19169. }
  19170. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19171. continue;
  19172. }
  19173. var world = mesh.getWorldMatrix();
  19174. var ray = rayFunction(world);
  19175. var result = mesh.intersects(ray, fastCheck);
  19176. if (!result || !result.hit)
  19177. continue;
  19178. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19179. continue;
  19180. pickingInfo = result;
  19181. if (fastCheck) {
  19182. break;
  19183. }
  19184. }
  19185. return pickingInfo || new BABYLON.PickingInfo();
  19186. };
  19187. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19188. if (!BABYLON.PickingInfo) {
  19189. return null;
  19190. }
  19191. var pickingInfos = new Array();
  19192. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19193. var mesh = this.meshes[meshIndex];
  19194. if (predicate) {
  19195. if (!predicate(mesh)) {
  19196. continue;
  19197. }
  19198. }
  19199. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19200. continue;
  19201. }
  19202. var world = mesh.getWorldMatrix();
  19203. var ray = rayFunction(world);
  19204. var result = mesh.intersects(ray, false);
  19205. if (!result || !result.hit)
  19206. continue;
  19207. pickingInfos.push(result);
  19208. }
  19209. return pickingInfos;
  19210. };
  19211. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19212. if (!BABYLON.PickingInfo) {
  19213. return null;
  19214. }
  19215. var pickingInfo = null;
  19216. camera = camera || this.activeCamera;
  19217. if (this.spriteManagers.length > 0) {
  19218. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19219. var spriteManager = this.spriteManagers[spriteIndex];
  19220. if (!spriteManager.isPickable) {
  19221. continue;
  19222. }
  19223. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19224. if (!result || !result.hit)
  19225. continue;
  19226. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19227. continue;
  19228. pickingInfo = result;
  19229. if (fastCheck) {
  19230. break;
  19231. }
  19232. }
  19233. }
  19234. return pickingInfo || new BABYLON.PickingInfo();
  19235. };
  19236. /** Launch a ray to try to pick a mesh in the scene
  19237. * @param x position on screen
  19238. * @param y position on screen
  19239. * @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
  19240. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19241. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19242. */
  19243. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19244. var _this = this;
  19245. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19246. };
  19247. /** Launch a ray to try to pick a sprite in the scene
  19248. * @param x position on screen
  19249. * @param y position on screen
  19250. * @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
  19251. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19252. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19253. */
  19254. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19255. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19256. };
  19257. /** Use the given ray to pick a mesh in the scene
  19258. * @param ray The ray to use to pick meshes
  19259. * @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
  19260. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19261. */
  19262. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19263. var _this = this;
  19264. return this._internalPick(function (world) {
  19265. if (!_this._pickWithRayInverseMatrix) {
  19266. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19267. }
  19268. world.invertToRef(_this._pickWithRayInverseMatrix);
  19269. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19270. }, predicate, fastCheck);
  19271. };
  19272. /**
  19273. * Launch a ray to try to pick a mesh in the scene
  19274. * @param x X position on screen
  19275. * @param y Y position on screen
  19276. * @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
  19277. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19278. */
  19279. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19280. var _this = this;
  19281. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19282. };
  19283. /**
  19284. * Launch a ray to try to pick a mesh in the scene
  19285. * @param ray Ray to use
  19286. * @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
  19287. */
  19288. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19289. var _this = this;
  19290. return this._internalMultiPick(function (world) {
  19291. if (!_this._pickWithRayInverseMatrix) {
  19292. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19293. }
  19294. world.invertToRef(_this._pickWithRayInverseMatrix);
  19295. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19296. }, predicate);
  19297. };
  19298. Scene.prototype.setPointerOverMesh = function (mesh) {
  19299. if (this._pointerOverMesh === mesh) {
  19300. return;
  19301. }
  19302. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19303. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19304. }
  19305. this._pointerOverMesh = mesh;
  19306. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19307. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19308. }
  19309. };
  19310. Scene.prototype.getPointerOverMesh = function () {
  19311. return this._pointerOverMesh;
  19312. };
  19313. Scene.prototype.setPointerOverSprite = function (sprite) {
  19314. if (this._pointerOverSprite === sprite) {
  19315. return;
  19316. }
  19317. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19318. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19319. }
  19320. this._pointerOverSprite = sprite;
  19321. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19322. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19323. }
  19324. };
  19325. Scene.prototype.getPointerOverSprite = function () {
  19326. return this._pointerOverSprite;
  19327. };
  19328. // Physics
  19329. Scene.prototype.getPhysicsEngine = function () {
  19330. return this._physicsEngine;
  19331. };
  19332. /**
  19333. * Enables physics to the current scene
  19334. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19335. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19336. * @return {boolean} was the physics engine initialized
  19337. */
  19338. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19339. if (this._physicsEngine) {
  19340. return true;
  19341. }
  19342. try {
  19343. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19344. return true;
  19345. }
  19346. catch (e) {
  19347. BABYLON.Tools.Error(e.message);
  19348. return false;
  19349. }
  19350. };
  19351. Scene.prototype.disablePhysicsEngine = function () {
  19352. if (!this._physicsEngine) {
  19353. return;
  19354. }
  19355. this._physicsEngine.dispose();
  19356. this._physicsEngine = undefined;
  19357. };
  19358. Scene.prototype.isPhysicsEnabled = function () {
  19359. return this._physicsEngine !== undefined;
  19360. };
  19361. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19362. var mesh = compound.parts[0].mesh;
  19363. mesh.physicsImpostor.dispose();
  19364. mesh.physicsImpostor = null;
  19365. };
  19366. // Misc.
  19367. Scene.prototype._rebuildGeometries = function () {
  19368. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19369. var geometry = _a[_i];
  19370. geometry._rebuild();
  19371. }
  19372. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19373. var mesh = _c[_b];
  19374. mesh._rebuild();
  19375. }
  19376. if (this.postProcessManager) {
  19377. this.postProcessManager._rebuild();
  19378. }
  19379. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19380. var layer = _e[_d];
  19381. layer._rebuild();
  19382. }
  19383. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19384. var highlightLayer = _g[_f];
  19385. highlightLayer._rebuild();
  19386. }
  19387. if (this._boundingBoxRenderer) {
  19388. this._boundingBoxRenderer._rebuild();
  19389. }
  19390. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  19391. var system = _j[_h];
  19392. system.rebuild();
  19393. }
  19394. if (this._postProcessRenderPipelineManager) {
  19395. this._postProcessRenderPipelineManager._rebuild();
  19396. }
  19397. };
  19398. Scene.prototype._rebuildTextures = function () {
  19399. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19400. var texture = _a[_i];
  19401. texture._rebuild();
  19402. }
  19403. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19404. };
  19405. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19406. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19407. if (replace === void 0) { replace = false; }
  19408. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19409. // Dispose existing camera or light in replace mode.
  19410. if (replace) {
  19411. if (this.activeCamera) {
  19412. this.activeCamera.dispose();
  19413. this.activeCamera = null;
  19414. }
  19415. if (this.lights) {
  19416. for (var i = 0; i < this.lights.length; i++) {
  19417. this.lights[i].dispose();
  19418. }
  19419. }
  19420. }
  19421. // Light
  19422. if (this.lights.length === 0) {
  19423. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19424. }
  19425. // Camera
  19426. if (!this.activeCamera) {
  19427. var worldExtends = this.getWorldExtends();
  19428. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19429. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19430. var camera;
  19431. var radius = worldSize.length() * 1.5;
  19432. if (createArcRotateCamera) {
  19433. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19434. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19435. arcRotateCamera.wheelPrecision = 100 / radius;
  19436. camera = arcRotateCamera;
  19437. }
  19438. else {
  19439. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19440. freeCamera.setTarget(worldCenter);
  19441. camera = freeCamera;
  19442. }
  19443. camera.minZ = radius * 0.01;
  19444. camera.maxZ = radius * 100;
  19445. camera.speed = radius * 0.2;
  19446. this.activeCamera = camera;
  19447. if (attachCameraControls) {
  19448. camera.attachControl(this.getEngine().getRenderingCanvas());
  19449. }
  19450. }
  19451. };
  19452. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19453. if (pbr === void 0) { pbr = false; }
  19454. if (scale === void 0) { scale = 1000; }
  19455. if (blur === void 0) { blur = 0; }
  19456. if (environmentTexture) {
  19457. this.environmentTexture = environmentTexture;
  19458. }
  19459. if (!this.environmentTexture) {
  19460. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19461. return;
  19462. }
  19463. // Skybox
  19464. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19465. if (pbr) {
  19466. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19467. hdrSkyboxMaterial.backFaceCulling = false;
  19468. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19469. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19470. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19471. hdrSkyboxMaterial.disableLighting = true;
  19472. hdrSkyboxMaterial.twoSidedLighting = true;
  19473. hdrSkybox.infiniteDistance = true;
  19474. hdrSkybox.material = hdrSkyboxMaterial;
  19475. }
  19476. else {
  19477. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19478. skyboxMaterial.backFaceCulling = false;
  19479. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19480. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19481. skyboxMaterial.disableLighting = true;
  19482. hdrSkybox.infiniteDistance = true;
  19483. hdrSkybox.material = skyboxMaterial;
  19484. }
  19485. return hdrSkybox;
  19486. };
  19487. Scene.prototype.createDefaultVRExperience = function () {
  19488. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19489. };
  19490. // Tags
  19491. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19492. if (tagsQuery === undefined) {
  19493. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19494. return list;
  19495. }
  19496. var listByTags = [];
  19497. forEach = forEach || (function (item) { return; });
  19498. for (var i in list) {
  19499. var item = list[i];
  19500. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19501. listByTags.push(item);
  19502. forEach(item);
  19503. }
  19504. }
  19505. return listByTags;
  19506. };
  19507. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19508. return this._getByTags(this.meshes, tagsQuery, forEach);
  19509. };
  19510. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19511. return this._getByTags(this.cameras, tagsQuery, forEach);
  19512. };
  19513. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19514. return this._getByTags(this.lights, tagsQuery, forEach);
  19515. };
  19516. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19517. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19518. };
  19519. /**
  19520. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19521. * This allowed control for front to back rendering or reversly depending of the special needs.
  19522. *
  19523. * @param renderingGroupId The rendering group id corresponding to its index
  19524. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19525. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19526. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19527. */
  19528. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19529. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19530. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19531. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19532. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19533. };
  19534. /**
  19535. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19536. *
  19537. * @param renderingGroupId The rendering group id corresponding to its index
  19538. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19539. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19540. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19541. */
  19542. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19543. if (depth === void 0) { depth = true; }
  19544. if (stencil === void 0) { stencil = true; }
  19545. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19546. };
  19547. /**
  19548. * Will flag all materials as dirty to trigger new shader compilation
  19549. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19550. */
  19551. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19552. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19553. var material = _a[_i];
  19554. if (predicate && !predicate(material)) {
  19555. continue;
  19556. }
  19557. material.markAsDirty(flag);
  19558. }
  19559. };
  19560. // Statics
  19561. Scene._FOGMODE_NONE = 0;
  19562. Scene._FOGMODE_EXP = 1;
  19563. Scene._FOGMODE_EXP2 = 2;
  19564. Scene._FOGMODE_LINEAR = 3;
  19565. Scene.MinDeltaTime = 1.0;
  19566. Scene.MaxDeltaTime = 1000.0;
  19567. /** The distance in pixel that you have to move to prevent some events */
  19568. Scene.DragMovementThreshold = 10; // in pixels
  19569. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19570. Scene.LongPressDelay = 500; // in milliseconds
  19571. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19572. Scene.DoubleClickDelay = 300; // in milliseconds
  19573. /** If you need to check double click without raising a single click at first click, enable this flag */
  19574. Scene.ExclusiveDoubleClickMode = false;
  19575. return Scene;
  19576. }());
  19577. BABYLON.Scene = Scene;
  19578. })(BABYLON || (BABYLON = {}));
  19579. //# sourceMappingURL=babylon.scene.js.map
  19580. var BABYLON;
  19581. (function (BABYLON) {
  19582. var Buffer = (function () {
  19583. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19584. if (engine instanceof BABYLON.Mesh) {
  19585. this._engine = engine.getScene().getEngine();
  19586. }
  19587. else {
  19588. this._engine = engine;
  19589. }
  19590. this._updatable = updatable;
  19591. this._data = data;
  19592. this._strideSize = stride;
  19593. if (!postponeInternalCreation) {
  19594. this.create();
  19595. }
  19596. this._instanced = instanced;
  19597. this._instanceDivisor = instanced ? 1 : 0;
  19598. }
  19599. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19600. // a lot of these parameters are ignored as they are overriden by the buffer
  19601. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19602. };
  19603. // Properties
  19604. Buffer.prototype.isUpdatable = function () {
  19605. return this._updatable;
  19606. };
  19607. Buffer.prototype.getData = function () {
  19608. return this._data;
  19609. };
  19610. Buffer.prototype.getBuffer = function () {
  19611. return this._buffer;
  19612. };
  19613. Buffer.prototype.getStrideSize = function () {
  19614. return this._strideSize;
  19615. };
  19616. Buffer.prototype.getIsInstanced = function () {
  19617. return this._instanced;
  19618. };
  19619. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19620. get: function () {
  19621. return this._instanceDivisor;
  19622. },
  19623. set: function (value) {
  19624. this._instanceDivisor = value;
  19625. if (value == 0) {
  19626. this._instanced = false;
  19627. }
  19628. else {
  19629. this._instanced = true;
  19630. }
  19631. },
  19632. enumerable: true,
  19633. configurable: true
  19634. });
  19635. // Methods
  19636. Buffer.prototype.create = function (data) {
  19637. if (!data && this._buffer) {
  19638. return; // nothing to do
  19639. }
  19640. data = data || this._data;
  19641. if (!this._buffer) {
  19642. if (this._updatable) {
  19643. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19644. this._data = data;
  19645. }
  19646. else {
  19647. this._buffer = this._engine.createVertexBuffer(data);
  19648. }
  19649. }
  19650. else if (this._updatable) {
  19651. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19652. this._data = data;
  19653. }
  19654. };
  19655. Buffer.prototype._rebuild = function () {
  19656. this._buffer = null;
  19657. this.create(this._data);
  19658. };
  19659. Buffer.prototype.update = function (data) {
  19660. this.create(data);
  19661. };
  19662. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19663. if (!this._buffer) {
  19664. return;
  19665. }
  19666. if (this._updatable) {
  19667. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19668. this._data = null;
  19669. }
  19670. };
  19671. Buffer.prototype.dispose = function () {
  19672. if (!this._buffer) {
  19673. return;
  19674. }
  19675. if (this._engine._releaseBuffer(this._buffer)) {
  19676. this._buffer = null;
  19677. }
  19678. };
  19679. return Buffer;
  19680. }());
  19681. BABYLON.Buffer = Buffer;
  19682. })(BABYLON || (BABYLON = {}));
  19683. //# sourceMappingURL=babylon.buffer.js.map
  19684. var BABYLON;
  19685. (function (BABYLON) {
  19686. var VertexBuffer = (function () {
  19687. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19688. if (!stride) {
  19689. // Deduce stride from kind
  19690. switch (kind) {
  19691. case VertexBuffer.PositionKind:
  19692. stride = 3;
  19693. break;
  19694. case VertexBuffer.NormalKind:
  19695. stride = 3;
  19696. break;
  19697. case VertexBuffer.UVKind:
  19698. case VertexBuffer.UV2Kind:
  19699. case VertexBuffer.UV3Kind:
  19700. case VertexBuffer.UV4Kind:
  19701. case VertexBuffer.UV5Kind:
  19702. case VertexBuffer.UV6Kind:
  19703. stride = 2;
  19704. break;
  19705. case VertexBuffer.TangentKind:
  19706. case VertexBuffer.ColorKind:
  19707. stride = 4;
  19708. break;
  19709. case VertexBuffer.MatricesIndicesKind:
  19710. case VertexBuffer.MatricesIndicesExtraKind:
  19711. stride = 4;
  19712. break;
  19713. case VertexBuffer.MatricesWeightsKind:
  19714. case VertexBuffer.MatricesWeightsExtraKind:
  19715. stride = 4;
  19716. break;
  19717. }
  19718. }
  19719. if (data instanceof BABYLON.Buffer) {
  19720. if (!stride) {
  19721. stride = data.getStrideSize();
  19722. }
  19723. this._buffer = data;
  19724. this._ownsBuffer = false;
  19725. }
  19726. else {
  19727. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19728. this._ownsBuffer = true;
  19729. }
  19730. this._stride = stride;
  19731. this._offset = offset ? offset : 0;
  19732. this._size = size ? size : stride;
  19733. this._kind = kind;
  19734. }
  19735. VertexBuffer.prototype._rebuild = function () {
  19736. if (!this._buffer) {
  19737. return;
  19738. }
  19739. this._buffer._rebuild();
  19740. };
  19741. /**
  19742. * Returns the kind of the VertexBuffer (string).
  19743. */
  19744. VertexBuffer.prototype.getKind = function () {
  19745. return this._kind;
  19746. };
  19747. // Properties
  19748. /**
  19749. * Boolean : is the VertexBuffer updatable ?
  19750. */
  19751. VertexBuffer.prototype.isUpdatable = function () {
  19752. return this._buffer.isUpdatable();
  19753. };
  19754. /**
  19755. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  19756. */
  19757. VertexBuffer.prototype.getData = function () {
  19758. return this._buffer.getData();
  19759. };
  19760. /**
  19761. * Returns the WebGLBuffer associated to the VertexBuffer.
  19762. */
  19763. VertexBuffer.prototype.getBuffer = function () {
  19764. return this._buffer.getBuffer();
  19765. };
  19766. /**
  19767. * Returns the stride of the VertexBuffer (integer).
  19768. */
  19769. VertexBuffer.prototype.getStrideSize = function () {
  19770. return this._stride;
  19771. };
  19772. /**
  19773. * Returns the offset (integer).
  19774. */
  19775. VertexBuffer.prototype.getOffset = function () {
  19776. return this._offset;
  19777. };
  19778. /**
  19779. * Returns the VertexBuffer total size (integer).
  19780. */
  19781. VertexBuffer.prototype.getSize = function () {
  19782. return this._size;
  19783. };
  19784. /**
  19785. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  19786. */
  19787. VertexBuffer.prototype.getIsInstanced = function () {
  19788. return this._buffer.getIsInstanced();
  19789. };
  19790. /**
  19791. * Returns the instancing divisor, zero for non-instanced (integer).
  19792. */
  19793. VertexBuffer.prototype.getInstanceDivisor = function () {
  19794. return this._buffer.instanceDivisor;
  19795. };
  19796. // Methods
  19797. /**
  19798. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  19799. * Returns the created WebGLBuffer.
  19800. */
  19801. VertexBuffer.prototype.create = function (data) {
  19802. return this._buffer.create(data);
  19803. };
  19804. /**
  19805. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19806. * Returns the updated WebGLBuffer.
  19807. */
  19808. VertexBuffer.prototype.update = function (data) {
  19809. return this._buffer.update(data);
  19810. };
  19811. /**
  19812. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19813. * Returns the directly updated WebGLBuffer.
  19814. */
  19815. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19816. return this._buffer.updateDirectly(data, offset);
  19817. };
  19818. /**
  19819. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  19820. */
  19821. VertexBuffer.prototype.dispose = function () {
  19822. if (this._ownsBuffer) {
  19823. this._buffer.dispose();
  19824. }
  19825. };
  19826. Object.defineProperty(VertexBuffer, "PositionKind", {
  19827. get: function () {
  19828. return VertexBuffer._PositionKind;
  19829. },
  19830. enumerable: true,
  19831. configurable: true
  19832. });
  19833. Object.defineProperty(VertexBuffer, "NormalKind", {
  19834. get: function () {
  19835. return VertexBuffer._NormalKind;
  19836. },
  19837. enumerable: true,
  19838. configurable: true
  19839. });
  19840. Object.defineProperty(VertexBuffer, "TangentKind", {
  19841. get: function () {
  19842. return VertexBuffer._TangentKind;
  19843. },
  19844. enumerable: true,
  19845. configurable: true
  19846. });
  19847. Object.defineProperty(VertexBuffer, "UVKind", {
  19848. get: function () {
  19849. return VertexBuffer._UVKind;
  19850. },
  19851. enumerable: true,
  19852. configurable: true
  19853. });
  19854. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19855. get: function () {
  19856. return VertexBuffer._UV2Kind;
  19857. },
  19858. enumerable: true,
  19859. configurable: true
  19860. });
  19861. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19862. get: function () {
  19863. return VertexBuffer._UV3Kind;
  19864. },
  19865. enumerable: true,
  19866. configurable: true
  19867. });
  19868. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19869. get: function () {
  19870. return VertexBuffer._UV4Kind;
  19871. },
  19872. enumerable: true,
  19873. configurable: true
  19874. });
  19875. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19876. get: function () {
  19877. return VertexBuffer._UV5Kind;
  19878. },
  19879. enumerable: true,
  19880. configurable: true
  19881. });
  19882. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19883. get: function () {
  19884. return VertexBuffer._UV6Kind;
  19885. },
  19886. enumerable: true,
  19887. configurable: true
  19888. });
  19889. Object.defineProperty(VertexBuffer, "ColorKind", {
  19890. get: function () {
  19891. return VertexBuffer._ColorKind;
  19892. },
  19893. enumerable: true,
  19894. configurable: true
  19895. });
  19896. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19897. get: function () {
  19898. return VertexBuffer._MatricesIndicesKind;
  19899. },
  19900. enumerable: true,
  19901. configurable: true
  19902. });
  19903. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19904. get: function () {
  19905. return VertexBuffer._MatricesWeightsKind;
  19906. },
  19907. enumerable: true,
  19908. configurable: true
  19909. });
  19910. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19911. get: function () {
  19912. return VertexBuffer._MatricesIndicesExtraKind;
  19913. },
  19914. enumerable: true,
  19915. configurable: true
  19916. });
  19917. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19918. get: function () {
  19919. return VertexBuffer._MatricesWeightsExtraKind;
  19920. },
  19921. enumerable: true,
  19922. configurable: true
  19923. });
  19924. // Enums
  19925. VertexBuffer._PositionKind = "position";
  19926. VertexBuffer._NormalKind = "normal";
  19927. VertexBuffer._TangentKind = "tangent";
  19928. VertexBuffer._UVKind = "uv";
  19929. VertexBuffer._UV2Kind = "uv2";
  19930. VertexBuffer._UV3Kind = "uv3";
  19931. VertexBuffer._UV4Kind = "uv4";
  19932. VertexBuffer._UV5Kind = "uv5";
  19933. VertexBuffer._UV6Kind = "uv6";
  19934. VertexBuffer._ColorKind = "color";
  19935. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19936. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19937. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19938. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19939. return VertexBuffer;
  19940. }());
  19941. BABYLON.VertexBuffer = VertexBuffer;
  19942. })(BABYLON || (BABYLON = {}));
  19943. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19944. var BABYLON;
  19945. (function (BABYLON) {
  19946. var InternalTexture = (function () {
  19947. function InternalTexture(engine, dataSource) {
  19948. this.onLoadedObservable = new BABYLON.Observable();
  19949. // Private
  19950. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  19951. this._references = 1;
  19952. this._engine = engine;
  19953. this._dataSource = dataSource;
  19954. this._webGLTexture = engine._createTexture();
  19955. }
  19956. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  19957. get: function () {
  19958. return this._dataSource;
  19959. },
  19960. enumerable: true,
  19961. configurable: true
  19962. });
  19963. InternalTexture.prototype.incrementReferences = function () {
  19964. this._references++;
  19965. };
  19966. InternalTexture.prototype.updateSize = function (width, height) {
  19967. this.width = width;
  19968. this.height = height;
  19969. this._size = width * height;
  19970. this.baseWidth = width;
  19971. this.baseHeight = height;
  19972. };
  19973. InternalTexture.prototype._rebuild = function () {
  19974. var _this = this;
  19975. var proxy;
  19976. this.isReady = false;
  19977. this._cachedCoordinatesMode = null;
  19978. this._cachedWrapU = null;
  19979. this._cachedWrapV = null;
  19980. this._cachedAnisotropicFilteringLevel = null;
  19981. switch (this._dataSource) {
  19982. case InternalTexture.DATASOURCE_TEMP:
  19983. return;
  19984. case InternalTexture.DATASOURCE_URL:
  19985. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  19986. _this.isReady = true;
  19987. }, null, this._buffer, null, this.format);
  19988. proxy._swapAndDie(this);
  19989. return;
  19990. case InternalTexture.DATASOURCE_RAW:
  19991. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  19992. proxy._swapAndDie(this);
  19993. this.isReady = true;
  19994. return;
  19995. case InternalTexture.DATASOURCE_DYNAMIC:
  19996. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  19997. proxy._swapAndDie(this);
  19998. // The engine will make sure to update content so no need to flag it as isReady = true
  19999. return;
  20000. case InternalTexture.DATASOURCE_RENDERTARGET:
  20001. var options = new BABYLON.RenderTargetCreationOptions();
  20002. options.generateDepthBuffer = this._generateDepthBuffer;
  20003. options.generateMipMaps = this.generateMipMaps;
  20004. options.generateStencilBuffer = this._generateStencilBuffer;
  20005. options.samplingMode = this.samplingMode;
  20006. options.type = this.type;
  20007. if (this.isCube) {
  20008. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20009. }
  20010. else {
  20011. var size = {
  20012. width: this.width,
  20013. height: this.height
  20014. };
  20015. proxy = this._engine.createRenderTargetTexture(size, options);
  20016. }
  20017. proxy._swapAndDie(this);
  20018. this.isReady = true;
  20019. return;
  20020. case InternalTexture.DATASOURCE_CUBE:
  20021. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20022. _this.isReady = true;
  20023. }, null, this.format, this._extension);
  20024. proxy._swapAndDie(this);
  20025. return;
  20026. case InternalTexture.DATASOURCE_CUBERAW:
  20027. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20028. proxy._swapAndDie(this);
  20029. this.isReady = true;
  20030. return;
  20031. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20032. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20033. proxy._swapAndDie(_this);
  20034. _this.isReady = true;
  20035. }, null, this.format, this._extension);
  20036. return;
  20037. }
  20038. };
  20039. InternalTexture.prototype._swapAndDie = function (target) {
  20040. target._webGLTexture = this._webGLTexture;
  20041. if (this._framebuffer) {
  20042. target._framebuffer = this._framebuffer;
  20043. }
  20044. if (this._depthStencilBuffer) {
  20045. target._depthStencilBuffer = this._depthStencilBuffer;
  20046. }
  20047. if (this._lodTextureHigh) {
  20048. if (target._lodTextureHigh) {
  20049. target._lodTextureHigh.dispose();
  20050. }
  20051. target._lodTextureHigh = this._lodTextureHigh;
  20052. }
  20053. if (this._lodTextureMid) {
  20054. if (target._lodTextureMid) {
  20055. target._lodTextureMid.dispose();
  20056. }
  20057. target._lodTextureMid = this._lodTextureMid;
  20058. }
  20059. if (this._lodTextureLow) {
  20060. if (target._lodTextureLow) {
  20061. target._lodTextureLow.dispose();
  20062. }
  20063. target._lodTextureLow = this._lodTextureLow;
  20064. }
  20065. var cache = this._engine.getLoadedTexturesCache();
  20066. var index = cache.indexOf(this);
  20067. if (index !== -1) {
  20068. cache.splice(index, 1);
  20069. }
  20070. };
  20071. InternalTexture.prototype.dispose = function () {
  20072. if (!this._webGLTexture) {
  20073. return;
  20074. }
  20075. this._references--;
  20076. if (this._references === 0) {
  20077. this._engine._releaseTexture(this);
  20078. this._webGLTexture = null;
  20079. }
  20080. };
  20081. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20082. InternalTexture.DATASOURCE_URL = 1;
  20083. InternalTexture.DATASOURCE_TEMP = 2;
  20084. InternalTexture.DATASOURCE_RAW = 3;
  20085. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20086. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20087. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20088. InternalTexture.DATASOURCE_CUBE = 7;
  20089. InternalTexture.DATASOURCE_CUBERAW = 8;
  20090. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20091. return InternalTexture;
  20092. }());
  20093. BABYLON.InternalTexture = InternalTexture;
  20094. })(BABYLON || (BABYLON = {}));
  20095. //# sourceMappingURL=babylon.internalTexture.js.map
  20096. var BABYLON;
  20097. (function (BABYLON) {
  20098. var BaseTexture = (function () {
  20099. function BaseTexture(scene) {
  20100. this._hasAlpha = false;
  20101. this.getAlphaFromRGB = false;
  20102. this.level = 1;
  20103. this.coordinatesIndex = 0;
  20104. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20105. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20106. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20107. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20108. this.isCube = false;
  20109. this.gammaSpace = true;
  20110. this.invertZ = false;
  20111. this.lodLevelInAlpha = false;
  20112. this.lodGenerationOffset = 0.0;
  20113. this.lodGenerationScale = 0.8;
  20114. this.isRenderTarget = false;
  20115. this.animations = new Array();
  20116. /**
  20117. * An event triggered when the texture is disposed.
  20118. * @type {BABYLON.Observable}
  20119. */
  20120. this.onDisposeObservable = new BABYLON.Observable();
  20121. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20122. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20123. this._scene.textures.push(this);
  20124. this._uid = null;
  20125. }
  20126. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20127. get: function () {
  20128. return this._hasAlpha;
  20129. },
  20130. set: function (value) {
  20131. if (this._hasAlpha === value) {
  20132. return;
  20133. }
  20134. this._hasAlpha = value;
  20135. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20136. },
  20137. enumerable: true,
  20138. configurable: true
  20139. });
  20140. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20141. get: function () {
  20142. return this._coordinatesMode;
  20143. },
  20144. set: function (value) {
  20145. if (this._coordinatesMode === value) {
  20146. return;
  20147. }
  20148. this._coordinatesMode = value;
  20149. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20150. },
  20151. enumerable: true,
  20152. configurable: true
  20153. });
  20154. Object.defineProperty(BaseTexture.prototype, "uid", {
  20155. get: function () {
  20156. if (!this._uid) {
  20157. this._uid = BABYLON.Tools.RandomId();
  20158. }
  20159. return this._uid;
  20160. },
  20161. enumerable: true,
  20162. configurable: true
  20163. });
  20164. BaseTexture.prototype.toString = function () {
  20165. return this.name;
  20166. };
  20167. BaseTexture.prototype.getClassName = function () {
  20168. return "BaseTexture";
  20169. };
  20170. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20171. set: function (callback) {
  20172. if (this._onDisposeObserver) {
  20173. this.onDisposeObservable.remove(this._onDisposeObserver);
  20174. }
  20175. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20176. },
  20177. enumerable: true,
  20178. configurable: true
  20179. });
  20180. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20181. get: function () {
  20182. return true;
  20183. },
  20184. enumerable: true,
  20185. configurable: true
  20186. });
  20187. BaseTexture.prototype.getScene = function () {
  20188. return this._scene;
  20189. };
  20190. BaseTexture.prototype.getTextureMatrix = function () {
  20191. return null;
  20192. };
  20193. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20194. return null;
  20195. };
  20196. BaseTexture.prototype.getInternalTexture = function () {
  20197. return this._texture;
  20198. };
  20199. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20200. return !this.isBlocking || this.isReady();
  20201. };
  20202. BaseTexture.prototype.isReady = function () {
  20203. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20204. this.delayLoad();
  20205. return false;
  20206. }
  20207. if (this._texture) {
  20208. return this._texture.isReady;
  20209. }
  20210. return false;
  20211. };
  20212. BaseTexture.prototype.getSize = function () {
  20213. if (this._texture.width) {
  20214. return new BABYLON.Size(this._texture.width, this._texture.height);
  20215. }
  20216. if (this._texture._size) {
  20217. return new BABYLON.Size(this._texture._size, this._texture._size);
  20218. }
  20219. return BABYLON.Size.Zero();
  20220. };
  20221. BaseTexture.prototype.getBaseSize = function () {
  20222. if (!this.isReady() || !this._texture)
  20223. return BABYLON.Size.Zero();
  20224. if (this._texture._size) {
  20225. return new BABYLON.Size(this._texture._size, this._texture._size);
  20226. }
  20227. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20228. };
  20229. BaseTexture.prototype.scale = function (ratio) {
  20230. };
  20231. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20232. get: function () {
  20233. return false;
  20234. },
  20235. enumerable: true,
  20236. configurable: true
  20237. });
  20238. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20239. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20240. for (var index = 0; index < texturesCache.length; index++) {
  20241. var texturesCacheEntry = texturesCache[index];
  20242. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20243. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20244. texturesCacheEntry.incrementReferences();
  20245. return texturesCacheEntry;
  20246. }
  20247. }
  20248. }
  20249. return null;
  20250. };
  20251. BaseTexture.prototype._rebuild = function () {
  20252. };
  20253. BaseTexture.prototype.delayLoad = function () {
  20254. };
  20255. BaseTexture.prototype.clone = function () {
  20256. return null;
  20257. };
  20258. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20259. get: function () {
  20260. if (!this._texture) {
  20261. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20262. }
  20263. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20264. },
  20265. enumerable: true,
  20266. configurable: true
  20267. });
  20268. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20269. get: function () {
  20270. if (!this._texture) {
  20271. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20272. }
  20273. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20274. },
  20275. enumerable: true,
  20276. configurable: true
  20277. });
  20278. BaseTexture.prototype.readPixels = function (faceIndex) {
  20279. if (faceIndex === void 0) { faceIndex = 0; }
  20280. if (!this._texture) {
  20281. return null;
  20282. }
  20283. var size = this.getSize();
  20284. var engine = this.getScene().getEngine();
  20285. if (this._texture.isCube) {
  20286. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20287. }
  20288. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20289. };
  20290. BaseTexture.prototype.releaseInternalTexture = function () {
  20291. if (this._texture) {
  20292. this._texture.dispose();
  20293. this._texture = null;
  20294. }
  20295. };
  20296. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20297. get: function () {
  20298. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20299. return null;
  20300. }
  20301. if (!this._texture._sphericalPolynomial) {
  20302. this._texture._sphericalPolynomial =
  20303. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20304. }
  20305. return this._texture._sphericalPolynomial;
  20306. },
  20307. set: function (value) {
  20308. if (this._texture) {
  20309. this._texture._sphericalPolynomial = value;
  20310. }
  20311. },
  20312. enumerable: true,
  20313. configurable: true
  20314. });
  20315. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20316. get: function () {
  20317. if (this._texture) {
  20318. return this._texture._lodTextureHigh;
  20319. }
  20320. return null;
  20321. },
  20322. enumerable: true,
  20323. configurable: true
  20324. });
  20325. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20326. get: function () {
  20327. if (this._texture) {
  20328. return this._texture._lodTextureMid;
  20329. }
  20330. return null;
  20331. },
  20332. enumerable: true,
  20333. configurable: true
  20334. });
  20335. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20336. get: function () {
  20337. if (this._texture) {
  20338. return this._texture._lodTextureLow;
  20339. }
  20340. return null;
  20341. },
  20342. enumerable: true,
  20343. configurable: true
  20344. });
  20345. BaseTexture.prototype.dispose = function () {
  20346. // Animations
  20347. this.getScene().stopAnimation(this);
  20348. // Remove from scene
  20349. this._scene._removePendingData(this);
  20350. var index = this._scene.textures.indexOf(this);
  20351. if (index >= 0) {
  20352. this._scene.textures.splice(index, 1);
  20353. }
  20354. if (this._texture === undefined) {
  20355. return;
  20356. }
  20357. // Release
  20358. this.releaseInternalTexture();
  20359. // Callback
  20360. this.onDisposeObservable.notifyObservers(this);
  20361. this.onDisposeObservable.clear();
  20362. };
  20363. BaseTexture.prototype.serialize = function () {
  20364. if (!this.name) {
  20365. return null;
  20366. }
  20367. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20368. // Animations
  20369. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20370. return serializationObject;
  20371. };
  20372. BaseTexture.WhenAllReady = function (textures, callback) {
  20373. var numRemaining = textures.length;
  20374. if (numRemaining === 0) {
  20375. callback();
  20376. return;
  20377. }
  20378. var _loop_1 = function () {
  20379. texture = textures[i];
  20380. if (texture.isReady()) {
  20381. if (--numRemaining === 0) {
  20382. callback();
  20383. }
  20384. }
  20385. else {
  20386. onLoadObservable = texture.onLoadObservable;
  20387. var onLoadCallback_1 = function () {
  20388. onLoadObservable.removeCallback(onLoadCallback_1);
  20389. if (--numRemaining === 0) {
  20390. callback();
  20391. }
  20392. };
  20393. onLoadObservable.add(onLoadCallback_1);
  20394. }
  20395. };
  20396. var texture, onLoadObservable;
  20397. for (var i = 0; i < textures.length; i++) {
  20398. _loop_1();
  20399. }
  20400. };
  20401. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20402. __decorate([
  20403. BABYLON.serialize()
  20404. ], BaseTexture.prototype, "name", void 0);
  20405. __decorate([
  20406. BABYLON.serialize("hasAlpha")
  20407. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20408. __decorate([
  20409. BABYLON.serialize()
  20410. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20411. __decorate([
  20412. BABYLON.serialize()
  20413. ], BaseTexture.prototype, "level", void 0);
  20414. __decorate([
  20415. BABYLON.serialize()
  20416. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20417. __decorate([
  20418. BABYLON.serialize("coordinatesMode")
  20419. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20420. __decorate([
  20421. BABYLON.serialize()
  20422. ], BaseTexture.prototype, "wrapU", void 0);
  20423. __decorate([
  20424. BABYLON.serialize()
  20425. ], BaseTexture.prototype, "wrapV", void 0);
  20426. __decorate([
  20427. BABYLON.serialize()
  20428. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20429. __decorate([
  20430. BABYLON.serialize()
  20431. ], BaseTexture.prototype, "isCube", void 0);
  20432. __decorate([
  20433. BABYLON.serialize()
  20434. ], BaseTexture.prototype, "gammaSpace", void 0);
  20435. __decorate([
  20436. BABYLON.serialize()
  20437. ], BaseTexture.prototype, "invertZ", void 0);
  20438. __decorate([
  20439. BABYLON.serialize()
  20440. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20441. __decorate([
  20442. BABYLON.serialize()
  20443. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20444. __decorate([
  20445. BABYLON.serialize()
  20446. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20447. __decorate([
  20448. BABYLON.serialize()
  20449. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20450. return BaseTexture;
  20451. }());
  20452. BABYLON.BaseTexture = BaseTexture;
  20453. })(BABYLON || (BABYLON = {}));
  20454. //# sourceMappingURL=babylon.baseTexture.js.map
  20455. var BABYLON;
  20456. (function (BABYLON) {
  20457. var Texture = (function (_super) {
  20458. __extends(Texture, _super);
  20459. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20460. if (noMipmap === void 0) { noMipmap = false; }
  20461. if (invertY === void 0) { invertY = true; }
  20462. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20463. if (onLoad === void 0) { onLoad = null; }
  20464. if (onError === void 0) { onError = null; }
  20465. if (buffer === void 0) { buffer = null; }
  20466. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20467. var _this = _super.call(this, scene) || this;
  20468. _this.uOffset = 0;
  20469. _this.vOffset = 0;
  20470. _this.uScale = 1.0;
  20471. _this.vScale = 1.0;
  20472. _this.uAng = 0;
  20473. _this.vAng = 0;
  20474. _this.wAng = 0;
  20475. _this._isBlocking = true;
  20476. _this.name = url;
  20477. _this.url = url;
  20478. _this._noMipmap = noMipmap;
  20479. _this._invertY = invertY;
  20480. _this._samplingMode = samplingMode;
  20481. _this._buffer = buffer;
  20482. _this._deleteBuffer = deleteBuffer;
  20483. _this._format = format;
  20484. scene = _this.getScene();
  20485. var load = function () {
  20486. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20487. _this.onLoadObservable.notifyObservers(_this);
  20488. }
  20489. if (onLoad) {
  20490. onLoad();
  20491. }
  20492. if (!_this.isBlocking) {
  20493. scene.resetCachedMaterial();
  20494. }
  20495. };
  20496. if (!url) {
  20497. _this._delayedOnLoad = load;
  20498. _this._delayedOnError = onError;
  20499. return _this;
  20500. }
  20501. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20502. if (!_this._texture) {
  20503. if (!scene.useDelayedTextureLoading) {
  20504. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20505. if (deleteBuffer) {
  20506. delete _this._buffer;
  20507. }
  20508. }
  20509. else {
  20510. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20511. _this._delayedOnLoad = load;
  20512. _this._delayedOnError = onError;
  20513. }
  20514. }
  20515. else {
  20516. if (_this._texture.isReady) {
  20517. BABYLON.Tools.SetImmediate(function () { return load(); });
  20518. }
  20519. else {
  20520. _this._texture.onLoadedObservable.add(load);
  20521. }
  20522. }
  20523. return _this;
  20524. }
  20525. Object.defineProperty(Texture.prototype, "noMipmap", {
  20526. get: function () {
  20527. return this._noMipmap;
  20528. },
  20529. enumerable: true,
  20530. configurable: true
  20531. });
  20532. Object.defineProperty(Texture.prototype, "isBlocking", {
  20533. get: function () {
  20534. return this._isBlocking;
  20535. },
  20536. set: function (value) {
  20537. this._isBlocking = value;
  20538. },
  20539. enumerable: true,
  20540. configurable: true
  20541. });
  20542. Object.defineProperty(Texture.prototype, "samplingMode", {
  20543. get: function () {
  20544. return this._samplingMode;
  20545. },
  20546. enumerable: true,
  20547. configurable: true
  20548. });
  20549. Texture.prototype.updateURL = function (url) {
  20550. this.url = url;
  20551. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20552. this.delayLoad();
  20553. };
  20554. Texture.prototype.delayLoad = function () {
  20555. var _this = this;
  20556. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20557. return;
  20558. }
  20559. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20560. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20561. if (!this._texture) {
  20562. 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);
  20563. if (this._deleteBuffer) {
  20564. delete this._buffer;
  20565. }
  20566. }
  20567. else {
  20568. if (this._texture.isReady) {
  20569. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20570. }
  20571. else {
  20572. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  20573. }
  20574. }
  20575. };
  20576. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20577. if (!this._texture) {
  20578. return;
  20579. }
  20580. this._samplingMode = samplingMode;
  20581. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20582. };
  20583. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20584. x *= this.uScale;
  20585. y *= this.vScale;
  20586. x -= 0.5 * this.uScale;
  20587. y -= 0.5 * this.vScale;
  20588. z -= 0.5;
  20589. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20590. t.x += 0.5 * this.uScale + this.uOffset;
  20591. t.y += 0.5 * this.vScale + this.vOffset;
  20592. t.z += 0.5;
  20593. };
  20594. Texture.prototype.getTextureMatrix = function () {
  20595. var _this = this;
  20596. if (this.uOffset === this._cachedUOffset &&
  20597. this.vOffset === this._cachedVOffset &&
  20598. this.uScale === this._cachedUScale &&
  20599. this.vScale === this._cachedVScale &&
  20600. this.uAng === this._cachedUAng &&
  20601. this.vAng === this._cachedVAng &&
  20602. this.wAng === this._cachedWAng) {
  20603. return this._cachedTextureMatrix;
  20604. }
  20605. this._cachedUOffset = this.uOffset;
  20606. this._cachedVOffset = this.vOffset;
  20607. this._cachedUScale = this.uScale;
  20608. this._cachedVScale = this.vScale;
  20609. this._cachedUAng = this.uAng;
  20610. this._cachedVAng = this.vAng;
  20611. this._cachedWAng = this.wAng;
  20612. if (!this._cachedTextureMatrix) {
  20613. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20614. this._rowGenerationMatrix = new BABYLON.Matrix();
  20615. this._t0 = BABYLON.Vector3.Zero();
  20616. this._t1 = BABYLON.Vector3.Zero();
  20617. this._t2 = BABYLON.Vector3.Zero();
  20618. }
  20619. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20620. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20621. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20622. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20623. this._t1.subtractInPlace(this._t0);
  20624. this._t2.subtractInPlace(this._t0);
  20625. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20626. this._cachedTextureMatrix.m[0] = this._t1.x;
  20627. this._cachedTextureMatrix.m[1] = this._t1.y;
  20628. this._cachedTextureMatrix.m[2] = this._t1.z;
  20629. this._cachedTextureMatrix.m[4] = this._t2.x;
  20630. this._cachedTextureMatrix.m[5] = this._t2.y;
  20631. this._cachedTextureMatrix.m[6] = this._t2.z;
  20632. this._cachedTextureMatrix.m[8] = this._t0.x;
  20633. this._cachedTextureMatrix.m[9] = this._t0.y;
  20634. this._cachedTextureMatrix.m[10] = this._t0.z;
  20635. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20636. return mat.hasTexture(_this);
  20637. });
  20638. return this._cachedTextureMatrix;
  20639. };
  20640. Texture.prototype.getReflectionTextureMatrix = function () {
  20641. var _this = this;
  20642. var scene = this.getScene();
  20643. if (this.uOffset === this._cachedUOffset &&
  20644. this.vOffset === this._cachedVOffset &&
  20645. this.uScale === this._cachedUScale &&
  20646. this.vScale === this._cachedVScale &&
  20647. this.coordinatesMode === this._cachedCoordinatesMode) {
  20648. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  20649. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  20650. return this._cachedTextureMatrix;
  20651. }
  20652. }
  20653. else {
  20654. return this._cachedTextureMatrix;
  20655. }
  20656. }
  20657. if (!this._cachedTextureMatrix) {
  20658. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20659. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20660. }
  20661. this._cachedUOffset = this.uOffset;
  20662. this._cachedVOffset = this.vOffset;
  20663. this._cachedUScale = this.uScale;
  20664. this._cachedVScale = this.vScale;
  20665. this._cachedCoordinatesMode = this.coordinatesMode;
  20666. switch (this.coordinatesMode) {
  20667. case Texture.PLANAR_MODE:
  20668. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20669. this._cachedTextureMatrix[0] = this.uScale;
  20670. this._cachedTextureMatrix[5] = this.vScale;
  20671. this._cachedTextureMatrix[12] = this.uOffset;
  20672. this._cachedTextureMatrix[13] = this.vOffset;
  20673. break;
  20674. case Texture.PROJECTION_MODE:
  20675. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20676. this._projectionModeMatrix.m[0] = 0.5;
  20677. this._projectionModeMatrix.m[5] = -0.5;
  20678. this._projectionModeMatrix.m[10] = 0.0;
  20679. this._projectionModeMatrix.m[12] = 0.5;
  20680. this._projectionModeMatrix.m[13] = 0.5;
  20681. this._projectionModeMatrix.m[14] = 1.0;
  20682. this._projectionModeMatrix.m[15] = 1.0;
  20683. var projectionMatrix = scene.getProjectionMatrix();
  20684. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  20685. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20686. break;
  20687. default:
  20688. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20689. break;
  20690. }
  20691. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20692. return (mat.getActiveTextures().indexOf(_this) !== -1);
  20693. });
  20694. return this._cachedTextureMatrix;
  20695. };
  20696. Texture.prototype.clone = function () {
  20697. var _this = this;
  20698. return BABYLON.SerializationHelper.Clone(function () {
  20699. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20700. }, this);
  20701. };
  20702. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  20703. get: function () {
  20704. if (!this._onLoadObservable) {
  20705. this._onLoadObservable = new BABYLON.Observable();
  20706. }
  20707. return this._onLoadObservable;
  20708. },
  20709. enumerable: true,
  20710. configurable: true
  20711. });
  20712. Texture.prototype.serialize = function () {
  20713. var serializationObject = _super.prototype.serialize.call(this);
  20714. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  20715. serializationObject.base64String = this._buffer;
  20716. serializationObject.name = serializationObject.name.replace("data:", "");
  20717. }
  20718. return serializationObject;
  20719. };
  20720. Texture.prototype.getClassName = function () {
  20721. return "Texture";
  20722. };
  20723. Texture.prototype.dispose = function () {
  20724. _super.prototype.dispose.call(this);
  20725. if (this.onLoadObservable) {
  20726. this.onLoadObservable.clear();
  20727. this._onLoadObservable = null;
  20728. }
  20729. this._delayedOnLoad = null;
  20730. this._delayedOnError = null;
  20731. };
  20732. // Statics
  20733. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20734. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20735. if (onLoad === void 0) { onLoad = null; }
  20736. if (onError === void 0) { onError = null; }
  20737. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20738. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  20739. };
  20740. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20741. if (parsedTexture.customType) {
  20742. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  20743. // Update Sampling Mode
  20744. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  20745. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  20746. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  20747. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  20748. }
  20749. }
  20750. return parsedCustomTexture;
  20751. }
  20752. if (parsedTexture.isCube) {
  20753. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20754. }
  20755. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20756. return null;
  20757. }
  20758. var texture = BABYLON.SerializationHelper.Parse(function () {
  20759. if (parsedTexture.mirrorPlane) {
  20760. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20761. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20762. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20763. return mirrorTexture;
  20764. }
  20765. else if (parsedTexture.isRenderTarget) {
  20766. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20767. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20768. return renderTargetTexture;
  20769. }
  20770. else {
  20771. var texture;
  20772. if (parsedTexture.base64String) {
  20773. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20774. }
  20775. else {
  20776. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20777. }
  20778. return texture;
  20779. }
  20780. }, parsedTexture, scene);
  20781. // Update Sampling Mode
  20782. if (parsedTexture.samplingMode) {
  20783. var sampling = parsedTexture.samplingMode;
  20784. if (texture._samplingMode !== sampling) {
  20785. texture.updateSamplingMode(sampling);
  20786. }
  20787. }
  20788. // Animations
  20789. if (parsedTexture.animations) {
  20790. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20791. var parsedAnimation = parsedTexture.animations[animationIndex];
  20792. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20793. }
  20794. }
  20795. return texture;
  20796. };
  20797. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20798. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20799. if (noMipmap === void 0) { noMipmap = false; }
  20800. if (invertY === void 0) { invertY = true; }
  20801. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20802. if (onLoad === void 0) { onLoad = null; }
  20803. if (onError === void 0) { onError = null; }
  20804. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20805. if (name.substr(0, 5) !== "data:") {
  20806. name = "data:" + name;
  20807. }
  20808. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  20809. };
  20810. // Constants
  20811. Texture.NEAREST_SAMPLINGMODE = 1;
  20812. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  20813. Texture.BILINEAR_SAMPLINGMODE = 2;
  20814. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  20815. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20816. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  20817. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  20818. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  20819. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  20820. Texture.NEAREST_LINEAR = 7;
  20821. Texture.NEAREST_NEAREST = 8;
  20822. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  20823. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  20824. Texture.LINEAR_LINEAR = 11;
  20825. Texture.LINEAR_NEAREST = 12;
  20826. Texture.EXPLICIT_MODE = 0;
  20827. Texture.SPHERICAL_MODE = 1;
  20828. Texture.PLANAR_MODE = 2;
  20829. Texture.CUBIC_MODE = 3;
  20830. Texture.PROJECTION_MODE = 4;
  20831. Texture.SKYBOX_MODE = 5;
  20832. Texture.INVCUBIC_MODE = 6;
  20833. Texture.EQUIRECTANGULAR_MODE = 7;
  20834. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20835. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  20836. Texture.CLAMP_ADDRESSMODE = 0;
  20837. Texture.WRAP_ADDRESSMODE = 1;
  20838. Texture.MIRROR_ADDRESSMODE = 2;
  20839. __decorate([
  20840. BABYLON.serialize()
  20841. ], Texture.prototype, "url", void 0);
  20842. __decorate([
  20843. BABYLON.serialize()
  20844. ], Texture.prototype, "uOffset", void 0);
  20845. __decorate([
  20846. BABYLON.serialize()
  20847. ], Texture.prototype, "vOffset", void 0);
  20848. __decorate([
  20849. BABYLON.serialize()
  20850. ], Texture.prototype, "uScale", void 0);
  20851. __decorate([
  20852. BABYLON.serialize()
  20853. ], Texture.prototype, "vScale", void 0);
  20854. __decorate([
  20855. BABYLON.serialize()
  20856. ], Texture.prototype, "uAng", void 0);
  20857. __decorate([
  20858. BABYLON.serialize()
  20859. ], Texture.prototype, "vAng", void 0);
  20860. __decorate([
  20861. BABYLON.serialize()
  20862. ], Texture.prototype, "wAng", void 0);
  20863. __decorate([
  20864. BABYLON.serialize()
  20865. ], Texture.prototype, "isBlocking", null);
  20866. return Texture;
  20867. }(BABYLON.BaseTexture));
  20868. BABYLON.Texture = Texture;
  20869. })(BABYLON || (BABYLON = {}));
  20870. //# sourceMappingURL=babylon.texture.js.map
  20871. var BABYLON;
  20872. (function (BABYLON) {
  20873. var _InstancesBatch = (function () {
  20874. function _InstancesBatch() {
  20875. this.mustReturn = false;
  20876. this.visibleInstances = new Array();
  20877. this.renderSelf = new Array();
  20878. }
  20879. return _InstancesBatch;
  20880. }());
  20881. BABYLON._InstancesBatch = _InstancesBatch;
  20882. var Mesh = (function (_super) {
  20883. __extends(Mesh, _super);
  20884. /**
  20885. * @constructor
  20886. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  20887. * @param {Scene} scene The scene to add this mesh to.
  20888. * @param {Node} parent The parent of this mesh, if it has one
  20889. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  20890. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  20891. * When false, achieved by calling a clone(), also passing False.
  20892. * This will make creation of children, recursive.
  20893. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  20894. */
  20895. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  20896. if (parent === void 0) { parent = null; }
  20897. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20898. var _this = _super.call(this, name, scene) || this;
  20899. // Events
  20900. /**
  20901. * An event triggered before rendering the mesh
  20902. * @type {BABYLON.Observable}
  20903. */
  20904. _this.onBeforeRenderObservable = new BABYLON.Observable();
  20905. /**
  20906. * An event triggered after rendering the mesh
  20907. * @type {BABYLON.Observable}
  20908. */
  20909. _this.onAfterRenderObservable = new BABYLON.Observable();
  20910. /**
  20911. * An event triggered before drawing the mesh
  20912. * @type {BABYLON.Observable}
  20913. */
  20914. _this.onBeforeDrawObservable = new BABYLON.Observable();
  20915. // Members
  20916. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20917. _this.instances = new Array();
  20918. _this._LODLevels = new Array();
  20919. _this._visibleInstances = {};
  20920. _this._renderIdForInstances = new Array();
  20921. _this._batchCache = new _InstancesBatch();
  20922. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  20923. _this._sideOrientation = Mesh._DEFAULTSIDE;
  20924. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  20925. // Will be used to save a source mesh reference, If any
  20926. _this._source = null;
  20927. if (source) {
  20928. // Source mesh
  20929. _this._source = source;
  20930. // Geometry
  20931. if (source._geometry) {
  20932. source._geometry.applyToMesh(_this);
  20933. }
  20934. // Deep copy
  20935. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  20936. // Parent
  20937. _this.parent = source.parent;
  20938. // Pivot
  20939. _this.setPivotMatrix(source.getPivotMatrix());
  20940. _this.id = name + "." + source.id;
  20941. // Material
  20942. _this.material = source.material;
  20943. var index;
  20944. if (!doNotCloneChildren) {
  20945. // Children
  20946. for (index = 0; index < scene.meshes.length; index++) {
  20947. var mesh = scene.meshes[index];
  20948. if (mesh.parent === source) {
  20949. // doNotCloneChildren is always going to be False
  20950. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20951. }
  20952. }
  20953. }
  20954. // Physics clone
  20955. var physicsEngine = _this.getScene().getPhysicsEngine();
  20956. if (clonePhysicsImpostor && physicsEngine) {
  20957. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20958. if (impostor) {
  20959. _this.physicsImpostor = impostor.clone(_this);
  20960. }
  20961. }
  20962. // Particles
  20963. for (index = 0; index < scene.particleSystems.length; index++) {
  20964. var system = scene.particleSystems[index];
  20965. if (system.emitter === source) {
  20966. system.clone(system.name, _this);
  20967. }
  20968. }
  20969. _this.computeWorldMatrix(true);
  20970. }
  20971. // Parent
  20972. if (parent !== null) {
  20973. _this.parent = parent;
  20974. }
  20975. return _this;
  20976. }
  20977. Object.defineProperty(Mesh, "FRONTSIDE", {
  20978. /**
  20979. * Mesh side orientation : usually the external or front surface
  20980. */
  20981. get: function () {
  20982. return Mesh._FRONTSIDE;
  20983. },
  20984. enumerable: true,
  20985. configurable: true
  20986. });
  20987. Object.defineProperty(Mesh, "BACKSIDE", {
  20988. /**
  20989. * Mesh side orientation : usually the internal or back surface
  20990. */
  20991. get: function () {
  20992. return Mesh._BACKSIDE;
  20993. },
  20994. enumerable: true,
  20995. configurable: true
  20996. });
  20997. Object.defineProperty(Mesh, "DOUBLESIDE", {
  20998. /**
  20999. * Mesh side orientation : both internal and external or front and back surfaces
  21000. */
  21001. get: function () {
  21002. return Mesh._DOUBLESIDE;
  21003. },
  21004. enumerable: true,
  21005. configurable: true
  21006. });
  21007. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21008. /**
  21009. * Mesh side orientation : by default, `FRONTSIDE`
  21010. */
  21011. get: function () {
  21012. return Mesh._DEFAULTSIDE;
  21013. },
  21014. enumerable: true,
  21015. configurable: true
  21016. });
  21017. Object.defineProperty(Mesh, "NO_CAP", {
  21018. /**
  21019. * Mesh cap setting : no cap
  21020. */
  21021. get: function () {
  21022. return Mesh._NO_CAP;
  21023. },
  21024. enumerable: true,
  21025. configurable: true
  21026. });
  21027. Object.defineProperty(Mesh, "CAP_START", {
  21028. /**
  21029. * Mesh cap setting : one cap at the beginning of the mesh
  21030. */
  21031. get: function () {
  21032. return Mesh._CAP_START;
  21033. },
  21034. enumerable: true,
  21035. configurable: true
  21036. });
  21037. Object.defineProperty(Mesh, "CAP_END", {
  21038. /**
  21039. * Mesh cap setting : one cap at the end of the mesh
  21040. */
  21041. get: function () {
  21042. return Mesh._CAP_END;
  21043. },
  21044. enumerable: true,
  21045. configurable: true
  21046. });
  21047. Object.defineProperty(Mesh, "CAP_ALL", {
  21048. /**
  21049. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21050. */
  21051. get: function () {
  21052. return Mesh._CAP_ALL;
  21053. },
  21054. enumerable: true,
  21055. configurable: true
  21056. });
  21057. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21058. set: function (callback) {
  21059. if (this._onBeforeDrawObserver) {
  21060. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21061. }
  21062. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21063. },
  21064. enumerable: true,
  21065. configurable: true
  21066. });
  21067. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21068. get: function () {
  21069. return this._morphTargetManager;
  21070. },
  21071. set: function (value) {
  21072. if (this._morphTargetManager === value) {
  21073. return;
  21074. }
  21075. this._morphTargetManager = value;
  21076. this._syncGeometryWithMorphTargetManager();
  21077. },
  21078. enumerable: true,
  21079. configurable: true
  21080. });
  21081. Object.defineProperty(Mesh.prototype, "source", {
  21082. get: function () {
  21083. return this._source;
  21084. },
  21085. enumerable: true,
  21086. configurable: true
  21087. });
  21088. // Methods
  21089. /**
  21090. * Returns the string "Mesh".
  21091. */
  21092. Mesh.prototype.getClassName = function () {
  21093. return "Mesh";
  21094. };
  21095. /**
  21096. * Returns a string.
  21097. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21098. */
  21099. Mesh.prototype.toString = function (fullDetails) {
  21100. var ret = _super.prototype.toString.call(this, fullDetails);
  21101. ret += ", n vertices: " + this.getTotalVertices();
  21102. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21103. if (this.animations) {
  21104. for (var i = 0; i < this.animations.length; i++) {
  21105. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21106. }
  21107. }
  21108. if (fullDetails) {
  21109. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21110. }
  21111. return ret;
  21112. };
  21113. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21114. /**
  21115. * True if the mesh has some Levels Of Details (LOD).
  21116. * Returns a boolean.
  21117. */
  21118. get: function () {
  21119. return this._LODLevels.length > 0;
  21120. },
  21121. enumerable: true,
  21122. configurable: true
  21123. });
  21124. Mesh.prototype._sortLODLevels = function () {
  21125. this._LODLevels.sort(function (a, b) {
  21126. if (a.distance < b.distance) {
  21127. return 1;
  21128. }
  21129. if (a.distance > b.distance) {
  21130. return -1;
  21131. }
  21132. return 0;
  21133. });
  21134. };
  21135. /**
  21136. * Add a mesh as LOD level triggered at the given distance.
  21137. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21138. * @param {number} distance The distance from the center of the object to show this level
  21139. * @param {Mesh} mesh The mesh to be added as LOD level
  21140. * @return {Mesh} This mesh (for chaining)
  21141. */
  21142. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21143. if (mesh && mesh._masterMesh) {
  21144. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21145. return this;
  21146. }
  21147. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21148. this._LODLevels.push(level);
  21149. if (mesh) {
  21150. mesh._masterMesh = this;
  21151. }
  21152. this._sortLODLevels();
  21153. return this;
  21154. };
  21155. /**
  21156. * Returns the LOD level mesh at the passed distance or null if not found.
  21157. * It is related to the method `addLODLevel(distance, mesh)`.
  21158. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21159. * Returns an object Mesh or `null`.
  21160. */
  21161. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21162. for (var index = 0; index < this._LODLevels.length; index++) {
  21163. var level = this._LODLevels[index];
  21164. if (level.distance === distance) {
  21165. return level.mesh;
  21166. }
  21167. }
  21168. return null;
  21169. };
  21170. /**
  21171. * Remove a mesh from the LOD array
  21172. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21173. * @param {Mesh} mesh The mesh to be removed.
  21174. * @return {Mesh} This mesh (for chaining)
  21175. */
  21176. Mesh.prototype.removeLODLevel = function (mesh) {
  21177. for (var index = 0; index < this._LODLevels.length; index++) {
  21178. if (this._LODLevels[index].mesh === mesh) {
  21179. this._LODLevels.splice(index, 1);
  21180. if (mesh) {
  21181. mesh._masterMesh = null;
  21182. }
  21183. }
  21184. }
  21185. this._sortLODLevels();
  21186. return this;
  21187. };
  21188. /**
  21189. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21190. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21191. */
  21192. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21193. if (!this._LODLevels || this._LODLevels.length === 0) {
  21194. return this;
  21195. }
  21196. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21197. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21198. if (this.onLODLevelSelection) {
  21199. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21200. }
  21201. return this;
  21202. }
  21203. for (var index = 0; index < this._LODLevels.length; index++) {
  21204. var level = this._LODLevels[index];
  21205. if (level.distance < distanceToCamera) {
  21206. if (level.mesh) {
  21207. level.mesh._preActivate();
  21208. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21209. }
  21210. if (this.onLODLevelSelection) {
  21211. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21212. }
  21213. return level.mesh;
  21214. }
  21215. }
  21216. if (this.onLODLevelSelection) {
  21217. this.onLODLevelSelection(distanceToCamera, this, this);
  21218. }
  21219. return this;
  21220. };
  21221. Object.defineProperty(Mesh.prototype, "geometry", {
  21222. /**
  21223. * Returns the mesh internal Geometry object.
  21224. */
  21225. get: function () {
  21226. return this._geometry;
  21227. },
  21228. enumerable: true,
  21229. configurable: true
  21230. });
  21231. /**
  21232. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21233. */
  21234. Mesh.prototype.getTotalVertices = function () {
  21235. if (!this._geometry) {
  21236. return 0;
  21237. }
  21238. return this._geometry.getTotalVertices();
  21239. };
  21240. /**
  21241. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21242. * 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.
  21243. * You can force the copy with forceCopy === true
  21244. * Returns null if the mesh has no geometry or no vertex buffer.
  21245. * Possible `kind` values :
  21246. * - BABYLON.VertexBuffer.PositionKind
  21247. * - BABYLON.VertexBuffer.UVKind
  21248. * - BABYLON.VertexBuffer.UV2Kind
  21249. * - BABYLON.VertexBuffer.UV3Kind
  21250. * - BABYLON.VertexBuffer.UV4Kind
  21251. * - BABYLON.VertexBuffer.UV5Kind
  21252. * - BABYLON.VertexBuffer.UV6Kind
  21253. * - BABYLON.VertexBuffer.ColorKind
  21254. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21255. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21256. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21257. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21258. */
  21259. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21260. if (!this._geometry) {
  21261. return null;
  21262. }
  21263. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21264. };
  21265. /**
  21266. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21267. * Returns `undefined` if the mesh has no geometry.
  21268. * Possible `kind` values :
  21269. * - BABYLON.VertexBuffer.PositionKind
  21270. * - BABYLON.VertexBuffer.UVKind
  21271. * - BABYLON.VertexBuffer.UV2Kind
  21272. * - BABYLON.VertexBuffer.UV3Kind
  21273. * - BABYLON.VertexBuffer.UV4Kind
  21274. * - BABYLON.VertexBuffer.UV5Kind
  21275. * - BABYLON.VertexBuffer.UV6Kind
  21276. * - BABYLON.VertexBuffer.ColorKind
  21277. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21278. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21279. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21280. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21281. */
  21282. Mesh.prototype.getVertexBuffer = function (kind) {
  21283. if (!this._geometry) {
  21284. return undefined;
  21285. }
  21286. return this._geometry.getVertexBuffer(kind);
  21287. };
  21288. /**
  21289. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21290. * Possible `kind` values :
  21291. * - BABYLON.VertexBuffer.PositionKind
  21292. * - BABYLON.VertexBuffer.UVKind
  21293. * - BABYLON.VertexBuffer.UV2Kind
  21294. * - BABYLON.VertexBuffer.UV3Kind
  21295. * - BABYLON.VertexBuffer.UV4Kind
  21296. * - BABYLON.VertexBuffer.UV5Kind
  21297. * - BABYLON.VertexBuffer.UV6Kind
  21298. * - BABYLON.VertexBuffer.ColorKind
  21299. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21300. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21301. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21302. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21303. */
  21304. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21305. if (!this._geometry) {
  21306. if (this._delayInfo) {
  21307. return this._delayInfo.indexOf(kind) !== -1;
  21308. }
  21309. return false;
  21310. }
  21311. return this._geometry.isVerticesDataPresent(kind);
  21312. };
  21313. /**
  21314. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21315. * Possible `kind` values :
  21316. * - BABYLON.VertexBuffer.PositionKind
  21317. * - BABYLON.VertexBuffer.UVKind
  21318. * - BABYLON.VertexBuffer.UV2Kind
  21319. * - BABYLON.VertexBuffer.UV3Kind
  21320. * - BABYLON.VertexBuffer.UV4Kind
  21321. * - BABYLON.VertexBuffer.UV5Kind
  21322. * - BABYLON.VertexBuffer.UV6Kind
  21323. * - BABYLON.VertexBuffer.ColorKind
  21324. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21325. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21326. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21327. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21328. */
  21329. Mesh.prototype.getVerticesDataKinds = function () {
  21330. if (!this._geometry) {
  21331. var result = [];
  21332. if (this._delayInfo) {
  21333. this._delayInfo.forEach(function (kind, index, array) {
  21334. result.push(kind);
  21335. });
  21336. }
  21337. return result;
  21338. }
  21339. return this._geometry.getVerticesDataKinds();
  21340. };
  21341. /**
  21342. * Returns a positive integer : the total number of indices in this mesh geometry.
  21343. * Returns zero if the mesh has no geometry.
  21344. */
  21345. Mesh.prototype.getTotalIndices = function () {
  21346. if (!this._geometry) {
  21347. return 0;
  21348. }
  21349. return this._geometry.getTotalIndices();
  21350. };
  21351. /**
  21352. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21353. * 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.
  21354. * Returns an empty array if the mesh has no geometry.
  21355. */
  21356. Mesh.prototype.getIndices = function (copyWhenShared) {
  21357. if (!this._geometry) {
  21358. return [];
  21359. }
  21360. return this._geometry.getIndices(copyWhenShared);
  21361. };
  21362. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21363. get: function () {
  21364. return this._masterMesh !== null && this._masterMesh !== undefined;
  21365. },
  21366. enumerable: true,
  21367. configurable: true
  21368. });
  21369. /**
  21370. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21371. */
  21372. Mesh.prototype.isReady = function () {
  21373. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21374. return false;
  21375. }
  21376. return _super.prototype.isReady.call(this);
  21377. };
  21378. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  21379. get: function () {
  21380. return this._sideOrientation;
  21381. },
  21382. /**
  21383. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  21384. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  21385. */
  21386. set: function (sideO) {
  21387. this._sideOrientation = sideO;
  21388. },
  21389. enumerable: true,
  21390. configurable: true
  21391. });
  21392. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21393. /**
  21394. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21395. * This property is pertinent only for updatable parametric shapes.
  21396. */
  21397. get: function () {
  21398. return this._areNormalsFrozen;
  21399. },
  21400. enumerable: true,
  21401. configurable: true
  21402. });
  21403. /**
  21404. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21405. * It has no effect at all on other shapes.
  21406. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21407. * Returns the Mesh.
  21408. */
  21409. Mesh.prototype.freezeNormals = function () {
  21410. this._areNormalsFrozen = true;
  21411. return this;
  21412. };
  21413. /**
  21414. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21415. * It has no effect at all on other shapes.
  21416. * It reactivates the mesh normals computation if it was previously frozen.
  21417. * Returns the Mesh.
  21418. */
  21419. Mesh.prototype.unfreezeNormals = function () {
  21420. this._areNormalsFrozen = false;
  21421. return this;
  21422. };
  21423. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21424. /**
  21425. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21426. */
  21427. set: function (count) {
  21428. this._overridenInstanceCount = count;
  21429. },
  21430. enumerable: true,
  21431. configurable: true
  21432. });
  21433. // Methods
  21434. Mesh.prototype._preActivate = function () {
  21435. var sceneRenderId = this.getScene().getRenderId();
  21436. if (this._preActivateId === sceneRenderId) {
  21437. return this;
  21438. }
  21439. this._preActivateId = sceneRenderId;
  21440. this._visibleInstances = null;
  21441. return this;
  21442. };
  21443. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21444. if (this._visibleInstances) {
  21445. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21446. }
  21447. return this;
  21448. };
  21449. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21450. if (!this._visibleInstances) {
  21451. this._visibleInstances = {};
  21452. this._visibleInstances.defaultRenderId = renderId;
  21453. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21454. }
  21455. if (!this._visibleInstances[renderId]) {
  21456. this._visibleInstances[renderId] = new Array();
  21457. }
  21458. this._visibleInstances[renderId].push(instance);
  21459. return this;
  21460. };
  21461. /**
  21462. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21463. * This means the mesh underlying bounding box and sphere are recomputed.
  21464. * Returns the Mesh.
  21465. */
  21466. Mesh.prototype.refreshBoundingInfo = function () {
  21467. if (this._boundingInfo.isLocked) {
  21468. return;
  21469. }
  21470. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21471. if (data) {
  21472. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21473. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21474. }
  21475. if (this.subMeshes) {
  21476. for (var index = 0; index < this.subMeshes.length; index++) {
  21477. this.subMeshes[index].refreshBoundingInfo();
  21478. }
  21479. }
  21480. this._updateBoundingInfo();
  21481. return this;
  21482. };
  21483. Mesh.prototype._createGlobalSubMesh = function (force) {
  21484. var totalVertices = this.getTotalVertices();
  21485. if (!totalVertices || !this.getIndices()) {
  21486. return null;
  21487. }
  21488. // Check if we need to recreate the submeshes
  21489. if (this.subMeshes && this.subMeshes.length > 0) {
  21490. var totalIndices = this.getIndices().length;
  21491. var needToRecreate = false;
  21492. if (force) {
  21493. needToRecreate = true;
  21494. }
  21495. else {
  21496. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21497. var submesh = _a[_i];
  21498. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21499. needToRecreate = true;
  21500. break;
  21501. }
  21502. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21503. needToRecreate = true;
  21504. break;
  21505. }
  21506. }
  21507. }
  21508. if (!needToRecreate) {
  21509. return;
  21510. }
  21511. }
  21512. this.releaseSubMeshes();
  21513. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21514. };
  21515. Mesh.prototype.subdivide = function (count) {
  21516. if (count < 1) {
  21517. return;
  21518. }
  21519. var totalIndices = this.getTotalIndices();
  21520. var subdivisionSize = (totalIndices / count) | 0;
  21521. var offset = 0;
  21522. // Ensure that subdivisionSize is a multiple of 3
  21523. while (subdivisionSize % 3 !== 0) {
  21524. subdivisionSize++;
  21525. }
  21526. this.releaseSubMeshes();
  21527. for (var index = 0; index < count; index++) {
  21528. if (offset >= totalIndices) {
  21529. break;
  21530. }
  21531. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21532. offset += subdivisionSize;
  21533. }
  21534. this.synchronizeInstances();
  21535. };
  21536. /**
  21537. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21538. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21539. * The `data` are either a numeric array either a Float32Array.
  21540. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21541. * 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).
  21542. * Note that a new underlying VertexBuffer object is created each call.
  21543. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21544. *
  21545. * Possible `kind` values :
  21546. * - BABYLON.VertexBuffer.PositionKind
  21547. * - BABYLON.VertexBuffer.UVKind
  21548. * - BABYLON.VertexBuffer.UV2Kind
  21549. * - BABYLON.VertexBuffer.UV3Kind
  21550. * - BABYLON.VertexBuffer.UV4Kind
  21551. * - BABYLON.VertexBuffer.UV5Kind
  21552. * - BABYLON.VertexBuffer.UV6Kind
  21553. * - BABYLON.VertexBuffer.ColorKind
  21554. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21555. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21556. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21557. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21558. *
  21559. * Returns the Mesh.
  21560. */
  21561. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21562. if (!this._geometry) {
  21563. var vertexData = new BABYLON.VertexData();
  21564. vertexData.set(data, kind);
  21565. var scene = this.getScene();
  21566. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21567. }
  21568. else {
  21569. this._geometry.setVerticesData(kind, data, updatable, stride);
  21570. }
  21571. return this;
  21572. };
  21573. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21574. if (updatable === void 0) { updatable = true; }
  21575. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21576. return;
  21577. }
  21578. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21579. };
  21580. /**
  21581. * Sets the mesh VertexBuffer.
  21582. * Returns the Mesh.
  21583. */
  21584. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21585. if (!this._geometry) {
  21586. var scene = this.getScene();
  21587. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21588. }
  21589. this._geometry.setVerticesBuffer(buffer);
  21590. return this;
  21591. };
  21592. /**
  21593. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21594. * If the mesh has no geometry, it is simply returned as it is.
  21595. * The `data` are either a numeric array either a Float32Array.
  21596. * No new underlying VertexBuffer object is created.
  21597. * 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.
  21598. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21599. *
  21600. * Possible `kind` values :
  21601. * - BABYLON.VertexBuffer.PositionKind
  21602. * - BABYLON.VertexBuffer.UVKind
  21603. * - BABYLON.VertexBuffer.UV2Kind
  21604. * - BABYLON.VertexBuffer.UV3Kind
  21605. * - BABYLON.VertexBuffer.UV4Kind
  21606. * - BABYLON.VertexBuffer.UV5Kind
  21607. * - BABYLON.VertexBuffer.UV6Kind
  21608. * - BABYLON.VertexBuffer.ColorKind
  21609. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21610. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21611. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21612. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21613. *
  21614. * Returns the Mesh.
  21615. */
  21616. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21617. if (!this._geometry) {
  21618. return;
  21619. }
  21620. if (!makeItUnique) {
  21621. this._geometry.updateVerticesData(kind, data, updateExtends);
  21622. }
  21623. else {
  21624. this.makeGeometryUnique();
  21625. this.updateVerticesData(kind, data, updateExtends, false);
  21626. }
  21627. return this;
  21628. };
  21629. /**
  21630. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21631. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21632. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21633. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21634. * Returns the Mesh.
  21635. */
  21636. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21637. if (computeNormals === void 0) { computeNormals = true; }
  21638. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21639. positionFunction(positions);
  21640. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21641. if (computeNormals) {
  21642. var indices = this.getIndices();
  21643. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21644. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21645. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21646. }
  21647. return this;
  21648. };
  21649. /**
  21650. * Creates a un-shared specific occurence of the geometry for the mesh.
  21651. * Returns the Mesh.
  21652. */
  21653. Mesh.prototype.makeGeometryUnique = function () {
  21654. if (!this._geometry) {
  21655. return;
  21656. }
  21657. var oldGeometry = this._geometry;
  21658. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21659. oldGeometry.releaseForMesh(this, true);
  21660. geometry.applyToMesh(this);
  21661. return this;
  21662. };
  21663. /**
  21664. * Sets the mesh indices.
  21665. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21666. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21667. * This method creates a new index buffer each call.
  21668. * Returns the Mesh.
  21669. */
  21670. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21671. if (!this._geometry) {
  21672. var vertexData = new BABYLON.VertexData();
  21673. vertexData.indices = indices;
  21674. var scene = this.getScene();
  21675. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21676. }
  21677. else {
  21678. this._geometry.setIndices(indices, totalVertices);
  21679. }
  21680. return this;
  21681. };
  21682. /**
  21683. * Invert the geometry to move from a right handed system to a left handed one.
  21684. * Returns the Mesh.
  21685. */
  21686. Mesh.prototype.toLeftHanded = function () {
  21687. if (!this._geometry) {
  21688. return;
  21689. }
  21690. this._geometry.toLeftHanded();
  21691. return this;
  21692. };
  21693. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21694. var engine = this.getScene().getEngine();
  21695. // Wireframe
  21696. var indexToBind;
  21697. if (this._unIndexed) {
  21698. indexToBind = null;
  21699. }
  21700. else {
  21701. switch (fillMode) {
  21702. case BABYLON.Material.PointFillMode:
  21703. indexToBind = null;
  21704. break;
  21705. case BABYLON.Material.WireFrameFillMode:
  21706. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21707. break;
  21708. default:
  21709. case BABYLON.Material.TriangleFillMode:
  21710. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21711. break;
  21712. }
  21713. }
  21714. // VBOs
  21715. this._geometry._bind(effect, indexToBind);
  21716. return this;
  21717. };
  21718. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21719. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21720. return this;
  21721. }
  21722. this.onBeforeDrawObservable.notifyObservers(this);
  21723. var engine = this.getScene().getEngine();
  21724. // Draw order
  21725. switch (fillMode) {
  21726. case BABYLON.Material.PointFillMode:
  21727. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21728. break;
  21729. case BABYLON.Material.WireFrameFillMode:
  21730. if (this._unIndexed) {
  21731. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21732. }
  21733. else {
  21734. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  21735. }
  21736. break;
  21737. default:
  21738. if (this._unIndexed) {
  21739. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21740. }
  21741. else {
  21742. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21743. }
  21744. }
  21745. return this;
  21746. };
  21747. /**
  21748. * Registers for this mesh a javascript function called just before the rendering process.
  21749. * This function is passed the current mesh.
  21750. * Return the Mesh.
  21751. */
  21752. Mesh.prototype.registerBeforeRender = function (func) {
  21753. this.onBeforeRenderObservable.add(func);
  21754. return this;
  21755. };
  21756. /**
  21757. * Disposes a previously registered javascript function called before the rendering.
  21758. * This function is passed the current mesh.
  21759. * Returns the Mesh.
  21760. */
  21761. Mesh.prototype.unregisterBeforeRender = function (func) {
  21762. this.onBeforeRenderObservable.removeCallback(func);
  21763. return this;
  21764. };
  21765. /**
  21766. * Registers for this mesh a javascript function called just after the rendering is complete.
  21767. * This function is passed the current mesh.
  21768. * Returns the Mesh.
  21769. */
  21770. Mesh.prototype.registerAfterRender = function (func) {
  21771. this.onAfterRenderObservable.add(func);
  21772. return this;
  21773. };
  21774. /**
  21775. * Disposes a previously registered javascript function called after the rendering.
  21776. * This function is passed the current mesh.
  21777. * Return the Mesh.
  21778. */
  21779. Mesh.prototype.unregisterAfterRender = function (func) {
  21780. this.onAfterRenderObservable.removeCallback(func);
  21781. return this;
  21782. };
  21783. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21784. var scene = this.getScene();
  21785. this._batchCache.mustReturn = false;
  21786. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21787. this._batchCache.visibleInstances[subMeshId] = null;
  21788. if (this._visibleInstances) {
  21789. var currentRenderId = scene.getRenderId();
  21790. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21791. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21792. var selfRenderId = this._renderId;
  21793. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21794. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21795. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21796. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21797. }
  21798. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21799. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21800. this._batchCache.mustReturn = true;
  21801. return this._batchCache;
  21802. }
  21803. if (currentRenderId !== selfRenderId) {
  21804. this._batchCache.renderSelf[subMeshId] = false;
  21805. }
  21806. }
  21807. this._renderIdForInstances[subMeshId] = currentRenderId;
  21808. }
  21809. return this._batchCache;
  21810. };
  21811. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21812. var visibleInstances = batch.visibleInstances[subMesh._id];
  21813. var matricesCount = visibleInstances.length + 1;
  21814. var bufferSize = matricesCount * 16 * 4;
  21815. var currentInstancesBufferSize = this._instancesBufferSize;
  21816. var instancesBuffer = this._instancesBuffer;
  21817. while (this._instancesBufferSize < bufferSize) {
  21818. this._instancesBufferSize *= 2;
  21819. }
  21820. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21821. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21822. }
  21823. var offset = 0;
  21824. var instancesCount = 0;
  21825. var world = this.getWorldMatrix();
  21826. if (batch.renderSelf[subMesh._id]) {
  21827. world.copyToArray(this._instancesData, offset);
  21828. offset += 16;
  21829. instancesCount++;
  21830. }
  21831. if (visibleInstances) {
  21832. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21833. var instance = visibleInstances[instanceIndex];
  21834. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21835. offset += 16;
  21836. instancesCount++;
  21837. }
  21838. }
  21839. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21840. if (instancesBuffer) {
  21841. instancesBuffer.dispose();
  21842. }
  21843. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21844. this._instancesBuffer = instancesBuffer;
  21845. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21846. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21847. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21848. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21849. }
  21850. else {
  21851. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21852. }
  21853. this._bind(subMesh, effect, fillMode);
  21854. this._draw(subMesh, fillMode, instancesCount);
  21855. engine.unbindInstanceAttributes();
  21856. return this;
  21857. };
  21858. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21859. var scene = this.getScene();
  21860. var engine = scene.getEngine();
  21861. if (hardwareInstancedRendering) {
  21862. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21863. }
  21864. else {
  21865. if (batch.renderSelf[subMesh._id]) {
  21866. // Draw
  21867. if (onBeforeDraw) {
  21868. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21869. }
  21870. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  21871. }
  21872. if (batch.visibleInstances[subMesh._id]) {
  21873. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21874. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21875. // World
  21876. var world = instance.getWorldMatrix();
  21877. if (onBeforeDraw) {
  21878. onBeforeDraw(true, world, effectiveMaterial);
  21879. }
  21880. // Draw
  21881. this._draw(subMesh, fillMode);
  21882. }
  21883. }
  21884. }
  21885. return this;
  21886. };
  21887. /**
  21888. * Triggers the draw call for the mesh.
  21889. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  21890. * Returns the Mesh.
  21891. */
  21892. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  21893. this.checkOcclusionQuery();
  21894. if (this._isOccluded) {
  21895. return;
  21896. }
  21897. var scene = this.getScene();
  21898. // Managing instances
  21899. var batch = this._getInstancesRenderList(subMesh._id);
  21900. if (batch.mustReturn) {
  21901. return this;
  21902. }
  21903. // Checking geometry state
  21904. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21905. return this;
  21906. }
  21907. var callbackIndex;
  21908. this.onBeforeRenderObservable.notifyObservers(this);
  21909. var engine = scene.getEngine();
  21910. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  21911. // Material
  21912. var effectiveMaterial = subMesh.getMaterial();
  21913. if (!effectiveMaterial) {
  21914. return this;
  21915. }
  21916. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21917. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  21918. return this;
  21919. }
  21920. }
  21921. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  21922. return this;
  21923. }
  21924. // Alpha mode
  21925. if (enableAlphaMode) {
  21926. engine.setAlphaMode(effectiveMaterial.alphaMode);
  21927. }
  21928. // Outline - step 1
  21929. var savedDepthWrite = engine.getDepthWrite();
  21930. if (this.renderOutline) {
  21931. engine.setDepthWrite(false);
  21932. scene.getOutlineRenderer().render(subMesh, batch);
  21933. engine.setDepthWrite(savedDepthWrite);
  21934. }
  21935. var effect;
  21936. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21937. effect = subMesh.effect;
  21938. }
  21939. else {
  21940. effect = effectiveMaterial.getEffect();
  21941. }
  21942. effectiveMaterial._preBind(effect);
  21943. // Bind
  21944. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  21945. if (!hardwareInstancedRendering) {
  21946. this._bind(subMesh, effect, fillMode);
  21947. }
  21948. var world = this.getWorldMatrix();
  21949. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21950. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  21951. }
  21952. else {
  21953. effectiveMaterial.bind(world, this);
  21954. }
  21955. // Draw
  21956. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  21957. // Unbind
  21958. effectiveMaterial.unbind();
  21959. // Outline - step 2
  21960. if (this.renderOutline && savedDepthWrite) {
  21961. engine.setDepthWrite(true);
  21962. engine.setColorWrite(false);
  21963. scene.getOutlineRenderer().render(subMesh, batch);
  21964. engine.setColorWrite(true);
  21965. }
  21966. // Overlay
  21967. if (this.renderOverlay) {
  21968. var currentMode = engine.getAlphaMode();
  21969. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21970. scene.getOutlineRenderer().render(subMesh, batch, true);
  21971. engine.setAlphaMode(currentMode);
  21972. }
  21973. this.onAfterRenderObservable.notifyObservers(this);
  21974. return this;
  21975. };
  21976. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  21977. if (isInstance) {
  21978. effectiveMaterial.bindOnlyWorldMatrix(world);
  21979. }
  21980. return this;
  21981. };
  21982. /**
  21983. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  21984. */
  21985. Mesh.prototype.getEmittedParticleSystems = function () {
  21986. var results = new Array();
  21987. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21988. var particleSystem = this.getScene().particleSystems[index];
  21989. if (particleSystem.emitter === this) {
  21990. results.push(particleSystem);
  21991. }
  21992. }
  21993. return results;
  21994. };
  21995. /**
  21996. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  21997. */
  21998. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  21999. var results = new Array();
  22000. var descendants = this.getDescendants();
  22001. descendants.push(this);
  22002. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22003. var particleSystem = this.getScene().particleSystems[index];
  22004. var emitter = particleSystem.emitter;
  22005. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  22006. results.push(particleSystem);
  22007. }
  22008. }
  22009. return results;
  22010. };
  22011. Mesh.prototype._checkDelayState = function () {
  22012. var scene = this.getScene();
  22013. if (this._geometry) {
  22014. this._geometry.load(scene);
  22015. }
  22016. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22017. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22018. this._queueLoad(this, scene);
  22019. }
  22020. return this;
  22021. };
  22022. Mesh.prototype._queueLoad = function (mesh, scene) {
  22023. var _this = this;
  22024. scene._addPendingData(mesh);
  22025. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22026. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22027. if (data instanceof ArrayBuffer) {
  22028. _this._delayLoadingFunction(data, _this);
  22029. }
  22030. else {
  22031. _this._delayLoadingFunction(JSON.parse(data), _this);
  22032. }
  22033. _this.instances.forEach(function (instance) {
  22034. instance._syncSubMeshes();
  22035. });
  22036. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22037. scene._removePendingData(_this);
  22038. }, function () { }, scene.database, getBinaryData);
  22039. return this;
  22040. };
  22041. /**
  22042. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22043. */
  22044. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22045. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22046. return false;
  22047. }
  22048. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22049. return false;
  22050. }
  22051. this._checkDelayState();
  22052. return true;
  22053. };
  22054. /**
  22055. * Sets the mesh material by the material or multiMaterial `id` property.
  22056. * The material `id` is a string identifying the material or the multiMaterial.
  22057. * This method returns the Mesh.
  22058. */
  22059. Mesh.prototype.setMaterialByID = function (id) {
  22060. var materials = this.getScene().materials;
  22061. var index;
  22062. for (index = materials.length - 1; index > -1; index--) {
  22063. if (materials[index].id === id) {
  22064. this.material = materials[index];
  22065. return this;
  22066. }
  22067. }
  22068. // Multi
  22069. var multiMaterials = this.getScene().multiMaterials;
  22070. for (index = multiMaterials.length - 1; index > -1; index--) {
  22071. if (multiMaterials[index].id === id) {
  22072. this.material = multiMaterials[index];
  22073. return this;
  22074. }
  22075. }
  22076. return this;
  22077. };
  22078. /**
  22079. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22080. */
  22081. Mesh.prototype.getAnimatables = function () {
  22082. var results = [];
  22083. if (this.material) {
  22084. results.push(this.material);
  22085. }
  22086. if (this.skeleton) {
  22087. results.push(this.skeleton);
  22088. }
  22089. return results;
  22090. };
  22091. /**
  22092. * Modifies the mesh geometry according to the passed transformation matrix.
  22093. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22094. * The mesh normals are modified accordingly the same transformation.
  22095. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22096. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22097. * Returns the Mesh.
  22098. */
  22099. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22100. // Position
  22101. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22102. return this;
  22103. }
  22104. var submeshes = this.subMeshes.splice(0);
  22105. this._resetPointsArrayCache();
  22106. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22107. var temp = [];
  22108. var index;
  22109. for (index = 0; index < data.length; index += 3) {
  22110. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22111. }
  22112. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22113. // Normals
  22114. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22115. return this;
  22116. }
  22117. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22118. temp = [];
  22119. for (index = 0; index < data.length; index += 3) {
  22120. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22121. }
  22122. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22123. // flip faces?
  22124. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22125. this.flipFaces();
  22126. }
  22127. // Restore submeshes
  22128. this.releaseSubMeshes();
  22129. this.subMeshes = submeshes;
  22130. return this;
  22131. };
  22132. /**
  22133. * Modifies the mesh geometry according to its own current World Matrix.
  22134. * The mesh World Matrix is then reset.
  22135. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22136. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22137. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22138. * Returns the Mesh.
  22139. */
  22140. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22141. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22142. this.scaling.copyFromFloats(1, 1, 1);
  22143. this.position.copyFromFloats(0, 0, 0);
  22144. this.rotation.copyFromFloats(0, 0, 0);
  22145. //only if quaternion is already set
  22146. if (this.rotationQuaternion) {
  22147. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22148. }
  22149. this._worldMatrix = BABYLON.Matrix.Identity();
  22150. return this;
  22151. };
  22152. Object.defineProperty(Mesh.prototype, "_positions", {
  22153. // Cache
  22154. get: function () {
  22155. if (this._geometry) {
  22156. return this._geometry._positions;
  22157. }
  22158. return null;
  22159. },
  22160. enumerable: true,
  22161. configurable: true
  22162. });
  22163. Mesh.prototype._resetPointsArrayCache = function () {
  22164. if (this._geometry) {
  22165. this._geometry._resetPointsArrayCache();
  22166. }
  22167. return this;
  22168. };
  22169. Mesh.prototype._generatePointsArray = function () {
  22170. if (this._geometry) {
  22171. return this._geometry._generatePointsArray();
  22172. }
  22173. return false;
  22174. };
  22175. /**
  22176. * Returns a new Mesh object generated from the current mesh properties.
  22177. * This method must not get confused with createInstance().
  22178. * The parameter `name` is a string, the name given to the new mesh.
  22179. * The optional parameter `newParent` can be any Node object (default `null`).
  22180. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22181. * 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.
  22182. */
  22183. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22184. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22185. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22186. };
  22187. /**
  22188. * Disposes the mesh.
  22189. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22190. */
  22191. Mesh.prototype.dispose = function (doNotRecurse) {
  22192. var _this = this;
  22193. this.morphTargetManager = undefined;
  22194. if (this._geometry) {
  22195. this._geometry.releaseForMesh(this, true);
  22196. }
  22197. // Sources
  22198. var meshes = this.getScene().meshes;
  22199. meshes.forEach(function (mesh) {
  22200. if (mesh._source && mesh._source === _this) {
  22201. mesh._source = null;
  22202. }
  22203. });
  22204. this._source = null;
  22205. // Instances
  22206. if (this._instancesBuffer) {
  22207. this._instancesBuffer.dispose();
  22208. this._instancesBuffer = null;
  22209. }
  22210. while (this.instances.length) {
  22211. this.instances[0].dispose();
  22212. }
  22213. // Highlight layers.
  22214. var highlightLayers = this.getScene().highlightLayers;
  22215. for (var i = 0; i < highlightLayers.length; i++) {
  22216. var highlightLayer = highlightLayers[i];
  22217. if (highlightLayer) {
  22218. highlightLayer.removeMesh(this);
  22219. highlightLayer.removeExcludedMesh(this);
  22220. }
  22221. }
  22222. _super.prototype.dispose.call(this, doNotRecurse);
  22223. };
  22224. /**
  22225. * Modifies the mesh geometry according to a displacement map.
  22226. * 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.
  22227. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22228. * This method returns nothing.
  22229. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22230. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22231. * 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.
  22232. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22233. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22234. *
  22235. * Returns the Mesh.
  22236. */
  22237. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22238. var _this = this;
  22239. var scene = this.getScene();
  22240. var onload = function (img) {
  22241. // Getting height map data
  22242. var canvas = document.createElement("canvas");
  22243. var context = canvas.getContext("2d");
  22244. var heightMapWidth = img.width;
  22245. var heightMapHeight = img.height;
  22246. canvas.width = heightMapWidth;
  22247. canvas.height = heightMapHeight;
  22248. context.drawImage(img, 0, 0);
  22249. // Create VertexData from map data
  22250. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22251. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22252. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22253. //execute success callback, if set
  22254. if (onSuccess) {
  22255. onSuccess(_this);
  22256. }
  22257. };
  22258. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22259. return this;
  22260. };
  22261. /**
  22262. * Modifies the mesh geometry according to a displacementMap buffer.
  22263. * 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.
  22264. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22265. * This method returns nothing.
  22266. * 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.
  22267. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22268. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22269. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22270. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22271. *
  22272. * Returns the Mesh.
  22273. */
  22274. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22275. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22276. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22277. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22278. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22279. return this;
  22280. }
  22281. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22282. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22283. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22284. var position = BABYLON.Vector3.Zero();
  22285. var normal = BABYLON.Vector3.Zero();
  22286. var uv = BABYLON.Vector2.Zero();
  22287. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22288. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22289. for (var index = 0; index < positions.length; index += 3) {
  22290. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22291. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22292. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22293. // Compute height
  22294. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22295. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22296. var pos = (u + v * heightMapWidth) * 4;
  22297. var r = buffer[pos] / 255.0;
  22298. var g = buffer[pos + 1] / 255.0;
  22299. var b = buffer[pos + 2] / 255.0;
  22300. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22301. normal.normalize();
  22302. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22303. position = position.add(normal);
  22304. position.toArray(positions, index);
  22305. }
  22306. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22307. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22308. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22309. return this;
  22310. };
  22311. /**
  22312. * Modify the mesh to get a flat shading rendering.
  22313. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22314. * This method returns the Mesh.
  22315. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22316. */
  22317. Mesh.prototype.convertToFlatShadedMesh = function () {
  22318. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22319. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22320. var kinds = this.getVerticesDataKinds();
  22321. var vbs = [];
  22322. var data = [];
  22323. var newdata = [];
  22324. var updatableNormals = false;
  22325. var kindIndex;
  22326. var kind;
  22327. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22328. kind = kinds[kindIndex];
  22329. var vertexBuffer = this.getVertexBuffer(kind);
  22330. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22331. updatableNormals = vertexBuffer.isUpdatable();
  22332. kinds.splice(kindIndex, 1);
  22333. kindIndex--;
  22334. continue;
  22335. }
  22336. vbs[kind] = vertexBuffer;
  22337. data[kind] = vbs[kind].getData();
  22338. newdata[kind] = [];
  22339. }
  22340. // Save previous submeshes
  22341. var previousSubmeshes = this.subMeshes.slice(0);
  22342. var indices = this.getIndices();
  22343. var totalIndices = this.getTotalIndices();
  22344. // Generating unique vertices per face
  22345. var index;
  22346. for (index = 0; index < totalIndices; index++) {
  22347. var vertexIndex = indices[index];
  22348. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22349. kind = kinds[kindIndex];
  22350. var stride = vbs[kind].getStrideSize();
  22351. for (var offset = 0; offset < stride; offset++) {
  22352. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22353. }
  22354. }
  22355. }
  22356. // Updating faces & normal
  22357. var normals = [];
  22358. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22359. for (index = 0; index < totalIndices; index += 3) {
  22360. indices[index] = index;
  22361. indices[index + 1] = index + 1;
  22362. indices[index + 2] = index + 2;
  22363. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22364. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22365. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22366. var p1p2 = p1.subtract(p2);
  22367. var p3p2 = p3.subtract(p2);
  22368. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22369. // Store same normals for every vertex
  22370. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22371. normals.push(normal.x);
  22372. normals.push(normal.y);
  22373. normals.push(normal.z);
  22374. }
  22375. }
  22376. this.setIndices(indices);
  22377. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22378. // Updating vertex buffers
  22379. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22380. kind = kinds[kindIndex];
  22381. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22382. }
  22383. // Updating submeshes
  22384. this.releaseSubMeshes();
  22385. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22386. var previousOne = previousSubmeshes[submeshIndex];
  22387. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22388. }
  22389. this.synchronizeInstances();
  22390. return this;
  22391. };
  22392. /**
  22393. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22394. * In other words, more vertices, no more indices and a single bigger VBO.
  22395. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22396. * Returns the Mesh.
  22397. */
  22398. Mesh.prototype.convertToUnIndexedMesh = function () {
  22399. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22400. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22401. var kinds = this.getVerticesDataKinds();
  22402. var vbs = [];
  22403. var data = [];
  22404. var newdata = [];
  22405. var updatableNormals = false;
  22406. var kindIndex;
  22407. var kind;
  22408. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22409. kind = kinds[kindIndex];
  22410. var vertexBuffer = this.getVertexBuffer(kind);
  22411. vbs[kind] = vertexBuffer;
  22412. data[kind] = vbs[kind].getData();
  22413. newdata[kind] = [];
  22414. }
  22415. // Save previous submeshes
  22416. var previousSubmeshes = this.subMeshes.slice(0);
  22417. var indices = this.getIndices();
  22418. var totalIndices = this.getTotalIndices();
  22419. // Generating unique vertices per face
  22420. var index;
  22421. for (index = 0; index < totalIndices; index++) {
  22422. var vertexIndex = indices[index];
  22423. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22424. kind = kinds[kindIndex];
  22425. var stride = vbs[kind].getStrideSize();
  22426. for (var offset = 0; offset < stride; offset++) {
  22427. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22428. }
  22429. }
  22430. }
  22431. // Updating indices
  22432. for (index = 0; index < totalIndices; index += 3) {
  22433. indices[index] = index;
  22434. indices[index + 1] = index + 1;
  22435. indices[index + 2] = index + 2;
  22436. }
  22437. this.setIndices(indices);
  22438. // Updating vertex buffers
  22439. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22440. kind = kinds[kindIndex];
  22441. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22442. }
  22443. // Updating submeshes
  22444. this.releaseSubMeshes();
  22445. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22446. var previousOne = previousSubmeshes[submeshIndex];
  22447. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22448. }
  22449. this._unIndexed = true;
  22450. this.synchronizeInstances();
  22451. return this;
  22452. };
  22453. /**
  22454. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22455. * This method returns the Mesh.
  22456. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22457. */
  22458. Mesh.prototype.flipFaces = function (flipNormals) {
  22459. if (flipNormals === void 0) { flipNormals = false; }
  22460. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22461. var i;
  22462. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22463. for (i = 0; i < vertex_data.normals.length; i++) {
  22464. vertex_data.normals[i] *= -1;
  22465. }
  22466. }
  22467. var temp;
  22468. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22469. // reassign indices
  22470. temp = vertex_data.indices[i + 1];
  22471. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22472. vertex_data.indices[i + 2] = temp;
  22473. }
  22474. vertex_data.applyToMesh(this);
  22475. return this;
  22476. };
  22477. // Instances
  22478. /**
  22479. * Creates a new InstancedMesh object from the mesh model.
  22480. * An instance shares the same properties and the same material than its model.
  22481. * Only these properties of each instance can then be set individually :
  22482. * - position
  22483. * - rotation
  22484. * - rotationQuaternion
  22485. * - setPivotMatrix
  22486. * - scaling
  22487. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22488. * Warning : this method is not supported for Line mesh and LineSystem
  22489. */
  22490. Mesh.prototype.createInstance = function (name) {
  22491. return new BABYLON.InstancedMesh(name, this);
  22492. };
  22493. /**
  22494. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22495. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22496. * This method returns the Mesh.
  22497. */
  22498. Mesh.prototype.synchronizeInstances = function () {
  22499. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22500. var instance = this.instances[instanceIndex];
  22501. instance._syncSubMeshes();
  22502. }
  22503. return this;
  22504. };
  22505. /**
  22506. * Simplify the mesh according to the given array of settings.
  22507. * Function will return immediately and will simplify async. It returns the Mesh.
  22508. * @param settings a collection of simplification settings.
  22509. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22510. * @param type the type of simplification to run.
  22511. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22512. */
  22513. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22514. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22515. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22516. this.getScene().simplificationQueue.addTask({
  22517. settings: settings,
  22518. parallelProcessing: parallelProcessing,
  22519. mesh: this,
  22520. simplificationType: simplificationType,
  22521. successCallback: successCallback
  22522. });
  22523. return this;
  22524. };
  22525. /**
  22526. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22527. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22528. * This should be used together with the simplification to avoid disappearing triangles.
  22529. * Returns the Mesh.
  22530. * @param successCallback an optional success callback to be called after the optimization finished.
  22531. */
  22532. Mesh.prototype.optimizeIndices = function (successCallback) {
  22533. var _this = this;
  22534. var indices = this.getIndices();
  22535. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22536. var vectorPositions = [];
  22537. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22538. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22539. }
  22540. var dupes = [];
  22541. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22542. var realPos = vectorPositions.length - 1 - iteration;
  22543. var testedPosition = vectorPositions[realPos];
  22544. for (var j = 0; j < realPos; ++j) {
  22545. var againstPosition = vectorPositions[j];
  22546. if (testedPosition.equals(againstPosition)) {
  22547. dupes[realPos] = j;
  22548. break;
  22549. }
  22550. }
  22551. }, function () {
  22552. for (var i = 0; i < indices.length; ++i) {
  22553. indices[i] = dupes[indices[i]] || indices[i];
  22554. }
  22555. //indices are now reordered
  22556. var originalSubMeshes = _this.subMeshes.slice(0);
  22557. _this.setIndices(indices);
  22558. _this.subMeshes = originalSubMeshes;
  22559. if (successCallback) {
  22560. successCallback(_this);
  22561. }
  22562. });
  22563. return this;
  22564. };
  22565. Mesh.prototype.serialize = function (serializationObject) {
  22566. serializationObject.name = this.name;
  22567. serializationObject.id = this.id;
  22568. serializationObject.type = this.getClassName();
  22569. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22570. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22571. }
  22572. serializationObject.position = this.position.asArray();
  22573. if (this.rotationQuaternion) {
  22574. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22575. }
  22576. else if (this.rotation) {
  22577. serializationObject.rotation = this.rotation.asArray();
  22578. }
  22579. serializationObject.scaling = this.scaling.asArray();
  22580. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22581. serializationObject.isEnabled = this.isEnabled();
  22582. serializationObject.isVisible = this.isVisible;
  22583. serializationObject.infiniteDistance = this.infiniteDistance;
  22584. serializationObject.pickable = this.isPickable;
  22585. serializationObject.receiveShadows = this.receiveShadows;
  22586. serializationObject.billboardMode = this.billboardMode;
  22587. serializationObject.visibility = this.visibility;
  22588. serializationObject.checkCollisions = this.checkCollisions;
  22589. serializationObject.isBlocker = this.isBlocker;
  22590. // Parent
  22591. if (this.parent) {
  22592. serializationObject.parentId = this.parent.id;
  22593. }
  22594. // Geometry
  22595. var geometry = this._geometry;
  22596. if (geometry) {
  22597. var geometryId = geometry.id;
  22598. serializationObject.geometryId = geometryId;
  22599. // SubMeshes
  22600. serializationObject.subMeshes = [];
  22601. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22602. var subMesh = this.subMeshes[subIndex];
  22603. serializationObject.subMeshes.push({
  22604. materialIndex: subMesh.materialIndex,
  22605. verticesStart: subMesh.verticesStart,
  22606. verticesCount: subMesh.verticesCount,
  22607. indexStart: subMesh.indexStart,
  22608. indexCount: subMesh.indexCount
  22609. });
  22610. }
  22611. }
  22612. // Material
  22613. if (this.material) {
  22614. serializationObject.materialId = this.material.id;
  22615. }
  22616. else {
  22617. this.material = null;
  22618. }
  22619. // Morph targets
  22620. if (this.morphTargetManager) {
  22621. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22622. }
  22623. // Skeleton
  22624. if (this.skeleton) {
  22625. serializationObject.skeletonId = this.skeleton.id;
  22626. }
  22627. // Physics
  22628. //TODO implement correct serialization for physics impostors.
  22629. if (this.getPhysicsImpostor()) {
  22630. var impostor = this.getPhysicsImpostor();
  22631. serializationObject.physicsMass = impostor.getParam("mass");
  22632. serializationObject.physicsFriction = impostor.getParam("friction");
  22633. serializationObject.physicsRestitution = impostor.getParam("mass");
  22634. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  22635. }
  22636. // Metadata
  22637. if (this.metadata) {
  22638. serializationObject.metadata = this.metadata;
  22639. }
  22640. // Instances
  22641. serializationObject.instances = [];
  22642. for (var index = 0; index < this.instances.length; index++) {
  22643. var instance = this.instances[index];
  22644. var serializationInstance = {
  22645. name: instance.name,
  22646. position: instance.position.asArray(),
  22647. scaling: instance.scaling.asArray()
  22648. };
  22649. if (instance.rotationQuaternion) {
  22650. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  22651. }
  22652. else if (instance.rotation) {
  22653. serializationInstance.rotation = instance.rotation.asArray();
  22654. }
  22655. serializationObject.instances.push(serializationInstance);
  22656. // Animations
  22657. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  22658. serializationInstance.ranges = instance.serializeAnimationRanges();
  22659. }
  22660. //
  22661. // Animations
  22662. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22663. serializationObject.ranges = this.serializeAnimationRanges();
  22664. // Layer mask
  22665. serializationObject.layerMask = this.layerMask;
  22666. // Alpha
  22667. serializationObject.alphaIndex = this.alphaIndex;
  22668. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  22669. // Overlay
  22670. serializationObject.overlayAlpha = this.overlayAlpha;
  22671. serializationObject.overlayColor = this.overlayColor.asArray();
  22672. serializationObject.renderOverlay = this.renderOverlay;
  22673. // Fog
  22674. serializationObject.applyFog = this.applyFog;
  22675. // Action Manager
  22676. if (this.actionManager) {
  22677. serializationObject.actions = this.actionManager.serialize(this.name);
  22678. }
  22679. };
  22680. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  22681. if (!this.geometry) {
  22682. return;
  22683. }
  22684. this._markSubMeshesAsAttributesDirty();
  22685. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  22686. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  22687. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  22688. this.morphTargetManager = undefined;
  22689. return;
  22690. }
  22691. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  22692. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  22693. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  22694. if (morphTarget.hasNormals) {
  22695. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  22696. }
  22697. if (morphTarget.hasTangents) {
  22698. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  22699. }
  22700. }
  22701. }
  22702. else {
  22703. var index = 0;
  22704. // Positions
  22705. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  22706. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  22707. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  22708. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  22709. }
  22710. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  22711. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  22712. }
  22713. index++;
  22714. }
  22715. }
  22716. };
  22717. // Statics
  22718. /**
  22719. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22720. * The parameter `parsedMesh` is the mesh to be copied.
  22721. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22722. */
  22723. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22724. var mesh;
  22725. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  22726. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  22727. }
  22728. else {
  22729. mesh = new Mesh(parsedMesh.name, scene);
  22730. }
  22731. mesh.id = parsedMesh.id;
  22732. if (BABYLON.Tags) {
  22733. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  22734. }
  22735. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  22736. if (parsedMesh.metadata !== undefined) {
  22737. mesh.metadata = parsedMesh.metadata;
  22738. }
  22739. if (parsedMesh.rotationQuaternion) {
  22740. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  22741. }
  22742. else if (parsedMesh.rotation) {
  22743. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  22744. }
  22745. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  22746. if (parsedMesh.localMatrix) {
  22747. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  22748. }
  22749. else if (parsedMesh.pivotMatrix) {
  22750. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  22751. }
  22752. mesh.setEnabled(parsedMesh.isEnabled);
  22753. mesh.isVisible = parsedMesh.isVisible;
  22754. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  22755. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  22756. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  22757. if (parsedMesh.applyFog !== undefined) {
  22758. mesh.applyFog = parsedMesh.applyFog;
  22759. }
  22760. if (parsedMesh.pickable !== undefined) {
  22761. mesh.isPickable = parsedMesh.pickable;
  22762. }
  22763. if (parsedMesh.alphaIndex !== undefined) {
  22764. mesh.alphaIndex = parsedMesh.alphaIndex;
  22765. }
  22766. mesh.receiveShadows = parsedMesh.receiveShadows;
  22767. mesh.billboardMode = parsedMesh.billboardMode;
  22768. if (parsedMesh.visibility !== undefined) {
  22769. mesh.visibility = parsedMesh.visibility;
  22770. }
  22771. mesh.checkCollisions = parsedMesh.checkCollisions;
  22772. if (parsedMesh.isBlocker !== undefined) {
  22773. mesh.isBlocker = parsedMesh.isBlocker;
  22774. }
  22775. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  22776. // freezeWorldMatrix
  22777. if (parsedMesh.freezeWorldMatrix) {
  22778. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  22779. }
  22780. // Parent
  22781. if (parsedMesh.parentId) {
  22782. mesh._waitingParentId = parsedMesh.parentId;
  22783. }
  22784. // Actions
  22785. if (parsedMesh.actions !== undefined) {
  22786. mesh._waitingActions = parsedMesh.actions;
  22787. }
  22788. // Overlay
  22789. if (parsedMesh.overlayAlpha !== undefined) {
  22790. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22791. }
  22792. if (parsedMesh.overlayColor !== undefined) {
  22793. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22794. }
  22795. if (parsedMesh.renderOverlay !== undefined) {
  22796. mesh.renderOverlay = parsedMesh.renderOverlay;
  22797. }
  22798. // Geometry
  22799. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22800. if (parsedMesh.delayLoadingFile) {
  22801. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22802. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22803. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22804. if (parsedMesh._binaryInfo) {
  22805. mesh._binaryInfo = parsedMesh._binaryInfo;
  22806. }
  22807. mesh._delayInfo = [];
  22808. if (parsedMesh.hasUVs) {
  22809. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22810. }
  22811. if (parsedMesh.hasUVs2) {
  22812. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22813. }
  22814. if (parsedMesh.hasUVs3) {
  22815. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22816. }
  22817. if (parsedMesh.hasUVs4) {
  22818. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22819. }
  22820. if (parsedMesh.hasUVs5) {
  22821. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22822. }
  22823. if (parsedMesh.hasUVs6) {
  22824. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22825. }
  22826. if (parsedMesh.hasColors) {
  22827. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22828. }
  22829. if (parsedMesh.hasMatricesIndices) {
  22830. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22831. }
  22832. if (parsedMesh.hasMatricesWeights) {
  22833. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22834. }
  22835. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22836. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22837. mesh._checkDelayState();
  22838. }
  22839. }
  22840. else {
  22841. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22842. }
  22843. // Material
  22844. if (parsedMesh.materialId) {
  22845. mesh.setMaterialByID(parsedMesh.materialId);
  22846. }
  22847. else {
  22848. mesh.material = null;
  22849. }
  22850. // Morph targets
  22851. if (parsedMesh.morphTargetManagerId > -1) {
  22852. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  22853. }
  22854. // Skeleton
  22855. if (parsedMesh.skeletonId > -1) {
  22856. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22857. if (parsedMesh.numBoneInfluencers) {
  22858. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22859. }
  22860. }
  22861. // Animations
  22862. if (parsedMesh.animations) {
  22863. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22864. var parsedAnimation = parsedMesh.animations[animationIndex];
  22865. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22866. }
  22867. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  22868. }
  22869. if (parsedMesh.autoAnimate) {
  22870. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  22871. }
  22872. // Layer Mask
  22873. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  22874. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  22875. }
  22876. else {
  22877. mesh.layerMask = 0x0FFFFFFF;
  22878. }
  22879. // Physics
  22880. if (parsedMesh.physicsImpostor) {
  22881. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  22882. mass: parsedMesh.physicsMass,
  22883. friction: parsedMesh.physicsFriction,
  22884. restitution: parsedMesh.physicsRestitution
  22885. }, scene);
  22886. }
  22887. // Instances
  22888. if (parsedMesh.instances) {
  22889. for (var index = 0; index < parsedMesh.instances.length; index++) {
  22890. var parsedInstance = parsedMesh.instances[index];
  22891. var instance = mesh.createInstance(parsedInstance.name);
  22892. if (BABYLON.Tags) {
  22893. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  22894. }
  22895. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  22896. if (parsedInstance.parentId) {
  22897. instance._waitingParentId = parsedInstance.parentId;
  22898. }
  22899. if (parsedInstance.rotationQuaternion) {
  22900. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  22901. }
  22902. else if (parsedInstance.rotation) {
  22903. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  22904. }
  22905. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  22906. instance.checkCollisions = mesh.checkCollisions;
  22907. if (parsedMesh.animations) {
  22908. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22909. parsedAnimation = parsedMesh.animations[animationIndex];
  22910. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22911. }
  22912. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  22913. }
  22914. }
  22915. }
  22916. return mesh;
  22917. };
  22918. /**
  22919. * Creates a ribbon mesh.
  22920. * Please consider using the same method from the MeshBuilder class instead.
  22921. * 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.
  22922. *
  22923. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22924. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22925. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22926. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22927. * 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.
  22928. * 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.
  22929. * 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
  22930. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22931. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22932. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22933. */
  22934. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  22935. return BABYLON.MeshBuilder.CreateRibbon(name, {
  22936. pathArray: pathArray,
  22937. closeArray: closeArray,
  22938. closePath: closePath,
  22939. offset: offset,
  22940. updatable: updatable,
  22941. sideOrientation: sideOrientation,
  22942. instance: instance
  22943. }, scene);
  22944. };
  22945. /**
  22946. * Creates a plane polygonal mesh. By default, this is a disc.
  22947. * Please consider using the same method from the MeshBuilder class instead.
  22948. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22949. * 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.
  22950. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22951. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22952. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22953. */
  22954. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22955. var options = {
  22956. radius: radius,
  22957. tessellation: tessellation,
  22958. sideOrientation: sideOrientation,
  22959. updatable: updatable
  22960. };
  22961. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22962. };
  22963. /**
  22964. * Creates a box mesh.
  22965. * Please consider using the same method from the MeshBuilder class instead.
  22966. * The parameter `size` sets the size (float) of each box side (default 1).
  22967. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22968. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22969. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22970. */
  22971. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22972. var options = {
  22973. size: size,
  22974. sideOrientation: sideOrientation,
  22975. updatable: updatable
  22976. };
  22977. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22978. };
  22979. /**
  22980. * Creates a sphere mesh.
  22981. * Please consider using the same method from the MeshBuilder class instead.
  22982. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22983. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22984. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22985. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22986. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22987. */
  22988. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22989. var options = {
  22990. segments: segments,
  22991. diameterX: diameter,
  22992. diameterY: diameter,
  22993. diameterZ: diameter,
  22994. sideOrientation: sideOrientation,
  22995. updatable: updatable
  22996. };
  22997. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  22998. };
  22999. /**
  23000. * Creates a cylinder or a cone mesh.
  23001. * Please consider using the same method from the MeshBuilder class instead.
  23002. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23003. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23004. * 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.
  23005. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23006. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23007. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23008. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23009. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23010. */
  23011. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23012. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23013. if (scene !== undefined) {
  23014. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23015. updatable = scene;
  23016. }
  23017. scene = subdivisions;
  23018. subdivisions = 1;
  23019. }
  23020. var options = {
  23021. height: height,
  23022. diameterTop: diameterTop,
  23023. diameterBottom: diameterBottom,
  23024. tessellation: tessellation,
  23025. subdivisions: subdivisions,
  23026. sideOrientation: sideOrientation,
  23027. updatable: updatable
  23028. };
  23029. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23030. };
  23031. // Torus (Code from SharpDX.org)
  23032. /**
  23033. * Creates a torus mesh.
  23034. * Please consider using the same method from the MeshBuilder class instead.
  23035. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23036. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23037. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23038. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23039. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23043. var options = {
  23044. diameter: diameter,
  23045. thickness: thickness,
  23046. tessellation: tessellation,
  23047. sideOrientation: sideOrientation,
  23048. updatable: updatable
  23049. };
  23050. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23051. };
  23052. /**
  23053. * Creates a torus knot mesh.
  23054. * Please consider using the same method from the MeshBuilder class instead.
  23055. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23056. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23057. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23058. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23059. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23060. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23064. var options = {
  23065. radius: radius,
  23066. tube: tube,
  23067. radialSegments: radialSegments,
  23068. tubularSegments: tubularSegments,
  23069. p: p,
  23070. q: q,
  23071. sideOrientation: sideOrientation,
  23072. updatable: updatable
  23073. };
  23074. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23075. };
  23076. /**
  23077. * Creates a line mesh.
  23078. * Please consider using the same method from the MeshBuilder class instead.
  23079. * 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.
  23080. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23081. * The parameter `points` is an array successive Vector3.
  23082. * 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
  23083. * When updating an instance, remember that only point positions can change, not the number of points.
  23084. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23085. */
  23086. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23087. var options = {
  23088. points: points,
  23089. updatable: updatable,
  23090. instance: instance
  23091. };
  23092. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23093. };
  23094. /**
  23095. * Creates a dashed line mesh.
  23096. * Please consider using the same method from the MeshBuilder class instead.
  23097. * 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.
  23098. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23099. * The parameter `points` is an array successive Vector3.
  23100. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23101. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23102. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23103. * 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
  23104. * When updating an instance, remember that only point positions can change, not the number of points.
  23105. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23106. */
  23107. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23108. var options = {
  23109. points: points,
  23110. dashSize: dashSize,
  23111. gapSize: gapSize,
  23112. dashNb: dashNb,
  23113. updatable: updatable,
  23114. instance: instance
  23115. };
  23116. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23117. };
  23118. /**
  23119. * Creates a polygon mesh.
  23120. * Please consider using the same method from the MeshBuilder class instead.
  23121. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23122. * 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.
  23123. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23124. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23125. * Remember you can only change the shape positions, not their number when updating a polygon.
  23126. */
  23127. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23128. var options = {
  23129. shape: shape,
  23130. holes: holes,
  23131. updatable: updatable,
  23132. sideOrientation: sideOrientation
  23133. };
  23134. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23135. };
  23136. /**
  23137. * Creates an extruded polygon mesh, with depth in the Y direction.
  23138. * Please consider using the same method from the MeshBuilder class instead.
  23139. */
  23140. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23141. var options = {
  23142. shape: shape,
  23143. holes: holes,
  23144. depth: depth,
  23145. updatable: updatable,
  23146. sideOrientation: sideOrientation
  23147. };
  23148. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23149. };
  23150. /**
  23151. * Creates an extruded shape mesh.
  23152. * 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.
  23153. * Please consider using the same method from the MeshBuilder class instead.
  23154. *
  23155. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23156. * 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
  23157. * extruded along the Z axis.
  23158. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23159. * 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.
  23160. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23161. * 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
  23162. * 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
  23163. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23164. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23165. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23166. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23167. */
  23168. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23169. var options = {
  23170. shape: shape,
  23171. path: path,
  23172. scale: scale,
  23173. rotation: rotation,
  23174. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23175. sideOrientation: sideOrientation,
  23176. instance: instance,
  23177. updatable: updatable
  23178. };
  23179. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23180. };
  23181. /**
  23182. * Creates an custom extruded shape mesh.
  23183. * 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.
  23184. * Please consider using the same method from the MeshBuilder class instead.
  23185. *
  23186. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23187. * 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
  23188. * extruded along the Z axis.
  23189. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23190. * 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
  23191. * and the distance of this point from the begining of the path :
  23192. * ```javascript
  23193. * var rotationFunction = function(i, distance) {
  23194. * // do things
  23195. * return rotationValue; }
  23196. * ```
  23197. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23198. * 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
  23199. * and the distance of this point from the begining of the path :
  23200. * ```javascript
  23201. * var scaleFunction = function(i, distance) {
  23202. * // do things
  23203. * return scaleValue;}
  23204. * ```
  23205. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23206. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23207. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23208. * 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
  23209. * 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
  23210. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23211. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23212. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23213. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23214. */
  23215. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23216. var options = {
  23217. shape: shape,
  23218. path: path,
  23219. scaleFunction: scaleFunction,
  23220. rotationFunction: rotationFunction,
  23221. ribbonCloseArray: ribbonCloseArray,
  23222. ribbonClosePath: ribbonClosePath,
  23223. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23224. sideOrientation: sideOrientation,
  23225. instance: instance,
  23226. updatable: updatable
  23227. };
  23228. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23229. };
  23230. /**
  23231. * Creates lathe mesh.
  23232. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23233. * Please consider using the same method from the MeshBuilder class instead.
  23234. * 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
  23235. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23236. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23237. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23238. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23239. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23240. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23241. */
  23242. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23243. var options = {
  23244. shape: shape,
  23245. radius: radius,
  23246. tessellation: tessellation,
  23247. sideOrientation: sideOrientation,
  23248. updatable: updatable
  23249. };
  23250. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23251. };
  23252. /**
  23253. * Creates a plane mesh.
  23254. * Please consider using the same method from the MeshBuilder class instead.
  23255. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23256. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23257. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23258. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23259. */
  23260. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23261. var options = {
  23262. size: size,
  23263. width: size,
  23264. height: size,
  23265. sideOrientation: sideOrientation,
  23266. updatable: updatable
  23267. };
  23268. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23269. };
  23270. /**
  23271. * Creates a ground mesh.
  23272. * Please consider using the same method from the MeshBuilder class instead.
  23273. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23274. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23275. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23276. */
  23277. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23278. var options = {
  23279. width: width,
  23280. height: height,
  23281. subdivisions: subdivisions,
  23282. updatable: updatable
  23283. };
  23284. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23285. };
  23286. /**
  23287. * Creates a tiled ground mesh.
  23288. * Please consider using the same method from the MeshBuilder class instead.
  23289. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23290. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23291. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23292. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23293. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23294. * numbers of subdivisions on the ground width and height of each tile.
  23295. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23296. */
  23297. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23298. var options = {
  23299. xmin: xmin,
  23300. zmin: zmin,
  23301. xmax: xmax,
  23302. zmax: zmax,
  23303. subdivisions: subdivisions,
  23304. precision: precision,
  23305. updatable: updatable
  23306. };
  23307. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23308. };
  23309. /**
  23310. * Creates a ground mesh from a height map.
  23311. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23312. * Please consider using the same method from the MeshBuilder class instead.
  23313. * The parameter `url` sets the URL of the height map image resource.
  23314. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23315. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23316. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23317. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23318. * 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).
  23319. * This function is passed the newly built mesh :
  23320. * ```javascript
  23321. * function(mesh) { // do things
  23322. * return; }
  23323. * ```
  23324. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23325. */
  23326. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23327. var options = {
  23328. width: width,
  23329. height: height,
  23330. subdivisions: subdivisions,
  23331. minHeight: minHeight,
  23332. maxHeight: maxHeight,
  23333. updatable: updatable,
  23334. onReady: onReady
  23335. };
  23336. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23337. };
  23338. /**
  23339. * Creates a tube mesh.
  23340. * 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.
  23341. * Please consider using the same method from the MeshBuilder class instead.
  23342. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23343. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23344. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23345. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23346. * 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.
  23347. * It must return a radius value (positive float) :
  23348. * ```javascript
  23349. * var radiusFunction = function(i, distance) {
  23350. * // do things
  23351. * return radius; }
  23352. * ```
  23353. * 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
  23354. * 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
  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.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23360. var options = {
  23361. path: path,
  23362. radius: radius,
  23363. tessellation: tessellation,
  23364. radiusFunction: radiusFunction,
  23365. arc: 1,
  23366. cap: cap,
  23367. updatable: updatable,
  23368. sideOrientation: sideOrientation,
  23369. instance: instance
  23370. };
  23371. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23372. };
  23373. /**
  23374. * Creates a polyhedron mesh.
  23375. * Please consider using the same method from the MeshBuilder class instead.
  23376. * 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
  23377. * to choose the wanted type.
  23378. * The parameter `size` (positive float, default 1) sets the polygon size.
  23379. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23380. * 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`.
  23381. * 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
  23382. * 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)`).
  23383. * 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
  23384. * 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.
  23385. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23386. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23387. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23388. */
  23389. Mesh.CreatePolyhedron = function (name, options, scene) {
  23390. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23391. };
  23392. /**
  23393. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23394. * Please consider using the same method from the MeshBuilder class instead.
  23395. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23396. * 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`).
  23397. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23398. * 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.
  23399. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23400. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23401. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23402. */
  23403. Mesh.CreateIcoSphere = function (name, options, scene) {
  23404. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23405. };
  23406. /**
  23407. * Creates a decal mesh.
  23408. * Please consider using the same method from the MeshBuilder class instead.
  23409. * 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.
  23410. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23411. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23412. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23413. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23414. */
  23415. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23416. var options = {
  23417. position: position,
  23418. normal: normal,
  23419. size: size,
  23420. angle: angle
  23421. };
  23422. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23423. };
  23424. // Skeletons
  23425. /**
  23426. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23427. */
  23428. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23429. var source;
  23430. if (!this._sourcePositions) {
  23431. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23432. this._sourcePositions = new Float32Array(source);
  23433. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23434. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23435. }
  23436. }
  23437. return this._sourcePositions;
  23438. };
  23439. /**
  23440. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23441. */
  23442. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23443. var source;
  23444. if (!this._sourceNormals) {
  23445. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23446. this._sourceNormals = new Float32Array(source);
  23447. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23448. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23449. }
  23450. }
  23451. return this._sourceNormals;
  23452. };
  23453. /**
  23454. * Updates the vertex buffer by applying transformation from the bones.
  23455. * Returns the Mesh.
  23456. *
  23457. * @param {skeleton} skeleton to apply
  23458. */
  23459. Mesh.prototype.applySkeleton = function (skeleton) {
  23460. if (!this.geometry) {
  23461. return this;
  23462. }
  23463. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23464. return this;
  23465. }
  23466. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23467. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23468. return this;
  23469. }
  23470. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23471. return this;
  23472. }
  23473. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23474. return this;
  23475. }
  23476. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23477. return this;
  23478. }
  23479. if (!this._sourcePositions) {
  23480. var submeshes = this.subMeshes.slice();
  23481. this.setPositionsForCPUSkinning();
  23482. this.subMeshes = submeshes;
  23483. }
  23484. if (!this._sourceNormals) {
  23485. this.setNormalsForCPUSkinning();
  23486. }
  23487. // positionsData checks for not being Float32Array will only pass at most once
  23488. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23489. if (!(positionsData instanceof Float32Array)) {
  23490. positionsData = new Float32Array(positionsData);
  23491. }
  23492. // normalsData checks for not being Float32Array will only pass at most once
  23493. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23494. if (!(normalsData instanceof Float32Array)) {
  23495. normalsData = new Float32Array(normalsData);
  23496. }
  23497. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23498. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23499. var needExtras = this.numBoneInfluencers > 4;
  23500. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23501. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23502. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23503. var tempVector3 = BABYLON.Vector3.Zero();
  23504. var finalMatrix = new BABYLON.Matrix();
  23505. var tempMatrix = new BABYLON.Matrix();
  23506. var matWeightIdx = 0;
  23507. var inf;
  23508. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23509. var weight;
  23510. for (inf = 0; inf < 4; inf++) {
  23511. weight = matricesWeightsData[matWeightIdx + inf];
  23512. if (weight > 0) {
  23513. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23514. finalMatrix.addToSelf(tempMatrix);
  23515. }
  23516. else
  23517. break;
  23518. }
  23519. if (needExtras) {
  23520. for (inf = 0; inf < 4; inf++) {
  23521. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23522. if (weight > 0) {
  23523. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23524. finalMatrix.addToSelf(tempMatrix);
  23525. }
  23526. else
  23527. break;
  23528. }
  23529. }
  23530. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23531. tempVector3.toArray(positionsData, index);
  23532. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23533. tempVector3.toArray(normalsData, index);
  23534. finalMatrix.reset();
  23535. }
  23536. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23537. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23538. return this;
  23539. };
  23540. // Tools
  23541. /**
  23542. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23543. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23544. */
  23545. Mesh.MinMax = function (meshes) {
  23546. var minVector = null;
  23547. var maxVector = null;
  23548. meshes.forEach(function (mesh, index, array) {
  23549. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23550. if (!minVector) {
  23551. minVector = boundingBox.minimumWorld;
  23552. maxVector = boundingBox.maximumWorld;
  23553. }
  23554. else {
  23555. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23556. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23557. }
  23558. });
  23559. return {
  23560. min: minVector,
  23561. max: maxVector
  23562. };
  23563. };
  23564. /**
  23565. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23566. */
  23567. Mesh.Center = function (meshesOrMinMaxVector) {
  23568. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23569. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23570. };
  23571. /**
  23572. * Merge the array of meshes into a single mesh for performance reasons.
  23573. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23574. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23575. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23576. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23577. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23578. */
  23579. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23580. if (disposeSource === void 0) { disposeSource = true; }
  23581. var index;
  23582. if (!allow32BitsIndices) {
  23583. var totalVertices = 0;
  23584. // Counting vertices
  23585. for (index = 0; index < meshes.length; index++) {
  23586. if (meshes[index]) {
  23587. totalVertices += meshes[index].getTotalVertices();
  23588. if (totalVertices > 65536) {
  23589. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23590. return null;
  23591. }
  23592. }
  23593. }
  23594. }
  23595. // Merge
  23596. var vertexData;
  23597. var otherVertexData;
  23598. var indiceArray = new Array();
  23599. var source;
  23600. for (index = 0; index < meshes.length; index++) {
  23601. if (meshes[index]) {
  23602. meshes[index].computeWorldMatrix(true);
  23603. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23604. otherVertexData.transform(meshes[index].getWorldMatrix());
  23605. if (vertexData) {
  23606. vertexData.merge(otherVertexData);
  23607. }
  23608. else {
  23609. vertexData = otherVertexData;
  23610. source = meshes[index];
  23611. }
  23612. if (subdivideWithSubMeshes) {
  23613. indiceArray.push(meshes[index].getTotalIndices());
  23614. }
  23615. }
  23616. }
  23617. if (!meshSubclass) {
  23618. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23619. }
  23620. vertexData.applyToMesh(meshSubclass);
  23621. // Setting properties
  23622. meshSubclass.material = source.material;
  23623. meshSubclass.checkCollisions = source.checkCollisions;
  23624. // Cleaning
  23625. if (disposeSource) {
  23626. for (index = 0; index < meshes.length; index++) {
  23627. if (meshes[index]) {
  23628. meshes[index].dispose();
  23629. }
  23630. }
  23631. }
  23632. // Subdivide
  23633. if (subdivideWithSubMeshes) {
  23634. //-- Suppresions du submesh global
  23635. meshSubclass.releaseSubMeshes();
  23636. index = 0;
  23637. var offset = 0;
  23638. //-- aplique la subdivision en fonction du tableau d'indices
  23639. while (index < indiceArray.length) {
  23640. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  23641. offset += indiceArray[index];
  23642. index++;
  23643. }
  23644. }
  23645. return meshSubclass;
  23646. };
  23647. // Consts
  23648. Mesh._FRONTSIDE = 0;
  23649. Mesh._BACKSIDE = 1;
  23650. Mesh._DOUBLESIDE = 2;
  23651. Mesh._DEFAULTSIDE = 0;
  23652. Mesh._NO_CAP = 0;
  23653. Mesh._CAP_START = 1;
  23654. Mesh._CAP_END = 2;
  23655. Mesh._CAP_ALL = 3;
  23656. return Mesh;
  23657. }(BABYLON.AbstractMesh));
  23658. BABYLON.Mesh = Mesh;
  23659. })(BABYLON || (BABYLON = {}));
  23660. //# sourceMappingURL=babylon.mesh.js.map
  23661. var BABYLON;
  23662. (function (BABYLON) {
  23663. var BaseSubMesh = (function () {
  23664. function BaseSubMesh() {
  23665. }
  23666. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  23667. get: function () {
  23668. return this._materialEffect;
  23669. },
  23670. enumerable: true,
  23671. configurable: true
  23672. });
  23673. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  23674. if (this._materialEffect === effect) {
  23675. if (!effect) {
  23676. this._materialDefines = undefined;
  23677. }
  23678. return;
  23679. }
  23680. this._materialDefines = defines;
  23681. this._materialEffect = effect;
  23682. };
  23683. return BaseSubMesh;
  23684. }());
  23685. BABYLON.BaseSubMesh = BaseSubMesh;
  23686. var SubMesh = (function (_super) {
  23687. __extends(SubMesh, _super);
  23688. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  23689. if (createBoundingBox === void 0) { createBoundingBox = true; }
  23690. var _this = _super.call(this) || this;
  23691. _this.materialIndex = materialIndex;
  23692. _this.verticesStart = verticesStart;
  23693. _this.verticesCount = verticesCount;
  23694. _this.indexStart = indexStart;
  23695. _this.indexCount = indexCount;
  23696. _this._renderId = 0;
  23697. _this._mesh = mesh;
  23698. _this._renderingMesh = renderingMesh || mesh;
  23699. mesh.subMeshes.push(_this);
  23700. _this._trianglePlanes = [];
  23701. _this._id = mesh.subMeshes.length - 1;
  23702. if (createBoundingBox) {
  23703. _this.refreshBoundingInfo();
  23704. mesh.computeWorldMatrix(true);
  23705. }
  23706. return _this;
  23707. }
  23708. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  23709. get: function () {
  23710. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  23711. },
  23712. enumerable: true,
  23713. configurable: true
  23714. });
  23715. /**
  23716. * Returns the submesh BoudingInfo object.
  23717. */
  23718. SubMesh.prototype.getBoundingInfo = function () {
  23719. if (this.IsGlobal) {
  23720. return this._mesh.getBoundingInfo();
  23721. }
  23722. return this._boundingInfo;
  23723. };
  23724. /**
  23725. * Sets the submesh BoundingInfo.
  23726. * Return the SubMesh.
  23727. */
  23728. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  23729. this._boundingInfo = boundingInfo;
  23730. return this;
  23731. };
  23732. /**
  23733. * Returns the mesh of the current submesh.
  23734. */
  23735. SubMesh.prototype.getMesh = function () {
  23736. return this._mesh;
  23737. };
  23738. /**
  23739. * Returns the rendering mesh of the submesh.
  23740. */
  23741. SubMesh.prototype.getRenderingMesh = function () {
  23742. return this._renderingMesh;
  23743. };
  23744. /**
  23745. * Returns the submesh material.
  23746. */
  23747. SubMesh.prototype.getMaterial = function () {
  23748. var rootMaterial = this._renderingMesh.material;
  23749. if (rootMaterial && rootMaterial.getSubMaterial) {
  23750. var multiMaterial = rootMaterial;
  23751. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  23752. if (this._currentMaterial !== effectiveMaterial) {
  23753. this._currentMaterial = effectiveMaterial;
  23754. this._materialDefines = undefined;
  23755. }
  23756. return effectiveMaterial;
  23757. }
  23758. if (!rootMaterial) {
  23759. return this._mesh.getScene().defaultMaterial;
  23760. }
  23761. return rootMaterial;
  23762. };
  23763. // Methods
  23764. /**
  23765. * Sets a new updated BoundingInfo object to the submesh.
  23766. * Returns the SubMesh.
  23767. */
  23768. SubMesh.prototype.refreshBoundingInfo = function () {
  23769. this._lastColliderWorldVertices = null;
  23770. if (this.IsGlobal) {
  23771. return;
  23772. }
  23773. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23774. if (!data) {
  23775. this._boundingInfo = this._mesh._boundingInfo;
  23776. return;
  23777. }
  23778. var indices = this._renderingMesh.getIndices();
  23779. var extend;
  23780. //is this the only submesh?
  23781. if (this.indexStart === 0 && this.indexCount === indices.length) {
  23782. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  23783. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  23784. }
  23785. else {
  23786. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  23787. }
  23788. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23789. return this;
  23790. };
  23791. SubMesh.prototype._checkCollision = function (collider) {
  23792. return this.getBoundingInfo()._checkCollision(collider);
  23793. };
  23794. /**
  23795. * Updates the submesh BoundingInfo.
  23796. * Returns the Submesh.
  23797. */
  23798. SubMesh.prototype.updateBoundingInfo = function (world) {
  23799. if (!this.getBoundingInfo()) {
  23800. this.refreshBoundingInfo();
  23801. }
  23802. this.getBoundingInfo().update(world);
  23803. return this;
  23804. };
  23805. /**
  23806. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  23807. * Boolean returned.
  23808. */
  23809. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  23810. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  23811. };
  23812. /**
  23813. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  23814. * Boolean returned.
  23815. */
  23816. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  23817. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  23818. };
  23819. /**
  23820. * Renders the submesh.
  23821. * Returns it.
  23822. */
  23823. SubMesh.prototype.render = function (enableAlphaMode) {
  23824. this._renderingMesh.render(this, enableAlphaMode);
  23825. return this;
  23826. };
  23827. /**
  23828. * Returns a new Index Buffer.
  23829. * Type returned : WebGLBuffer.
  23830. */
  23831. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  23832. if (!this._linesIndexBuffer) {
  23833. var linesIndices = [];
  23834. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23835. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  23836. }
  23837. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  23838. this.linesIndexCount = linesIndices.length;
  23839. }
  23840. return this._linesIndexBuffer;
  23841. };
  23842. /**
  23843. * True is the passed Ray intersects the submesh bounding box.
  23844. * Boolean returned.
  23845. */
  23846. SubMesh.prototype.canIntersects = function (ray) {
  23847. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  23848. };
  23849. /**
  23850. * Returns an object IntersectionInfo.
  23851. */
  23852. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  23853. var intersectInfo = null;
  23854. // LineMesh first as it's also a Mesh...
  23855. if (this._mesh instanceof BABYLON.LinesMesh) {
  23856. var lineMesh = this._mesh;
  23857. // Line test
  23858. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  23859. var p0 = positions[indices[index]];
  23860. var p1 = positions[indices[index + 1]];
  23861. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  23862. if (length < 0) {
  23863. continue;
  23864. }
  23865. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  23866. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  23867. if (fastCheck) {
  23868. break;
  23869. }
  23870. }
  23871. }
  23872. }
  23873. else {
  23874. // Triangles test
  23875. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23876. var p0 = positions[indices[index]];
  23877. var p1 = positions[indices[index + 1]];
  23878. var p2 = positions[indices[index + 2]];
  23879. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  23880. if (currentIntersectInfo) {
  23881. if (currentIntersectInfo.distance < 0) {
  23882. continue;
  23883. }
  23884. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  23885. intersectInfo = currentIntersectInfo;
  23886. intersectInfo.faceId = index / 3;
  23887. if (fastCheck) {
  23888. break;
  23889. }
  23890. }
  23891. }
  23892. }
  23893. }
  23894. return intersectInfo;
  23895. };
  23896. SubMesh.prototype._rebuild = function () {
  23897. if (this._linesIndexBuffer) {
  23898. this._linesIndexBuffer = null;
  23899. }
  23900. };
  23901. // Clone
  23902. /**
  23903. * Creates a new Submesh from the passed Mesh.
  23904. */
  23905. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  23906. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  23907. if (!this.IsGlobal) {
  23908. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  23909. }
  23910. return result;
  23911. };
  23912. // Dispose
  23913. /**
  23914. * Disposes the Submesh.
  23915. * Returns nothing.
  23916. */
  23917. SubMesh.prototype.dispose = function () {
  23918. if (this._linesIndexBuffer) {
  23919. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  23920. this._linesIndexBuffer = null;
  23921. }
  23922. // Remove from mesh
  23923. var index = this._mesh.subMeshes.indexOf(this);
  23924. this._mesh.subMeshes.splice(index, 1);
  23925. };
  23926. // Statics
  23927. /**
  23928. * Creates a new Submesh from the passed parameters :
  23929. * - materialIndex (integer) : the index of the main mesh material.
  23930. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  23931. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  23932. * - mesh (Mesh) : the main mesh to create the submesh from.
  23933. * - renderingMesh (optional Mesh) : rendering mesh.
  23934. */
  23935. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  23936. var minVertexIndex = Number.MAX_VALUE;
  23937. var maxVertexIndex = -Number.MAX_VALUE;
  23938. renderingMesh = renderingMesh || mesh;
  23939. var indices = renderingMesh.getIndices();
  23940. for (var index = startIndex; index < startIndex + indexCount; index++) {
  23941. var vertexIndex = indices[index];
  23942. if (vertexIndex < minVertexIndex)
  23943. minVertexIndex = vertexIndex;
  23944. if (vertexIndex > maxVertexIndex)
  23945. maxVertexIndex = vertexIndex;
  23946. }
  23947. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  23948. };
  23949. return SubMesh;
  23950. }(BaseSubMesh));
  23951. BABYLON.SubMesh = SubMesh;
  23952. })(BABYLON || (BABYLON = {}));
  23953. //# sourceMappingURL=babylon.subMesh.js.map
  23954. var BABYLON;
  23955. (function (BABYLON) {
  23956. var EffectFallbacks = (function () {
  23957. function EffectFallbacks() {
  23958. this._defines = {};
  23959. this._currentRank = 32;
  23960. this._maxRank = -1;
  23961. }
  23962. EffectFallbacks.prototype.unBindMesh = function () {
  23963. this._mesh = null;
  23964. };
  23965. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23966. if (!this._defines[rank]) {
  23967. if (rank < this._currentRank) {
  23968. this._currentRank = rank;
  23969. }
  23970. if (rank > this._maxRank) {
  23971. this._maxRank = rank;
  23972. }
  23973. this._defines[rank] = new Array();
  23974. }
  23975. this._defines[rank].push(define);
  23976. };
  23977. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23978. this._meshRank = rank;
  23979. this._mesh = mesh;
  23980. if (rank < this._currentRank) {
  23981. this._currentRank = rank;
  23982. }
  23983. if (rank > this._maxRank) {
  23984. this._maxRank = rank;
  23985. }
  23986. };
  23987. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23988. get: function () {
  23989. return this._currentRank <= this._maxRank;
  23990. },
  23991. enumerable: true,
  23992. configurable: true
  23993. });
  23994. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23995. // First we try to switch to CPU skinning
  23996. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  23997. this._mesh.computeBonesUsingShaders = false;
  23998. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23999. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24000. var scene = this._mesh.getScene();
  24001. for (var index = 0; index < scene.meshes.length; index++) {
  24002. var otherMesh = scene.meshes[index];
  24003. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  24004. otherMesh.computeBonesUsingShaders = false;
  24005. }
  24006. }
  24007. }
  24008. else {
  24009. var currentFallbacks = this._defines[this._currentRank];
  24010. if (currentFallbacks) {
  24011. for (var index = 0; index < currentFallbacks.length; index++) {
  24012. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24013. }
  24014. }
  24015. this._currentRank++;
  24016. }
  24017. return currentDefines;
  24018. };
  24019. return EffectFallbacks;
  24020. }());
  24021. BABYLON.EffectFallbacks = EffectFallbacks;
  24022. var EffectCreationOptions = (function () {
  24023. function EffectCreationOptions() {
  24024. }
  24025. return EffectCreationOptions;
  24026. }());
  24027. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24028. var Effect = (function () {
  24029. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24030. var _this = this;
  24031. this.uniqueId = 0;
  24032. this.onCompileObservable = new BABYLON.Observable();
  24033. this.onErrorObservable = new BABYLON.Observable();
  24034. this.onBindObservable = new BABYLON.Observable();
  24035. this._uniformBuffersNames = {};
  24036. this._isReady = false;
  24037. this._compilationError = "";
  24038. this.name = baseName;
  24039. if (attributesNamesOrOptions.attributes) {
  24040. var options = attributesNamesOrOptions;
  24041. this._engine = uniformsNamesOrEngine;
  24042. this._attributesNames = options.attributes;
  24043. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24044. this._samplers = options.samplers;
  24045. this.defines = options.defines;
  24046. this.onError = options.onError;
  24047. this.onCompiled = options.onCompiled;
  24048. this._fallbacks = options.fallbacks;
  24049. this._indexParameters = options.indexParameters;
  24050. if (options.uniformBuffersNames) {
  24051. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24052. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24053. }
  24054. }
  24055. }
  24056. else {
  24057. this._engine = engine;
  24058. this.defines = defines;
  24059. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24060. this._samplers = samplers;
  24061. this._attributesNames = attributesNamesOrOptions;
  24062. this.onError = onError;
  24063. this.onCompiled = onCompiled;
  24064. this._indexParameters = indexParameters;
  24065. this._fallbacks = fallbacks;
  24066. }
  24067. this.uniqueId = Effect._uniqueIdSeed++;
  24068. var vertexSource;
  24069. var fragmentSource;
  24070. if (baseName.vertexElement) {
  24071. vertexSource = document.getElementById(baseName.vertexElement);
  24072. if (!vertexSource) {
  24073. vertexSource = baseName.vertexElement;
  24074. }
  24075. }
  24076. else {
  24077. vertexSource = baseName.vertex || baseName;
  24078. }
  24079. if (baseName.fragmentElement) {
  24080. fragmentSource = document.getElementById(baseName.fragmentElement);
  24081. if (!fragmentSource) {
  24082. fragmentSource = baseName.fragmentElement;
  24083. }
  24084. }
  24085. else {
  24086. fragmentSource = baseName.fragment || baseName;
  24087. }
  24088. this._loadVertexShader(vertexSource, function (vertexCode) {
  24089. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24090. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24091. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24092. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24093. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24094. if (baseName) {
  24095. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + migratedVertexCode;
  24096. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + migratedFragmentCode;
  24097. }
  24098. else {
  24099. _this._vertexSourceCode = migratedVertexCode;
  24100. _this._fragmentSourceCode = migratedFragmentCode;
  24101. }
  24102. _this._prepareEffect();
  24103. });
  24104. });
  24105. });
  24106. });
  24107. });
  24108. });
  24109. }
  24110. Object.defineProperty(Effect.prototype, "key", {
  24111. get: function () {
  24112. return this._key;
  24113. },
  24114. enumerable: true,
  24115. configurable: true
  24116. });
  24117. // Properties
  24118. Effect.prototype.isReady = function () {
  24119. return this._isReady;
  24120. };
  24121. Effect.prototype.getEngine = function () {
  24122. return this._engine;
  24123. };
  24124. Effect.prototype.getProgram = function () {
  24125. return this._program;
  24126. };
  24127. Effect.prototype.getAttributesNames = function () {
  24128. return this._attributesNames;
  24129. };
  24130. Effect.prototype.getAttributeLocation = function (index) {
  24131. return this._attributes[index];
  24132. };
  24133. Effect.prototype.getAttributeLocationByName = function (name) {
  24134. var index = this._attributesNames.indexOf(name);
  24135. return this._attributes[index];
  24136. };
  24137. Effect.prototype.getAttributesCount = function () {
  24138. return this._attributes.length;
  24139. };
  24140. Effect.prototype.getUniformIndex = function (uniformName) {
  24141. return this._uniformsNames.indexOf(uniformName);
  24142. };
  24143. Effect.prototype.getUniform = function (uniformName) {
  24144. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24145. };
  24146. Effect.prototype.getSamplers = function () {
  24147. return this._samplers;
  24148. };
  24149. Effect.prototype.getCompilationError = function () {
  24150. return this._compilationError;
  24151. };
  24152. // Methods
  24153. Effect.prototype.executeWhenCompiled = function (func) {
  24154. if (this.isReady()) {
  24155. func(this);
  24156. return;
  24157. }
  24158. this.onCompileObservable.add(function (effect) {
  24159. func(effect);
  24160. });
  24161. };
  24162. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24163. // DOM element ?
  24164. if (vertex instanceof HTMLElement) {
  24165. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24166. callback(vertexCode);
  24167. return;
  24168. }
  24169. // Base64 encoded ?
  24170. if (vertex.substr(0, 7) === "base64:") {
  24171. var vertexBinary = window.atob(vertex.substr(7));
  24172. callback(vertexBinary);
  24173. return;
  24174. }
  24175. // Is in local store ?
  24176. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24177. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24178. return;
  24179. }
  24180. var vertexShaderUrl;
  24181. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24182. vertexShaderUrl = vertex;
  24183. }
  24184. else {
  24185. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24186. }
  24187. // Vertex shader
  24188. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24189. };
  24190. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24191. // DOM element ?
  24192. if (fragment instanceof HTMLElement) {
  24193. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24194. callback(fragmentCode);
  24195. return;
  24196. }
  24197. // Base64 encoded ?
  24198. if (fragment.substr(0, 7) === "base64:") {
  24199. var fragmentBinary = window.atob(fragment.substr(7));
  24200. callback(fragmentBinary);
  24201. return;
  24202. }
  24203. // Is in local store ?
  24204. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24205. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24206. return;
  24207. }
  24208. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24209. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24210. return;
  24211. }
  24212. var fragmentShaderUrl;
  24213. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24214. fragmentShaderUrl = fragment;
  24215. }
  24216. else {
  24217. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24218. }
  24219. // Fragment shader
  24220. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24221. };
  24222. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24223. // Rebuild shaders source code
  24224. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24225. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24226. vertexCode = prefix + vertexCode;
  24227. fragmentCode = prefix + fragmentCode;
  24228. // Number lines of shaders source code
  24229. var i = 2;
  24230. var regex = /\n/gm;
  24231. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24232. i = 2;
  24233. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24234. // Dump shaders name and formatted source code
  24235. if (this.name.vertexElement) {
  24236. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24237. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24238. }
  24239. else if (this.name.vertex) {
  24240. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24241. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24242. }
  24243. else {
  24244. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24245. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24246. }
  24247. };
  24248. ;
  24249. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24250. var preparedSourceCode = this._processPrecision(sourceCode);
  24251. if (this._engine.webGLVersion == 1) {
  24252. callback(preparedSourceCode);
  24253. return;
  24254. }
  24255. // Already converted
  24256. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24257. callback(preparedSourceCode.replace("#version 300 es", ""));
  24258. return;
  24259. }
  24260. // Remove extensions
  24261. // #extension GL_OES_standard_derivatives : enable
  24262. // #extension GL_EXT_shader_texture_lod : enable
  24263. // #extension GL_EXT_frag_depth : enable
  24264. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  24265. var result = preparedSourceCode.replace(regex, "");
  24266. // Migrate to GLSL v300
  24267. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24268. result = result.replace(/attribute[ \t]/g, "in ");
  24269. result = result.replace(/[ \t]attribute/g, " in");
  24270. if (isFragment) {
  24271. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  24272. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  24273. result = result.replace(/texture2D\(/g, "texture(");
  24274. result = result.replace(/textureCube\(/g, "texture(");
  24275. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24276. result = result.replace(/gl_FragColor/g, "glFragColor");
  24277. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  24278. }
  24279. callback(result);
  24280. };
  24281. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24282. var _this = this;
  24283. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24284. var match = regex.exec(sourceCode);
  24285. var returnValue = new String(sourceCode);
  24286. while (match != null) {
  24287. var includeFile = match[1];
  24288. // Uniform declaration
  24289. if (includeFile.indexOf("__decl__") !== -1) {
  24290. includeFile = includeFile.replace(/__decl__/, "");
  24291. if (this._engine.webGLVersion != 1) {
  24292. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24293. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24294. }
  24295. includeFile = includeFile + "Declaration";
  24296. }
  24297. if (Effect.IncludesShadersStore[includeFile]) {
  24298. // Substitution
  24299. var includeContent = Effect.IncludesShadersStore[includeFile];
  24300. if (match[2]) {
  24301. var splits = match[3].split(",");
  24302. for (var index = 0; index < splits.length; index += 2) {
  24303. var source = new RegExp(splits[index], "g");
  24304. var dest = splits[index + 1];
  24305. includeContent = includeContent.replace(source, dest);
  24306. }
  24307. }
  24308. if (match[4]) {
  24309. var indexString = match[5];
  24310. if (indexString.indexOf("..") !== -1) {
  24311. var indexSplits = indexString.split("..");
  24312. var minIndex = parseInt(indexSplits[0]);
  24313. var maxIndex = parseInt(indexSplits[1]);
  24314. var sourceIncludeContent = includeContent.slice(0);
  24315. includeContent = "";
  24316. if (isNaN(maxIndex)) {
  24317. maxIndex = this._indexParameters[indexSplits[1]];
  24318. }
  24319. for (var i = minIndex; i < maxIndex; i++) {
  24320. if (this._engine.webGLVersion === 1) {
  24321. // Ubo replacement
  24322. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24323. return p1 + "{X}";
  24324. });
  24325. }
  24326. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24327. }
  24328. }
  24329. else {
  24330. if (this._engine.webGLVersion === 1) {
  24331. // Ubo replacement
  24332. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24333. return p1 + "{X}";
  24334. });
  24335. }
  24336. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24337. }
  24338. }
  24339. // Replace
  24340. returnValue = returnValue.replace(match[0], includeContent);
  24341. }
  24342. else {
  24343. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24344. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24345. Effect.IncludesShadersStore[includeFile] = fileContent;
  24346. _this._processIncludes(returnValue, callback);
  24347. });
  24348. return;
  24349. }
  24350. match = regex.exec(sourceCode);
  24351. }
  24352. callback(returnValue);
  24353. };
  24354. Effect.prototype._processPrecision = function (source) {
  24355. if (source.indexOf("precision highp float") === -1) {
  24356. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24357. source = "precision mediump float;\n" + source;
  24358. }
  24359. else {
  24360. source = "precision highp float;\n" + source;
  24361. }
  24362. }
  24363. else {
  24364. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24365. source = source.replace("precision highp float", "precision mediump float");
  24366. }
  24367. }
  24368. return source;
  24369. };
  24370. Effect.prototype._prepareEffect = function () {
  24371. var attributesNames = this._attributesNames;
  24372. var defines = this.defines;
  24373. var fallbacks = this._fallbacks;
  24374. this._valueCache = {};
  24375. try {
  24376. var engine = this._engine;
  24377. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24378. if (engine.webGLVersion > 1) {
  24379. for (var name in this._uniformBuffersNames) {
  24380. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24381. }
  24382. }
  24383. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24384. this._attributes = engine.getAttributes(this._program, attributesNames);
  24385. var index;
  24386. for (index = 0; index < this._samplers.length; index++) {
  24387. var sampler = this.getUniform(this._samplers[index]);
  24388. if (sampler == null) {
  24389. this._samplers.splice(index, 1);
  24390. index--;
  24391. }
  24392. }
  24393. engine.bindSamplers(this);
  24394. this._compilationError = "";
  24395. this._isReady = true;
  24396. if (this.onCompiled) {
  24397. this.onCompiled(this);
  24398. }
  24399. this.onCompileObservable.notifyObservers(this);
  24400. this.onCompileObservable.clear();
  24401. // Unbind mesh reference in fallbacks
  24402. if (this._fallbacks) {
  24403. this._fallbacks.unBindMesh();
  24404. }
  24405. }
  24406. catch (e) {
  24407. this._compilationError = e.message;
  24408. // Let's go through fallbacks then
  24409. BABYLON.Tools.Error("Unable to compile effect:");
  24410. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24411. return " " + uniform;
  24412. }));
  24413. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24414. return " " + attribute;
  24415. }));
  24416. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24417. BABYLON.Tools.Error("Error: " + this._compilationError);
  24418. if (fallbacks && fallbacks.isMoreFallbacks) {
  24419. BABYLON.Tools.Error("Trying next fallback.");
  24420. this.defines = fallbacks.reduce(this.defines);
  24421. this._prepareEffect();
  24422. }
  24423. else {
  24424. if (this.onError) {
  24425. this.onError(this, this._compilationError);
  24426. }
  24427. this.onErrorObservable.notifyObservers(this);
  24428. this.onErrorObservable.clear();
  24429. // Unbind mesh reference in fallbacks
  24430. if (this._fallbacks) {
  24431. this._fallbacks.unBindMesh();
  24432. }
  24433. }
  24434. }
  24435. };
  24436. Object.defineProperty(Effect.prototype, "isSupported", {
  24437. get: function () {
  24438. return this._compilationError === "";
  24439. },
  24440. enumerable: true,
  24441. configurable: true
  24442. });
  24443. Effect.prototype._bindTexture = function (channel, texture) {
  24444. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24445. };
  24446. Effect.prototype.setTexture = function (channel, texture) {
  24447. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24448. };
  24449. Effect.prototype.setTextureArray = function (channel, textures) {
  24450. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24451. var initialPos = this._samplers.indexOf(channel);
  24452. for (var index = 1; index < textures.length; index++) {
  24453. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24454. }
  24455. }
  24456. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24457. };
  24458. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24459. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24460. };
  24461. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24462. var cache = this._valueCache[uniformName];
  24463. var flag = matrix.updateFlag;
  24464. if (cache !== undefined && cache === flag) {
  24465. return false;
  24466. }
  24467. this._valueCache[uniformName] = flag;
  24468. return true;
  24469. };
  24470. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24471. var cache = this._valueCache[uniformName];
  24472. if (!cache) {
  24473. cache = [x, y];
  24474. this._valueCache[uniformName] = cache;
  24475. return true;
  24476. }
  24477. var changed = false;
  24478. if (cache[0] !== x) {
  24479. cache[0] = x;
  24480. changed = true;
  24481. }
  24482. if (cache[1] !== y) {
  24483. cache[1] = y;
  24484. changed = true;
  24485. }
  24486. return changed;
  24487. };
  24488. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24489. var cache = this._valueCache[uniformName];
  24490. if (!cache) {
  24491. cache = [x, y, z];
  24492. this._valueCache[uniformName] = cache;
  24493. return true;
  24494. }
  24495. var changed = false;
  24496. if (cache[0] !== x) {
  24497. cache[0] = x;
  24498. changed = true;
  24499. }
  24500. if (cache[1] !== y) {
  24501. cache[1] = y;
  24502. changed = true;
  24503. }
  24504. if (cache[2] !== z) {
  24505. cache[2] = z;
  24506. changed = true;
  24507. }
  24508. return changed;
  24509. };
  24510. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24511. var cache = this._valueCache[uniformName];
  24512. if (!cache) {
  24513. cache = [x, y, z, w];
  24514. this._valueCache[uniformName] = cache;
  24515. return true;
  24516. }
  24517. var changed = false;
  24518. if (cache[0] !== x) {
  24519. cache[0] = x;
  24520. changed = true;
  24521. }
  24522. if (cache[1] !== y) {
  24523. cache[1] = y;
  24524. changed = true;
  24525. }
  24526. if (cache[2] !== z) {
  24527. cache[2] = z;
  24528. changed = true;
  24529. }
  24530. if (cache[3] !== w) {
  24531. cache[3] = w;
  24532. changed = true;
  24533. }
  24534. return changed;
  24535. };
  24536. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24537. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24538. return;
  24539. }
  24540. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24541. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24542. };
  24543. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24544. this._engine.bindUniformBlock(this._program, blockName, index);
  24545. };
  24546. Effect.prototype.setIntArray = function (uniformName, array) {
  24547. this._valueCache[uniformName] = null;
  24548. this._engine.setIntArray(this.getUniform(uniformName), array);
  24549. return this;
  24550. };
  24551. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24552. this._valueCache[uniformName] = null;
  24553. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24554. return this;
  24555. };
  24556. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24557. this._valueCache[uniformName] = null;
  24558. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24559. return this;
  24560. };
  24561. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24562. this._valueCache[uniformName] = null;
  24563. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24564. return this;
  24565. };
  24566. Effect.prototype.setFloatArray = function (uniformName, array) {
  24567. this._valueCache[uniformName] = null;
  24568. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24569. return this;
  24570. };
  24571. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24572. this._valueCache[uniformName] = null;
  24573. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24574. return this;
  24575. };
  24576. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24577. this._valueCache[uniformName] = null;
  24578. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24579. return this;
  24580. };
  24581. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24582. this._valueCache[uniformName] = null;
  24583. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24584. return this;
  24585. };
  24586. Effect.prototype.setArray = function (uniformName, array) {
  24587. this._valueCache[uniformName] = null;
  24588. this._engine.setArray(this.getUniform(uniformName), array);
  24589. return this;
  24590. };
  24591. Effect.prototype.setArray2 = function (uniformName, array) {
  24592. this._valueCache[uniformName] = null;
  24593. this._engine.setArray2(this.getUniform(uniformName), array);
  24594. return this;
  24595. };
  24596. Effect.prototype.setArray3 = function (uniformName, array) {
  24597. this._valueCache[uniformName] = null;
  24598. this._engine.setArray3(this.getUniform(uniformName), array);
  24599. return this;
  24600. };
  24601. Effect.prototype.setArray4 = function (uniformName, array) {
  24602. this._valueCache[uniformName] = null;
  24603. this._engine.setArray4(this.getUniform(uniformName), array);
  24604. return this;
  24605. };
  24606. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24607. if (!matrices) {
  24608. return;
  24609. }
  24610. this._valueCache[uniformName] = null;
  24611. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24612. return this;
  24613. };
  24614. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24615. if (this._cacheMatrix(uniformName, matrix)) {
  24616. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24617. }
  24618. return this;
  24619. };
  24620. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24621. this._valueCache[uniformName] = null;
  24622. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24623. return this;
  24624. };
  24625. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24626. this._valueCache[uniformName] = null;
  24627. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24628. return this;
  24629. };
  24630. Effect.prototype.setFloat = function (uniformName, value) {
  24631. var cache = this._valueCache[uniformName];
  24632. if (cache !== undefined && cache === value)
  24633. return this;
  24634. this._valueCache[uniformName] = value;
  24635. this._engine.setFloat(this.getUniform(uniformName), value);
  24636. return this;
  24637. };
  24638. Effect.prototype.setBool = function (uniformName, bool) {
  24639. var cache = this._valueCache[uniformName];
  24640. if (cache !== undefined && cache === bool)
  24641. return this;
  24642. this._valueCache[uniformName] = bool;
  24643. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24644. return this;
  24645. };
  24646. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24647. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24648. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24649. }
  24650. return this;
  24651. };
  24652. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24653. if (this._cacheFloat2(uniformName, x, y)) {
  24654. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24655. }
  24656. return this;
  24657. };
  24658. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24659. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24660. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24661. }
  24662. return this;
  24663. };
  24664. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24665. if (this._cacheFloat3(uniformName, x, y, z)) {
  24666. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24667. }
  24668. return this;
  24669. };
  24670. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24671. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24672. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24673. }
  24674. return this;
  24675. };
  24676. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24677. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24678. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24679. }
  24680. return this;
  24681. };
  24682. Effect.prototype.setColor3 = function (uniformName, color3) {
  24683. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24684. this._engine.setColor3(this.getUniform(uniformName), color3);
  24685. }
  24686. return this;
  24687. };
  24688. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24689. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24690. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24691. }
  24692. return this;
  24693. };
  24694. Effect.ResetCache = function () {
  24695. Effect._baseCache = {};
  24696. };
  24697. Effect._uniqueIdSeed = 0;
  24698. Effect._baseCache = {};
  24699. // Statics
  24700. Effect.ShadersStore = {};
  24701. Effect.IncludesShadersStore = {};
  24702. return Effect;
  24703. }());
  24704. BABYLON.Effect = Effect;
  24705. })(BABYLON || (BABYLON = {}));
  24706. //# sourceMappingURL=babylon.effect.js.map
  24707. var BABYLON;
  24708. (function (BABYLON) {
  24709. var MaterialHelper = (function () {
  24710. function MaterialHelper() {
  24711. }
  24712. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24713. defines._needUVs = true;
  24714. defines[key] = true;
  24715. if (texture.getTextureMatrix().isIdentity(true)) {
  24716. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24717. if (texture.coordinatesIndex === 0) {
  24718. defines["MAINUV1"] = true;
  24719. }
  24720. else {
  24721. defines["MAINUV2"] = true;
  24722. }
  24723. }
  24724. else {
  24725. defines[key + "DIRECTUV"] = 0;
  24726. }
  24727. };
  24728. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24729. var matrix = texture.getTextureMatrix();
  24730. if (!matrix.isIdentity(true)) {
  24731. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  24732. }
  24733. };
  24734. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  24735. if (defines._areMiscDirty) {
  24736. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  24737. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  24738. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  24739. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  24740. }
  24741. };
  24742. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  24743. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  24744. var changed = false;
  24745. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  24746. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  24747. changed = true;
  24748. }
  24749. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  24750. defines["ALPHATEST"] = !defines["ALPHATEST"];
  24751. changed = true;
  24752. }
  24753. if (defines["INSTANCES"] !== useInstances) {
  24754. defines["INSTANCES"] = useInstances;
  24755. changed = true;
  24756. }
  24757. if (changed) {
  24758. defines.markAsUnprocessed();
  24759. }
  24760. };
  24761. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  24762. if (useMorphTargets === void 0) { useMorphTargets = false; }
  24763. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  24764. return false;
  24765. }
  24766. defines._normals = defines._needNormals;
  24767. defines._uvs = defines._needUVs;
  24768. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  24769. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24770. defines["TANGENT"] = true;
  24771. }
  24772. if (defines._needUVs) {
  24773. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  24774. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  24775. }
  24776. else {
  24777. defines["UV1"] = false;
  24778. defines["UV2"] = false;
  24779. }
  24780. if (useVertexColor) {
  24781. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  24782. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  24783. }
  24784. if (useBones) {
  24785. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24786. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  24787. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  24788. }
  24789. else {
  24790. defines["NUM_BONE_INFLUENCERS"] = 0;
  24791. defines["BonesPerMesh"] = 0;
  24792. }
  24793. }
  24794. if (useMorphTargets) {
  24795. if (mesh.morphTargetManager) {
  24796. var manager = mesh.morphTargetManager;
  24797. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  24798. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  24799. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  24800. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  24801. }
  24802. else {
  24803. defines["MORPHTARGETS_TANGENT"] = false;
  24804. defines["MORPHTARGETS_NORMAL"] = false;
  24805. defines["MORPHTARGETS"] = false;
  24806. defines["NUM_MORPH_INFLUENCERS"] = 0;
  24807. }
  24808. }
  24809. return true;
  24810. };
  24811. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  24812. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24813. if (disableLighting === void 0) { disableLighting = false; }
  24814. if (!defines._areLightsDirty) {
  24815. return defines._needNormals;
  24816. }
  24817. var lightIndex = 0;
  24818. var needNormals = false;
  24819. var needRebuild = false;
  24820. var lightmapMode = false;
  24821. var shadowEnabled = false;
  24822. var specularEnabled = false;
  24823. if (scene.lightsEnabled && !disableLighting) {
  24824. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24825. var light = _a[_i];
  24826. needNormals = true;
  24827. if (defines["LIGHT" + lightIndex] === undefined) {
  24828. needRebuild = true;
  24829. }
  24830. defines["LIGHT" + lightIndex] = true;
  24831. defines["SPOTLIGHT" + lightIndex] = false;
  24832. defines["HEMILIGHT" + lightIndex] = false;
  24833. defines["POINTLIGHT" + lightIndex] = false;
  24834. defines["DIRLIGHT" + lightIndex] = false;
  24835. var type;
  24836. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  24837. type = "SPOTLIGHT" + lightIndex;
  24838. }
  24839. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  24840. type = "HEMILIGHT" + lightIndex;
  24841. }
  24842. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  24843. type = "POINTLIGHT" + lightIndex;
  24844. }
  24845. else {
  24846. type = "DIRLIGHT" + lightIndex;
  24847. }
  24848. defines[type] = true;
  24849. // Specular
  24850. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  24851. specularEnabled = true;
  24852. }
  24853. // Shadows
  24854. defines["SHADOW" + lightIndex] = false;
  24855. defines["SHADOWPCF" + lightIndex] = false;
  24856. defines["SHADOWESM" + lightIndex] = false;
  24857. defines["SHADOWCUBE" + lightIndex] = false;
  24858. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  24859. var shadowGenerator = light.getShadowGenerator();
  24860. if (shadowGenerator) {
  24861. shadowEnabled = true;
  24862. shadowGenerator.prepareDefines(defines, lightIndex);
  24863. }
  24864. }
  24865. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24866. lightmapMode = true;
  24867. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24868. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  24869. }
  24870. else {
  24871. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  24872. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  24873. }
  24874. lightIndex++;
  24875. if (lightIndex === maxSimultaneousLights)
  24876. break;
  24877. }
  24878. }
  24879. defines["SPECULARTERM"] = specularEnabled;
  24880. defines["SHADOWS"] = shadowEnabled;
  24881. // Resetting all other lights if any
  24882. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  24883. if (defines["LIGHT" + index] !== undefined) {
  24884. defines["LIGHT" + index] = false;
  24885. defines["HEMILIGHT" + lightIndex] = false;
  24886. defines["POINTLIGHT" + lightIndex] = false;
  24887. defines["DIRLIGHT" + lightIndex] = false;
  24888. defines["SPOTLIGHT" + lightIndex] = false;
  24889. defines["SHADOW" + lightIndex] = false;
  24890. }
  24891. }
  24892. var caps = scene.getEngine().getCaps();
  24893. if (defines["SHADOWFLOAT"] === undefined) {
  24894. needRebuild = true;
  24895. }
  24896. defines["SHADOWFLOAT"] = shadowEnabled &&
  24897. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  24898. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  24899. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  24900. if (needRebuild) {
  24901. defines.rebuild();
  24902. }
  24903. return needNormals;
  24904. };
  24905. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  24906. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24907. var uniformsList, uniformBuffersList, samplersList, defines;
  24908. if (uniformsListOrOptions.uniformsNames) {
  24909. var options = uniformsListOrOptions;
  24910. uniformsList = options.uniformsNames;
  24911. uniformBuffersList = options.uniformBuffersNames;
  24912. samplersList = options.samplers;
  24913. defines = options.defines;
  24914. maxSimultaneousLights = options.maxSimultaneousLights;
  24915. }
  24916. else {
  24917. uniformsList = uniformsListOrOptions;
  24918. }
  24919. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24920. if (!defines["LIGHT" + lightIndex]) {
  24921. break;
  24922. }
  24923. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  24924. if (uniformBuffersList) {
  24925. uniformBuffersList.push("Light" + lightIndex);
  24926. }
  24927. samplersList.push("shadowSampler" + lightIndex);
  24928. }
  24929. if (defines["NUM_MORPH_INFLUENCERS"]) {
  24930. uniformsList.push("morphTargetInfluences");
  24931. }
  24932. };
  24933. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24934. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24935. if (!defines["SHADOWS"]) {
  24936. return;
  24937. }
  24938. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24939. if (!defines["LIGHT" + lightIndex]) {
  24940. break;
  24941. }
  24942. if (lightIndex > 0) {
  24943. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24944. }
  24945. if (defines["SHADOW" + lightIndex]) {
  24946. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24947. }
  24948. if (defines["SHADOWPCF" + lightIndex]) {
  24949. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24950. }
  24951. if (defines["SHADOWESM" + lightIndex]) {
  24952. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  24953. }
  24954. }
  24955. };
  24956. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  24957. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  24958. if (influencers > 0) {
  24959. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  24960. var manager = mesh.morphTargetManager;
  24961. var normal = manager.supportsNormals && defines["NORMAL"];
  24962. var tangent = manager.supportsTangents && defines["TANGENT"];
  24963. for (var index = 0; index < influencers; index++) {
  24964. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  24965. if (normal) {
  24966. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  24967. }
  24968. if (tangent) {
  24969. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  24970. }
  24971. if (attribs.length > maxAttributesCount) {
  24972. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  24973. }
  24974. }
  24975. }
  24976. };
  24977. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24978. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24979. fallbacks.addCPUSkinningFallback(0, mesh);
  24980. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24981. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24982. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24983. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24984. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24985. }
  24986. }
  24987. };
  24988. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24989. if (defines["INSTANCES"]) {
  24990. attribs.push("world0");
  24991. attribs.push("world1");
  24992. attribs.push("world2");
  24993. attribs.push("world3");
  24994. }
  24995. };
  24996. // Bindings
  24997. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  24998. if (light.shadowEnabled && mesh.receiveShadows) {
  24999. var shadowGenerator = light.getShadowGenerator();
  25000. if (shadowGenerator) {
  25001. shadowGenerator.bindShadowLight(lightIndex, effect);
  25002. }
  25003. }
  25004. };
  25005. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25006. light.transferToEffect(effect, lightIndex + "");
  25007. };
  25008. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25009. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25010. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25011. var lightIndex = 0;
  25012. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25013. var light = _a[_i];
  25014. var scaledIntensity = light.getScaledIntensity();
  25015. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25016. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25017. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25018. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25019. if (defines["SPECULARTERM"]) {
  25020. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25021. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25022. }
  25023. // Shadows
  25024. if (scene.shadowsEnabled) {
  25025. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25026. }
  25027. light._uniformBuffer.update();
  25028. lightIndex++;
  25029. if (lightIndex === maxSimultaneousLights)
  25030. break;
  25031. }
  25032. };
  25033. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25034. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25035. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25036. effect.setColor3("vFogColor", scene.fogColor);
  25037. }
  25038. };
  25039. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25040. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25041. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25042. if (matrices) {
  25043. effect.setMatrices("mBones", matrices);
  25044. }
  25045. }
  25046. };
  25047. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25048. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25049. return;
  25050. }
  25051. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25052. };
  25053. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25054. if (defines["LOGARITHMICDEPTH"]) {
  25055. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25056. }
  25057. };
  25058. MaterialHelper.BindClipPlane = function (effect, scene) {
  25059. if (scene.clipPlane) {
  25060. var clipPlane = scene.clipPlane;
  25061. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25062. }
  25063. };
  25064. return MaterialHelper;
  25065. }());
  25066. BABYLON.MaterialHelper = MaterialHelper;
  25067. })(BABYLON || (BABYLON = {}));
  25068. //# sourceMappingURL=babylon.materialHelper.js.map
  25069. var BABYLON;
  25070. (function (BABYLON) {
  25071. var MaterialDefines = (function () {
  25072. function MaterialDefines() {
  25073. this._isDirty = true;
  25074. this._areLightsDirty = true;
  25075. this._areAttributesDirty = true;
  25076. this._areTexturesDirty = true;
  25077. this._areFresnelDirty = true;
  25078. this._areMiscDirty = true;
  25079. this._areImageProcessingDirty = true;
  25080. this._normals = false;
  25081. this._uvs = false;
  25082. this._needNormals = false;
  25083. this._needUVs = false;
  25084. }
  25085. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25086. get: function () {
  25087. return this._isDirty;
  25088. },
  25089. enumerable: true,
  25090. configurable: true
  25091. });
  25092. MaterialDefines.prototype.markAsProcessed = function () {
  25093. this._isDirty = false;
  25094. this._areAttributesDirty = false;
  25095. this._areTexturesDirty = false;
  25096. this._areFresnelDirty = false;
  25097. this._areLightsDirty = false;
  25098. this._areMiscDirty = false;
  25099. this._areImageProcessingDirty = false;
  25100. };
  25101. MaterialDefines.prototype.markAsUnprocessed = function () {
  25102. this._isDirty = true;
  25103. };
  25104. MaterialDefines.prototype.markAllAsDirty = function () {
  25105. this._areTexturesDirty = true;
  25106. this._areAttributesDirty = true;
  25107. this._areLightsDirty = true;
  25108. this._areFresnelDirty = true;
  25109. this._areMiscDirty = true;
  25110. this._areImageProcessingDirty = true;
  25111. this._isDirty = true;
  25112. };
  25113. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25114. this._areImageProcessingDirty = true;
  25115. this._isDirty = true;
  25116. };
  25117. MaterialDefines.prototype.markAsLightDirty = function () {
  25118. this._areLightsDirty = true;
  25119. this._isDirty = true;
  25120. };
  25121. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25122. this._areAttributesDirty = true;
  25123. this._isDirty = true;
  25124. };
  25125. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25126. this._areTexturesDirty = true;
  25127. this._isDirty = true;
  25128. };
  25129. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25130. this._areFresnelDirty = true;
  25131. this._isDirty = true;
  25132. };
  25133. MaterialDefines.prototype.markAsMiscDirty = function () {
  25134. this._areMiscDirty = true;
  25135. this._isDirty = true;
  25136. };
  25137. MaterialDefines.prototype.rebuild = function () {
  25138. if (this._keys) {
  25139. delete this._keys;
  25140. }
  25141. this._keys = [];
  25142. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25143. var key = _a[_i];
  25144. if (key[0] === "_") {
  25145. continue;
  25146. }
  25147. this._keys.push(key);
  25148. }
  25149. };
  25150. MaterialDefines.prototype.isEqual = function (other) {
  25151. if (this._keys.length !== other._keys.length) {
  25152. return false;
  25153. }
  25154. for (var index = 0; index < this._keys.length; index++) {
  25155. var prop = this._keys[index];
  25156. if (this[prop] !== other[prop]) {
  25157. return false;
  25158. }
  25159. }
  25160. return true;
  25161. };
  25162. MaterialDefines.prototype.cloneTo = function (other) {
  25163. if (this._keys.length !== other._keys.length) {
  25164. other._keys = this._keys.slice(0);
  25165. }
  25166. for (var index = 0; index < this._keys.length; index++) {
  25167. var prop = this._keys[index];
  25168. other[prop] = this[prop];
  25169. }
  25170. };
  25171. MaterialDefines.prototype.reset = function () {
  25172. for (var index = 0; index < this._keys.length; index++) {
  25173. var prop = this._keys[index];
  25174. if (typeof (this[prop]) === "number") {
  25175. this[prop] = 0;
  25176. }
  25177. else {
  25178. this[prop] = false;
  25179. }
  25180. }
  25181. };
  25182. MaterialDefines.prototype.toString = function () {
  25183. var result = "";
  25184. for (var index = 0; index < this._keys.length; index++) {
  25185. var prop = this._keys[index];
  25186. var value = this[prop];
  25187. if (typeof (value) === "number") {
  25188. result += "#define " + prop + " " + this[prop] + "\n";
  25189. }
  25190. else if (value) {
  25191. result += "#define " + prop + "\n";
  25192. }
  25193. }
  25194. return result;
  25195. };
  25196. return MaterialDefines;
  25197. }());
  25198. BABYLON.MaterialDefines = MaterialDefines;
  25199. var Material = (function () {
  25200. function Material(name, scene, doNotAdd) {
  25201. this.checkReadyOnEveryCall = false;
  25202. this.checkReadyOnlyOnce = false;
  25203. this.state = "";
  25204. this.alpha = 1.0;
  25205. this._backFaceCulling = true;
  25206. this.doNotSerialize = false;
  25207. this.storeEffectOnSubMeshes = false;
  25208. /**
  25209. * An event triggered when the material is disposed.
  25210. * @type {BABYLON.Observable}
  25211. */
  25212. this.onDisposeObservable = new BABYLON.Observable();
  25213. /**
  25214. * An event triggered when the material is bound.
  25215. * @type {BABYLON.Observable}
  25216. */
  25217. this.onBindObservable = new BABYLON.Observable();
  25218. /**
  25219. * An event triggered when the material is unbound.
  25220. * @type {BABYLON.Observable}
  25221. */
  25222. this.onUnBindObservable = new BABYLON.Observable();
  25223. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25224. this.disableDepthWrite = false;
  25225. this._fogEnabled = true;
  25226. this.pointSize = 1.0;
  25227. this.zOffset = 0;
  25228. this._wasPreviouslyReady = false;
  25229. this._fillMode = Material.TriangleFillMode;
  25230. this.name = name;
  25231. this.id = name || BABYLON.Tools.RandomId();
  25232. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25233. if (this._scene.useRightHandedSystem) {
  25234. this.sideOrientation = Material.ClockWiseSideOrientation;
  25235. }
  25236. else {
  25237. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25238. }
  25239. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25240. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  25241. if (!doNotAdd) {
  25242. this._scene.materials.push(this);
  25243. }
  25244. }
  25245. Object.defineProperty(Material, "TriangleFillMode", {
  25246. get: function () {
  25247. return Material._TriangleFillMode;
  25248. },
  25249. enumerable: true,
  25250. configurable: true
  25251. });
  25252. Object.defineProperty(Material, "WireFrameFillMode", {
  25253. get: function () {
  25254. return Material._WireFrameFillMode;
  25255. },
  25256. enumerable: true,
  25257. configurable: true
  25258. });
  25259. Object.defineProperty(Material, "PointFillMode", {
  25260. get: function () {
  25261. return Material._PointFillMode;
  25262. },
  25263. enumerable: true,
  25264. configurable: true
  25265. });
  25266. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25267. get: function () {
  25268. return Material._ClockWiseSideOrientation;
  25269. },
  25270. enumerable: true,
  25271. configurable: true
  25272. });
  25273. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25274. get: function () {
  25275. return Material._CounterClockWiseSideOrientation;
  25276. },
  25277. enumerable: true,
  25278. configurable: true
  25279. });
  25280. Object.defineProperty(Material, "TextureDirtyFlag", {
  25281. get: function () {
  25282. return Material._TextureDirtyFlag;
  25283. },
  25284. enumerable: true,
  25285. configurable: true
  25286. });
  25287. Object.defineProperty(Material, "LightDirtyFlag", {
  25288. get: function () {
  25289. return Material._LightDirtyFlag;
  25290. },
  25291. enumerable: true,
  25292. configurable: true
  25293. });
  25294. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25295. get: function () {
  25296. return Material._FresnelDirtyFlag;
  25297. },
  25298. enumerable: true,
  25299. configurable: true
  25300. });
  25301. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25302. get: function () {
  25303. return Material._AttributesDirtyFlag;
  25304. },
  25305. enumerable: true,
  25306. configurable: true
  25307. });
  25308. Object.defineProperty(Material, "MiscDirtyFlag", {
  25309. get: function () {
  25310. return Material._MiscDirtyFlag;
  25311. },
  25312. enumerable: true,
  25313. configurable: true
  25314. });
  25315. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25316. get: function () {
  25317. return this._backFaceCulling;
  25318. },
  25319. set: function (value) {
  25320. if (this._backFaceCulling === value) {
  25321. return;
  25322. }
  25323. this._backFaceCulling = value;
  25324. this.markAsDirty(Material.TextureDirtyFlag);
  25325. },
  25326. enumerable: true,
  25327. configurable: true
  25328. });
  25329. Object.defineProperty(Material.prototype, "onDispose", {
  25330. set: function (callback) {
  25331. if (this._onDisposeObserver) {
  25332. this.onDisposeObservable.remove(this._onDisposeObserver);
  25333. }
  25334. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25335. },
  25336. enumerable: true,
  25337. configurable: true
  25338. });
  25339. Object.defineProperty(Material.prototype, "onBind", {
  25340. set: function (callback) {
  25341. if (this._onBindObserver) {
  25342. this.onBindObservable.remove(this._onBindObserver);
  25343. }
  25344. this._onBindObserver = this.onBindObservable.add(callback);
  25345. },
  25346. enumerable: true,
  25347. configurable: true
  25348. });
  25349. Object.defineProperty(Material.prototype, "fogEnabled", {
  25350. get: function () {
  25351. return this._fogEnabled;
  25352. },
  25353. set: function (value) {
  25354. if (this._fogEnabled === value) {
  25355. return;
  25356. }
  25357. this._fogEnabled = value;
  25358. this.markAsDirty(Material.MiscDirtyFlag);
  25359. },
  25360. enumerable: true,
  25361. configurable: true
  25362. });
  25363. Object.defineProperty(Material.prototype, "wireframe", {
  25364. get: function () {
  25365. return this._fillMode === Material.WireFrameFillMode;
  25366. },
  25367. set: function (value) {
  25368. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25369. },
  25370. enumerable: true,
  25371. configurable: true
  25372. });
  25373. Object.defineProperty(Material.prototype, "pointsCloud", {
  25374. get: function () {
  25375. return this._fillMode === Material.PointFillMode;
  25376. },
  25377. set: function (value) {
  25378. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25379. },
  25380. enumerable: true,
  25381. configurable: true
  25382. });
  25383. Object.defineProperty(Material.prototype, "fillMode", {
  25384. get: function () {
  25385. return this._fillMode;
  25386. },
  25387. set: function (value) {
  25388. if (this._fillMode === value) {
  25389. return;
  25390. }
  25391. this._fillMode = value;
  25392. this.markAsDirty(Material.MiscDirtyFlag);
  25393. },
  25394. enumerable: true,
  25395. configurable: true
  25396. });
  25397. /**
  25398. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25399. * subclasses should override adding information pertainent to themselves
  25400. */
  25401. Material.prototype.toString = function (fullDetails) {
  25402. var ret = "Name: " + this.name;
  25403. if (fullDetails) {
  25404. }
  25405. return ret;
  25406. };
  25407. /**
  25408. * Child classes can use it to update shaders
  25409. */
  25410. Material.prototype.getClassName = function () {
  25411. return "Material";
  25412. };
  25413. Object.defineProperty(Material.prototype, "isFrozen", {
  25414. get: function () {
  25415. return this.checkReadyOnlyOnce;
  25416. },
  25417. enumerable: true,
  25418. configurable: true
  25419. });
  25420. Material.prototype.freeze = function () {
  25421. this.checkReadyOnlyOnce = true;
  25422. };
  25423. Material.prototype.unfreeze = function () {
  25424. this.checkReadyOnlyOnce = false;
  25425. };
  25426. Material.prototype.isReady = function (mesh, useInstances) {
  25427. return true;
  25428. };
  25429. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25430. return false;
  25431. };
  25432. Material.prototype.getEffect = function () {
  25433. return this._effect;
  25434. };
  25435. Material.prototype.getScene = function () {
  25436. return this._scene;
  25437. };
  25438. Material.prototype.needAlphaBlending = function () {
  25439. return (this.alpha < 1.0);
  25440. };
  25441. Material.prototype.needAlphaTesting = function () {
  25442. return false;
  25443. };
  25444. Material.prototype.getAlphaTestTexture = function () {
  25445. return null;
  25446. };
  25447. Material.prototype.markDirty = function () {
  25448. this._wasPreviouslyReady = false;
  25449. };
  25450. Material.prototype._preBind = function (effect) {
  25451. var engine = this._scene.getEngine();
  25452. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25453. engine.enableEffect(effect ? effect : this._effect);
  25454. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25455. };
  25456. Material.prototype.bind = function (world, mesh) {
  25457. };
  25458. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25459. };
  25460. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25461. };
  25462. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25463. sceneUbo.bindToEffect(effect, "Scene");
  25464. };
  25465. Material.prototype.bindView = function (effect) {
  25466. if (!this._useUBO) {
  25467. effect.setMatrix("view", this.getScene().getViewMatrix());
  25468. }
  25469. else {
  25470. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25471. }
  25472. };
  25473. Material.prototype.bindViewProjection = function (effect) {
  25474. if (!this._useUBO) {
  25475. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25476. }
  25477. else {
  25478. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25479. }
  25480. };
  25481. Material.prototype._afterBind = function (mesh) {
  25482. this._scene._cachedMaterial = this;
  25483. if (mesh) {
  25484. this._scene._cachedVisibility = mesh.visibility;
  25485. }
  25486. else {
  25487. this._scene._cachedVisibility = 1;
  25488. }
  25489. this.onBindObservable.notifyObservers(mesh);
  25490. if (this.disableDepthWrite) {
  25491. var engine = this._scene.getEngine();
  25492. this._cachedDepthWriteState = engine.getDepthWrite();
  25493. engine.setDepthWrite(false);
  25494. }
  25495. };
  25496. Material.prototype.unbind = function () {
  25497. this.onUnBindObservable.notifyObservers(this);
  25498. if (this.disableDepthWrite) {
  25499. var engine = this._scene.getEngine();
  25500. engine.setDepthWrite(this._cachedDepthWriteState);
  25501. }
  25502. };
  25503. Material.prototype.getActiveTextures = function () {
  25504. return [];
  25505. };
  25506. Material.prototype.hasTexture = function (texture) {
  25507. return false;
  25508. };
  25509. Material.prototype.clone = function (name) {
  25510. return null;
  25511. };
  25512. Material.prototype.getBindedMeshes = function () {
  25513. var result = new Array();
  25514. for (var index = 0; index < this._scene.meshes.length; index++) {
  25515. var mesh = this._scene.meshes[index];
  25516. if (mesh.material === this) {
  25517. result.push(mesh);
  25518. }
  25519. }
  25520. return result;
  25521. };
  25522. /**
  25523. * Force shader compilation including textures ready check
  25524. */
  25525. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25526. var _this = this;
  25527. var subMesh = new BABYLON.BaseSubMesh();
  25528. var scene = this.getScene();
  25529. var engine = scene.getEngine();
  25530. var checkReady = function () {
  25531. if (!_this._scene || !_this._scene.getEngine()) {
  25532. return;
  25533. }
  25534. if (subMesh._materialDefines) {
  25535. subMesh._materialDefines._renderId = -1;
  25536. }
  25537. var alphaTestState = engine.getAlphaTesting();
  25538. var clipPlaneState = scene.clipPlane;
  25539. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25540. if (options && options.clipPlane) {
  25541. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25542. }
  25543. if (_this.storeEffectOnSubMeshes) {
  25544. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25545. if (onCompiled) {
  25546. onCompiled(_this);
  25547. }
  25548. }
  25549. else {
  25550. setTimeout(checkReady, 16);
  25551. }
  25552. }
  25553. else {
  25554. if (_this.isReady(mesh)) {
  25555. if (onCompiled) {
  25556. onCompiled(_this);
  25557. }
  25558. }
  25559. else {
  25560. setTimeout(checkReady, 16);
  25561. }
  25562. }
  25563. engine.setAlphaTesting(alphaTestState);
  25564. if (options && options.clipPlane) {
  25565. scene.clipPlane = clipPlaneState;
  25566. }
  25567. };
  25568. checkReady();
  25569. };
  25570. Material.prototype.markAsDirty = function (flag) {
  25571. if (flag & Material.TextureDirtyFlag) {
  25572. this._markAllSubMeshesAsTexturesDirty();
  25573. }
  25574. if (flag & Material.LightDirtyFlag) {
  25575. this._markAllSubMeshesAsLightsDirty();
  25576. }
  25577. if (flag & Material.FresnelDirtyFlag) {
  25578. this._markAllSubMeshesAsFresnelDirty();
  25579. }
  25580. if (flag & Material.AttributesDirtyFlag) {
  25581. this._markAllSubMeshesAsAttributesDirty();
  25582. }
  25583. if (flag & Material.MiscDirtyFlag) {
  25584. this._markAllSubMeshesAsMiscDirty();
  25585. }
  25586. this.getScene().resetCachedMaterial();
  25587. };
  25588. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25589. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25590. var mesh = _a[_i];
  25591. if (!mesh.subMeshes) {
  25592. continue;
  25593. }
  25594. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25595. var subMesh = _c[_b];
  25596. if (subMesh.getMaterial() !== this) {
  25597. continue;
  25598. }
  25599. if (!subMesh._materialDefines) {
  25600. continue;
  25601. }
  25602. func(subMesh._materialDefines);
  25603. }
  25604. }
  25605. };
  25606. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25607. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25608. };
  25609. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25610. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25611. };
  25612. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25613. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25614. };
  25615. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25616. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25617. };
  25618. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25619. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25620. };
  25621. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  25622. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  25623. };
  25624. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25625. // Animations
  25626. this.getScene().stopAnimation(this);
  25627. // Remove from scene
  25628. var index = this._scene.materials.indexOf(this);
  25629. if (index >= 0) {
  25630. this._scene.materials.splice(index, 1);
  25631. }
  25632. // Remove from meshes
  25633. for (index = 0; index < this._scene.meshes.length; index++) {
  25634. var mesh = this._scene.meshes[index];
  25635. if (mesh.material === this) {
  25636. mesh.material = null;
  25637. if (mesh.geometry) {
  25638. var geometry = mesh.geometry;
  25639. if (this.storeEffectOnSubMeshes) {
  25640. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  25641. var subMesh = _a[_i];
  25642. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  25643. }
  25644. }
  25645. else {
  25646. geometry._releaseVertexArrayObject(this._effect);
  25647. }
  25648. }
  25649. }
  25650. }
  25651. this._uniformBuffer.dispose();
  25652. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25653. if (forceDisposeEffect && this._effect) {
  25654. if (this.storeEffectOnSubMeshes) {
  25655. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25656. var subMesh = _c[_b];
  25657. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  25658. }
  25659. }
  25660. else {
  25661. this._scene.getEngine()._releaseEffect(this._effect);
  25662. }
  25663. this._effect = null;
  25664. }
  25665. // Callback
  25666. this.onDisposeObservable.notifyObservers(this);
  25667. this.onDisposeObservable.clear();
  25668. this.onBindObservable.clear();
  25669. this.onUnBindObservable.clear();
  25670. };
  25671. Material.prototype.serialize = function () {
  25672. return BABYLON.SerializationHelper.Serialize(this);
  25673. };
  25674. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25675. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25676. multiMaterial.id = parsedMultiMaterial.id;
  25677. if (BABYLON.Tags) {
  25678. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25679. }
  25680. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25681. var subMatId = parsedMultiMaterial.materials[matIndex];
  25682. if (subMatId) {
  25683. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25684. }
  25685. else {
  25686. multiMaterial.subMaterials.push(null);
  25687. }
  25688. }
  25689. return multiMaterial;
  25690. };
  25691. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25692. if (!parsedMaterial.customType) {
  25693. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25694. }
  25695. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  25696. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  25697. if (!BABYLON.LegacyPBRMaterial) {
  25698. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25699. return;
  25700. }
  25701. }
  25702. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25703. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25704. ;
  25705. };
  25706. Material._TriangleFillMode = 0;
  25707. Material._WireFrameFillMode = 1;
  25708. Material._PointFillMode = 2;
  25709. Material._ClockWiseSideOrientation = 0;
  25710. Material._CounterClockWiseSideOrientation = 1;
  25711. Material._TextureDirtyFlag = 1;
  25712. Material._LightDirtyFlag = 2;
  25713. Material._FresnelDirtyFlag = 4;
  25714. Material._AttributesDirtyFlag = 8;
  25715. Material._MiscDirtyFlag = 16;
  25716. __decorate([
  25717. BABYLON.serialize()
  25718. ], Material.prototype, "id", void 0);
  25719. __decorate([
  25720. BABYLON.serialize()
  25721. ], Material.prototype, "name", void 0);
  25722. __decorate([
  25723. BABYLON.serialize()
  25724. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25725. __decorate([
  25726. BABYLON.serialize()
  25727. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25728. __decorate([
  25729. BABYLON.serialize()
  25730. ], Material.prototype, "state", void 0);
  25731. __decorate([
  25732. BABYLON.serialize()
  25733. ], Material.prototype, "alpha", void 0);
  25734. __decorate([
  25735. BABYLON.serialize("backFaceCulling")
  25736. ], Material.prototype, "_backFaceCulling", void 0);
  25737. __decorate([
  25738. BABYLON.serialize()
  25739. ], Material.prototype, "sideOrientation", void 0);
  25740. __decorate([
  25741. BABYLON.serialize()
  25742. ], Material.prototype, "alphaMode", void 0);
  25743. __decorate([
  25744. BABYLON.serialize()
  25745. ], Material.prototype, "disableDepthWrite", void 0);
  25746. __decorate([
  25747. BABYLON.serialize("fogEnabled")
  25748. ], Material.prototype, "_fogEnabled", void 0);
  25749. __decorate([
  25750. BABYLON.serialize()
  25751. ], Material.prototype, "pointSize", void 0);
  25752. __decorate([
  25753. BABYLON.serialize()
  25754. ], Material.prototype, "zOffset", void 0);
  25755. __decorate([
  25756. BABYLON.serialize()
  25757. ], Material.prototype, "wireframe", null);
  25758. __decorate([
  25759. BABYLON.serialize()
  25760. ], Material.prototype, "pointsCloud", null);
  25761. __decorate([
  25762. BABYLON.serialize()
  25763. ], Material.prototype, "fillMode", null);
  25764. return Material;
  25765. }());
  25766. BABYLON.Material = Material;
  25767. })(BABYLON || (BABYLON = {}));
  25768. //# sourceMappingURL=babylon.material.js.map
  25769. var BABYLON;
  25770. (function (BABYLON) {
  25771. var UniformBuffer = (function () {
  25772. /**
  25773. * Uniform buffer objects.
  25774. *
  25775. * Handles blocks of uniform on the GPU.
  25776. *
  25777. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  25778. *
  25779. * For more information, please refer to :
  25780. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  25781. */
  25782. function UniformBuffer(engine, data, dynamic) {
  25783. this._engine = engine;
  25784. this._noUBO = engine.webGLVersion === 1;
  25785. this._dynamic = dynamic;
  25786. this._data = data || [];
  25787. this._uniformLocations = {};
  25788. this._uniformSizes = {};
  25789. this._uniformLocationPointer = 0;
  25790. this._needSync = false;
  25791. if (this._noUBO) {
  25792. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  25793. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  25794. this.updateFloat = this._updateFloatForEffect;
  25795. this.updateFloat2 = this._updateFloat2ForEffect;
  25796. this.updateFloat3 = this._updateFloat3ForEffect;
  25797. this.updateFloat4 = this._updateFloat4ForEffect;
  25798. this.updateMatrix = this._updateMatrixForEffect;
  25799. this.updateVector3 = this._updateVector3ForEffect;
  25800. this.updateVector4 = this._updateVector4ForEffect;
  25801. this.updateColor3 = this._updateColor3ForEffect;
  25802. this.updateColor4 = this._updateColor4ForEffect;
  25803. }
  25804. else {
  25805. this._engine._uniformBuffers.push(this);
  25806. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  25807. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  25808. this.updateFloat = this._updateFloatForUniform;
  25809. this.updateFloat2 = this._updateFloat2ForUniform;
  25810. this.updateFloat3 = this._updateFloat3ForUniform;
  25811. this.updateFloat4 = this._updateFloat4ForUniform;
  25812. this.updateMatrix = this._updateMatrixForUniform;
  25813. this.updateVector3 = this._updateVector3ForUniform;
  25814. this.updateVector4 = this._updateVector4ForUniform;
  25815. this.updateColor3 = this._updateColor3ForUniform;
  25816. this.updateColor4 = this._updateColor4ForUniform;
  25817. }
  25818. }
  25819. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  25820. // Properties
  25821. /**
  25822. * Indicates if the buffer is using the WebGL2 UBO implementation,
  25823. * or just falling back on setUniformXXX calls.
  25824. */
  25825. get: function () {
  25826. return !this._noUBO;
  25827. },
  25828. enumerable: true,
  25829. configurable: true
  25830. });
  25831. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  25832. /**
  25833. * Indicates if the WebGL underlying uniform buffer is in sync
  25834. * with the javascript cache data.
  25835. */
  25836. get: function () {
  25837. return !this._needSync;
  25838. },
  25839. enumerable: true,
  25840. configurable: true
  25841. });
  25842. /**
  25843. * Indicates if the WebGL underlying uniform buffer is dynamic.
  25844. * Also, a dynamic UniformBuffer will disable cache verification and always
  25845. * update the underlying WebGL uniform buffer to the GPU.
  25846. */
  25847. UniformBuffer.prototype.isDynamic = function () {
  25848. return this._dynamic;
  25849. };
  25850. /**
  25851. * The data cache on JS side.
  25852. */
  25853. UniformBuffer.prototype.getData = function () {
  25854. return this._bufferData;
  25855. };
  25856. /**
  25857. * The underlying WebGL Uniform buffer.
  25858. */
  25859. UniformBuffer.prototype.getBuffer = function () {
  25860. return this._buffer;
  25861. };
  25862. /**
  25863. * std140 layout specifies how to align data within an UBO structure.
  25864. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  25865. * for specs.
  25866. */
  25867. UniformBuffer.prototype._fillAlignment = function (size) {
  25868. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  25869. // and 4x4 matrices
  25870. // TODO : change if other types are used
  25871. var alignment;
  25872. if (size <= 2) {
  25873. alignment = size;
  25874. }
  25875. else {
  25876. alignment = 4;
  25877. }
  25878. if ((this._uniformLocationPointer % alignment) !== 0) {
  25879. var oldPointer = this._uniformLocationPointer;
  25880. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  25881. var diff = this._uniformLocationPointer - oldPointer;
  25882. for (var i = 0; i < diff; i++) {
  25883. this._data.push(0);
  25884. }
  25885. }
  25886. };
  25887. /**
  25888. * Adds an uniform in the buffer.
  25889. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  25890. * for the layout to be correct !
  25891. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25892. * @param {number|number[]} size Data size, or data directly.
  25893. */
  25894. UniformBuffer.prototype.addUniform = function (name, size) {
  25895. if (this._noUBO) {
  25896. return;
  25897. }
  25898. if (this._uniformLocations[name] !== undefined) {
  25899. // Already existing uniform
  25900. return;
  25901. }
  25902. // This function must be called in the order of the shader layout !
  25903. // size can be the size of the uniform, or data directly
  25904. var data;
  25905. if (size instanceof Array) {
  25906. data = size;
  25907. size = data.length;
  25908. }
  25909. else {
  25910. size = size;
  25911. data = [];
  25912. // Fill with zeros
  25913. for (var i = 0; i < size; i++) {
  25914. data.push(0);
  25915. }
  25916. }
  25917. this._fillAlignment(size);
  25918. this._uniformSizes[name] = size;
  25919. this._uniformLocations[name] = this._uniformLocationPointer;
  25920. this._uniformLocationPointer += size;
  25921. for (var i = 0; i < size; i++) {
  25922. this._data.push(data[i]);
  25923. }
  25924. this._needSync = true;
  25925. };
  25926. /**
  25927. * Wrapper for addUniform.
  25928. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25929. * @param {Matrix} mat A 4x4 matrix.
  25930. */
  25931. UniformBuffer.prototype.addMatrix = function (name, mat) {
  25932. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  25933. };
  25934. /**
  25935. * Wrapper for addUniform.
  25936. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25937. * @param {number} x
  25938. * @param {number} y
  25939. */
  25940. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  25941. var temp = [x, y];
  25942. this.addUniform(name, temp);
  25943. };
  25944. /**
  25945. * Wrapper for addUniform.
  25946. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25947. * @param {number} x
  25948. * @param {number} y
  25949. * @param {number} z
  25950. */
  25951. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  25952. var temp = [x, y, z];
  25953. this.addUniform(name, temp);
  25954. };
  25955. /**
  25956. * Wrapper for addUniform.
  25957. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25958. * @param {Color3} color
  25959. */
  25960. UniformBuffer.prototype.addColor3 = function (name, color) {
  25961. var temp = [];
  25962. color.toArray(temp);
  25963. this.addUniform(name, temp);
  25964. };
  25965. /**
  25966. * Wrapper for addUniform.
  25967. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25968. * @param {Color3} color
  25969. * @param {number} alpha
  25970. */
  25971. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  25972. var temp = [];
  25973. color.toArray(temp);
  25974. temp.push(alpha);
  25975. this.addUniform(name, temp);
  25976. };
  25977. /**
  25978. * Wrapper for addUniform.
  25979. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25980. * @param {Vector3} vector
  25981. */
  25982. UniformBuffer.prototype.addVector3 = function (name, vector) {
  25983. var temp = [];
  25984. vector.toArray(temp);
  25985. this.addUniform(name, temp);
  25986. };
  25987. /**
  25988. * Wrapper for addUniform.
  25989. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25990. */
  25991. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  25992. this.addUniform(name, 12);
  25993. };
  25994. /**
  25995. * Wrapper for addUniform.
  25996. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25997. */
  25998. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  25999. this.addUniform(name, 8);
  26000. };
  26001. /**
  26002. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  26003. */
  26004. UniformBuffer.prototype.create = function () {
  26005. if (this._noUBO) {
  26006. return;
  26007. }
  26008. if (this._buffer) {
  26009. return; // nothing to do
  26010. }
  26011. // See spec, alignment must be filled as a vec4
  26012. this._fillAlignment(4);
  26013. this._bufferData = new Float32Array(this._data);
  26014. this._rebuild();
  26015. this._needSync = true;
  26016. };
  26017. UniformBuffer.prototype._rebuild = function () {
  26018. if (this._noUBO) {
  26019. return;
  26020. }
  26021. if (this._dynamic) {
  26022. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26023. }
  26024. else {
  26025. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26026. }
  26027. };
  26028. /**
  26029. * Updates the WebGL Uniform Buffer on the GPU.
  26030. * If the `dynamic` flag is set to true, no cache comparison is done.
  26031. * Otherwise, the buffer will be updated only if the cache differs.
  26032. */
  26033. UniformBuffer.prototype.update = function () {
  26034. if (!this._buffer) {
  26035. this.create();
  26036. return;
  26037. }
  26038. if (!this._dynamic && !this._needSync) {
  26039. return;
  26040. }
  26041. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26042. this._needSync = false;
  26043. };
  26044. /**
  26045. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26046. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26047. * @param {number[]|Float32Array} data Flattened data
  26048. * @param {number} size Size of the data.
  26049. */
  26050. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26051. var location = this._uniformLocations[uniformName];
  26052. if (location === undefined) {
  26053. if (this._buffer) {
  26054. // Cannot add an uniform if the buffer is already created
  26055. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26056. return;
  26057. }
  26058. this.addUniform(uniformName, size);
  26059. location = this._uniformLocations[uniformName];
  26060. }
  26061. if (!this._buffer) {
  26062. this.create();
  26063. }
  26064. if (!this._dynamic) {
  26065. // Cache for static uniform buffers
  26066. var changed = false;
  26067. for (var i = 0; i < size; i++) {
  26068. if (this._bufferData[location + i] !== data[i]) {
  26069. changed = true;
  26070. this._bufferData[location + i] = data[i];
  26071. }
  26072. }
  26073. this._needSync = this._needSync || changed;
  26074. }
  26075. else {
  26076. // No cache for dynamic
  26077. for (var i = 0; i < size; i++) {
  26078. this._bufferData[location + i] = data[i];
  26079. }
  26080. }
  26081. };
  26082. // Update methods
  26083. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26084. // To match std140, matrix must be realigned
  26085. for (var i = 0; i < 3; i++) {
  26086. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26087. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26088. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26089. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26090. }
  26091. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26092. };
  26093. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26094. this._currentEffect.setMatrix3x3(name, matrix);
  26095. };
  26096. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26097. this._currentEffect.setMatrix2x2(name, matrix);
  26098. };
  26099. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26100. // To match std140, matrix must be realigned
  26101. for (var i = 0; i < 2; i++) {
  26102. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26103. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26104. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26105. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26106. }
  26107. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26108. };
  26109. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26110. this._currentEffect.setFloat(name, x);
  26111. };
  26112. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26113. UniformBuffer._tempBuffer[0] = x;
  26114. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26115. };
  26116. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26117. if (suffix === void 0) { suffix = ""; }
  26118. this._currentEffect.setFloat2(name + suffix, x, y);
  26119. };
  26120. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26121. if (suffix === void 0) { suffix = ""; }
  26122. UniformBuffer._tempBuffer[0] = x;
  26123. UniformBuffer._tempBuffer[1] = y;
  26124. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26125. };
  26126. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26127. if (suffix === void 0) { suffix = ""; }
  26128. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26129. };
  26130. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26131. if (suffix === void 0) { suffix = ""; }
  26132. UniformBuffer._tempBuffer[0] = x;
  26133. UniformBuffer._tempBuffer[1] = y;
  26134. UniformBuffer._tempBuffer[2] = z;
  26135. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26136. };
  26137. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26138. if (suffix === void 0) { suffix = ""; }
  26139. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26140. };
  26141. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26142. if (suffix === void 0) { suffix = ""; }
  26143. UniformBuffer._tempBuffer[0] = x;
  26144. UniformBuffer._tempBuffer[1] = y;
  26145. UniformBuffer._tempBuffer[2] = z;
  26146. UniformBuffer._tempBuffer[3] = w;
  26147. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26148. };
  26149. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26150. this._currentEffect.setMatrix(name, mat);
  26151. };
  26152. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26153. this.updateUniform(name, mat.toArray(), 16);
  26154. };
  26155. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26156. this._currentEffect.setVector3(name, vector);
  26157. };
  26158. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26159. vector.toArray(UniformBuffer._tempBuffer);
  26160. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26161. };
  26162. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26163. this._currentEffect.setVector4(name, vector);
  26164. };
  26165. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26166. vector.toArray(UniformBuffer._tempBuffer);
  26167. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26168. };
  26169. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26170. if (suffix === void 0) { suffix = ""; }
  26171. this._currentEffect.setColor3(name + suffix, color);
  26172. };
  26173. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26174. if (suffix === void 0) { suffix = ""; }
  26175. color.toArray(UniformBuffer._tempBuffer);
  26176. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26177. };
  26178. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26179. if (suffix === void 0) { suffix = ""; }
  26180. this._currentEffect.setColor4(name + suffix, color, alpha);
  26181. };
  26182. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26183. if (suffix === void 0) { suffix = ""; }
  26184. color.toArray(UniformBuffer._tempBuffer);
  26185. UniformBuffer._tempBuffer[3] = alpha;
  26186. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26187. };
  26188. /**
  26189. * Sets a sampler uniform on the effect.
  26190. * @param {string} name Name of the sampler.
  26191. * @param {Texture} texture
  26192. */
  26193. UniformBuffer.prototype.setTexture = function (name, texture) {
  26194. this._currentEffect.setTexture(name, texture);
  26195. };
  26196. /**
  26197. * Directly updates the value of the uniform in the cache AND on the GPU.
  26198. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26199. * @param {number[]|Float32Array} data Flattened data
  26200. */
  26201. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26202. this.updateUniform(uniformName, data, data.length);
  26203. this.update();
  26204. };
  26205. /**
  26206. * Binds this uniform buffer to an effect.
  26207. * @param {Effect} effect
  26208. * @param {string} name Name of the uniform block in the shader.
  26209. */
  26210. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26211. this._currentEffect = effect;
  26212. if (this._noUBO) {
  26213. return;
  26214. }
  26215. effect.bindUniformBuffer(this._buffer, name);
  26216. };
  26217. /**
  26218. * Disposes the uniform buffer.
  26219. */
  26220. UniformBuffer.prototype.dispose = function () {
  26221. if (this._noUBO) {
  26222. return;
  26223. }
  26224. var index = this._engine._uniformBuffers.indexOf(this);
  26225. if (index !== -1) {
  26226. this._engine._uniformBuffers.splice(index, 1);
  26227. }
  26228. if (!this._buffer) {
  26229. return;
  26230. }
  26231. if (this._engine._releaseBuffer(this._buffer)) {
  26232. this._buffer = null;
  26233. }
  26234. };
  26235. // Pool for avoiding memory leaks
  26236. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26237. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26238. return UniformBuffer;
  26239. }());
  26240. BABYLON.UniformBuffer = UniformBuffer;
  26241. })(BABYLON || (BABYLON = {}));
  26242. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26243. var BABYLON;
  26244. (function (BABYLON) {
  26245. var PushMaterial = (function (_super) {
  26246. __extends(PushMaterial, _super);
  26247. function PushMaterial(name, scene) {
  26248. var _this = _super.call(this, name, scene) || this;
  26249. _this.storeEffectOnSubMeshes = true;
  26250. return _this;
  26251. }
  26252. PushMaterial.prototype.getEffect = function () {
  26253. return this._activeEffect;
  26254. };
  26255. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26256. if (!mesh) {
  26257. return false;
  26258. }
  26259. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26260. return true;
  26261. }
  26262. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26263. };
  26264. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26265. this._activeEffect.setMatrix("world", world);
  26266. };
  26267. PushMaterial.prototype.bind = function (world, mesh) {
  26268. if (!mesh) {
  26269. return;
  26270. }
  26271. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26272. };
  26273. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26274. _super.prototype._afterBind.call(this, mesh);
  26275. this.getScene()._cachedEffect = effect;
  26276. };
  26277. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26278. if (visibility === void 0) { visibility = 1; }
  26279. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26280. };
  26281. return PushMaterial;
  26282. }(BABYLON.Material));
  26283. BABYLON.PushMaterial = PushMaterial;
  26284. })(BABYLON || (BABYLON = {}));
  26285. //# sourceMappingURL=babylon.pushMaterial.js.map
  26286. var BABYLON;
  26287. (function (BABYLON) {
  26288. var VertexData = (function () {
  26289. function VertexData() {
  26290. }
  26291. VertexData.prototype.set = function (data, kind) {
  26292. switch (kind) {
  26293. case BABYLON.VertexBuffer.PositionKind:
  26294. this.positions = data;
  26295. break;
  26296. case BABYLON.VertexBuffer.NormalKind:
  26297. this.normals = data;
  26298. break;
  26299. case BABYLON.VertexBuffer.TangentKind:
  26300. this.tangents = data;
  26301. break;
  26302. case BABYLON.VertexBuffer.UVKind:
  26303. this.uvs = data;
  26304. break;
  26305. case BABYLON.VertexBuffer.UV2Kind:
  26306. this.uvs2 = data;
  26307. break;
  26308. case BABYLON.VertexBuffer.UV3Kind:
  26309. this.uvs3 = data;
  26310. break;
  26311. case BABYLON.VertexBuffer.UV4Kind:
  26312. this.uvs4 = data;
  26313. break;
  26314. case BABYLON.VertexBuffer.UV5Kind:
  26315. this.uvs5 = data;
  26316. break;
  26317. case BABYLON.VertexBuffer.UV6Kind:
  26318. this.uvs6 = data;
  26319. break;
  26320. case BABYLON.VertexBuffer.ColorKind:
  26321. this.colors = data;
  26322. break;
  26323. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26324. this.matricesIndices = data;
  26325. break;
  26326. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26327. this.matricesWeights = data;
  26328. break;
  26329. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26330. this.matricesIndicesExtra = data;
  26331. break;
  26332. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26333. this.matricesWeightsExtra = data;
  26334. break;
  26335. }
  26336. };
  26337. /**
  26338. * Associates the vertexData to the passed Mesh.
  26339. * Sets it as updatable or not (default `false`).
  26340. * Returns the VertexData.
  26341. */
  26342. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26343. this._applyTo(mesh, updatable);
  26344. return this;
  26345. };
  26346. /**
  26347. * Associates the vertexData to the passed Geometry.
  26348. * Sets it as updatable or not (default `false`).
  26349. * Returns the VertexData.
  26350. */
  26351. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26352. this._applyTo(geometry, updatable);
  26353. return this;
  26354. };
  26355. /**
  26356. * Updates the associated mesh.
  26357. * Returns the VertexData.
  26358. */
  26359. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26360. this._update(mesh);
  26361. return this;
  26362. };
  26363. /**
  26364. * Updates the associated geometry.
  26365. * Returns the VertexData.
  26366. */
  26367. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26368. this._update(geometry);
  26369. return this;
  26370. };
  26371. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26372. if (this.positions) {
  26373. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26374. }
  26375. if (this.normals) {
  26376. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26377. }
  26378. if (this.tangents) {
  26379. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26380. }
  26381. if (this.uvs) {
  26382. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26383. }
  26384. if (this.uvs2) {
  26385. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26386. }
  26387. if (this.uvs3) {
  26388. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26389. }
  26390. if (this.uvs4) {
  26391. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26392. }
  26393. if (this.uvs5) {
  26394. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26395. }
  26396. if (this.uvs6) {
  26397. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26398. }
  26399. if (this.colors) {
  26400. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26401. }
  26402. if (this.matricesIndices) {
  26403. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26404. }
  26405. if (this.matricesWeights) {
  26406. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26407. }
  26408. if (this.matricesIndicesExtra) {
  26409. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26410. }
  26411. if (this.matricesWeightsExtra) {
  26412. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26413. }
  26414. if (this.indices) {
  26415. meshOrGeometry.setIndices(this.indices);
  26416. }
  26417. return this;
  26418. };
  26419. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26420. if (this.positions) {
  26421. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26422. }
  26423. if (this.normals) {
  26424. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26425. }
  26426. if (this.tangents) {
  26427. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26428. }
  26429. if (this.uvs) {
  26430. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26431. }
  26432. if (this.uvs2) {
  26433. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26434. }
  26435. if (this.uvs3) {
  26436. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26437. }
  26438. if (this.uvs4) {
  26439. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26440. }
  26441. if (this.uvs5) {
  26442. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26443. }
  26444. if (this.uvs6) {
  26445. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26446. }
  26447. if (this.colors) {
  26448. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26449. }
  26450. if (this.matricesIndices) {
  26451. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26452. }
  26453. if (this.matricesWeights) {
  26454. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26455. }
  26456. if (this.matricesIndicesExtra) {
  26457. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26458. }
  26459. if (this.matricesWeightsExtra) {
  26460. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26461. }
  26462. if (this.indices) {
  26463. meshOrGeometry.setIndices(this.indices);
  26464. }
  26465. return this;
  26466. };
  26467. /**
  26468. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26469. * Returns the VertexData.
  26470. */
  26471. VertexData.prototype.transform = function (matrix) {
  26472. var transformed = BABYLON.Vector3.Zero();
  26473. var index;
  26474. if (this.positions) {
  26475. var position = BABYLON.Vector3.Zero();
  26476. for (index = 0; index < this.positions.length; index += 3) {
  26477. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26478. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26479. this.positions[index] = transformed.x;
  26480. this.positions[index + 1] = transformed.y;
  26481. this.positions[index + 2] = transformed.z;
  26482. }
  26483. }
  26484. if (this.normals) {
  26485. var normal = BABYLON.Vector3.Zero();
  26486. for (index = 0; index < this.normals.length; index += 3) {
  26487. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26488. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26489. this.normals[index] = transformed.x;
  26490. this.normals[index + 1] = transformed.y;
  26491. this.normals[index + 2] = transformed.z;
  26492. }
  26493. }
  26494. if (this.tangents) {
  26495. var tangent = BABYLON.Vector4.Zero();
  26496. var tangentTransformed = BABYLON.Vector4.Zero();
  26497. for (index = 0; index < this.tangents.length; index += 4) {
  26498. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26499. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26500. this.tangents[index] = tangentTransformed.x;
  26501. this.tangents[index + 1] = tangentTransformed.y;
  26502. this.tangents[index + 2] = tangentTransformed.z;
  26503. this.tangents[index + 3] = tangentTransformed.w;
  26504. }
  26505. }
  26506. return this;
  26507. };
  26508. /**
  26509. * Merges the passed VertexData into the current one.
  26510. * Returns the modified VertexData.
  26511. */
  26512. VertexData.prototype.merge = function (other) {
  26513. if (other.indices) {
  26514. if (!this.indices) {
  26515. this.indices = [];
  26516. }
  26517. var offset = this.positions ? this.positions.length / 3 : 0;
  26518. for (var index = 0; index < other.indices.length; index++) {
  26519. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26520. this.indices.push(other.indices[index] + offset);
  26521. }
  26522. }
  26523. this.positions = this._mergeElement(this.positions, other.positions);
  26524. this.normals = this._mergeElement(this.normals, other.normals);
  26525. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26526. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26527. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26528. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26529. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26530. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26531. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26532. this.colors = this._mergeElement(this.colors, other.colors);
  26533. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26534. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26535. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26536. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26537. return this;
  26538. };
  26539. VertexData.prototype._mergeElement = function (source, other) {
  26540. if (!other)
  26541. return source;
  26542. if (!source)
  26543. return other;
  26544. var len = other.length + source.length;
  26545. var isSrcTypedArray = source instanceof Float32Array;
  26546. var isOthTypedArray = other instanceof Float32Array;
  26547. // use non-loop method when the source is Float32Array
  26548. if (isSrcTypedArray) {
  26549. var ret32 = new Float32Array(len);
  26550. ret32.set(source);
  26551. ret32.set(other, source.length);
  26552. return ret32;
  26553. // source is number[], when other is also use concat
  26554. }
  26555. else if (!isOthTypedArray) {
  26556. return source.concat(other);
  26557. // source is a number[], but other is a Float32Array, loop required
  26558. }
  26559. else {
  26560. var ret = source.slice(0); // copy source to a separate array
  26561. for (var i = 0, len = other.length; i < len; i++) {
  26562. ret.push(other[i]);
  26563. }
  26564. return ret;
  26565. }
  26566. };
  26567. /**
  26568. * Serializes the VertexData.
  26569. * Returns a serialized object.
  26570. */
  26571. VertexData.prototype.serialize = function () {
  26572. var serializationObject = this.serialize();
  26573. if (this.positions) {
  26574. serializationObject.positions = this.positions;
  26575. }
  26576. if (this.normals) {
  26577. serializationObject.normals = this.normals;
  26578. }
  26579. if (this.tangents) {
  26580. serializationObject.tangents = this.tangents;
  26581. }
  26582. if (this.uvs) {
  26583. serializationObject.uvs = this.uvs;
  26584. }
  26585. if (this.uvs2) {
  26586. serializationObject.uvs2 = this.uvs2;
  26587. }
  26588. if (this.uvs3) {
  26589. serializationObject.uvs3 = this.uvs3;
  26590. }
  26591. if (this.uvs4) {
  26592. serializationObject.uvs4 = this.uvs4;
  26593. }
  26594. if (this.uvs5) {
  26595. serializationObject.uvs5 = this.uvs5;
  26596. }
  26597. if (this.uvs6) {
  26598. serializationObject.uvs6 = this.uvs6;
  26599. }
  26600. if (this.colors) {
  26601. serializationObject.colors = this.colors;
  26602. }
  26603. if (this.matricesIndices) {
  26604. serializationObject.matricesIndices = this.matricesIndices;
  26605. serializationObject.matricesIndices._isExpanded = true;
  26606. }
  26607. if (this.matricesWeights) {
  26608. serializationObject.matricesWeights = this.matricesWeights;
  26609. }
  26610. if (this.matricesIndicesExtra) {
  26611. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26612. serializationObject.matricesIndicesExtra._isExpanded = true;
  26613. }
  26614. if (this.matricesWeightsExtra) {
  26615. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26616. }
  26617. serializationObject.indices = this.indices;
  26618. return serializationObject;
  26619. };
  26620. // Statics
  26621. /**
  26622. * Returns the object VertexData associated to the passed mesh.
  26623. */
  26624. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  26625. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  26626. };
  26627. /**
  26628. * Returns the object VertexData associated to the passed geometry.
  26629. */
  26630. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  26631. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  26632. };
  26633. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  26634. var result = new VertexData();
  26635. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26636. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  26637. }
  26638. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26639. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  26640. }
  26641. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26642. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  26643. }
  26644. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26645. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  26646. }
  26647. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26648. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  26649. }
  26650. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26651. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  26652. }
  26653. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26654. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  26655. }
  26656. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26657. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  26658. }
  26659. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26660. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  26661. }
  26662. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26663. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  26664. }
  26665. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26666. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  26667. }
  26668. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26669. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  26670. }
  26671. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26672. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  26673. }
  26674. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26675. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  26676. }
  26677. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26678. return result;
  26679. };
  26680. /**
  26681. * Creates the vertexData of the Ribbon.
  26682. */
  26683. VertexData.CreateRibbon = function (options) {
  26684. var pathArray = options.pathArray;
  26685. var closeArray = options.closeArray || false;
  26686. var closePath = options.closePath || false;
  26687. var invertUV = options.invertUV || false;
  26688. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26689. var offset = options.offset || defaultOffset;
  26690. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26691. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26692. var customUV = options.uvs;
  26693. var customColors = options.colors;
  26694. var positions = [];
  26695. var indices = [];
  26696. var normals = [];
  26697. var uvs = [];
  26698. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26699. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26700. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26701. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26702. var minlg; // minimal length among all paths from pathArray
  26703. var lg = []; // array of path lengths : nb of vertex per path
  26704. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26705. var p; // path iterator
  26706. var i; // point iterator
  26707. var j; // point iterator
  26708. // if single path in pathArray
  26709. if (pathArray.length < 2) {
  26710. var ar1 = [];
  26711. var ar2 = [];
  26712. for (i = 0; i < pathArray[0].length - offset; i++) {
  26713. ar1.push(pathArray[0][i]);
  26714. ar2.push(pathArray[0][i + offset]);
  26715. }
  26716. pathArray = [ar1, ar2];
  26717. }
  26718. // positions and horizontal distances (u)
  26719. var idc = 0;
  26720. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26721. var path;
  26722. var l;
  26723. minlg = pathArray[0].length;
  26724. var vectlg;
  26725. var dist;
  26726. for (p = 0; p < pathArray.length; p++) {
  26727. uTotalDistance[p] = 0;
  26728. us[p] = [0];
  26729. path = pathArray[p];
  26730. l = path.length;
  26731. minlg = (minlg < l) ? minlg : l;
  26732. j = 0;
  26733. while (j < l) {
  26734. positions.push(path[j].x, path[j].y, path[j].z);
  26735. if (j > 0) {
  26736. vectlg = path[j].subtract(path[j - 1]).length();
  26737. dist = vectlg + uTotalDistance[p];
  26738. us[p].push(dist);
  26739. uTotalDistance[p] = dist;
  26740. }
  26741. j++;
  26742. }
  26743. if (closePath) {
  26744. j--;
  26745. positions.push(path[0].x, path[0].y, path[0].z);
  26746. vectlg = path[j].subtract(path[0]).length();
  26747. dist = vectlg + uTotalDistance[p];
  26748. us[p].push(dist);
  26749. uTotalDistance[p] = dist;
  26750. }
  26751. lg[p] = l + closePathCorr;
  26752. idx[p] = idc;
  26753. idc += (l + closePathCorr);
  26754. }
  26755. // vertical distances (v)
  26756. var path1;
  26757. var path2;
  26758. var vertex1;
  26759. var vertex2;
  26760. for (i = 0; i < minlg + closePathCorr; i++) {
  26761. vTotalDistance[i] = 0;
  26762. vs[i] = [0];
  26763. for (p = 0; p < pathArray.length - 1; p++) {
  26764. path1 = pathArray[p];
  26765. path2 = pathArray[p + 1];
  26766. if (i === minlg) {
  26767. vertex1 = path1[0];
  26768. vertex2 = path2[0];
  26769. }
  26770. else {
  26771. vertex1 = path1[i];
  26772. vertex2 = path2[i];
  26773. }
  26774. vectlg = vertex2.subtract(vertex1).length();
  26775. dist = vectlg + vTotalDistance[i];
  26776. vs[i].push(dist);
  26777. vTotalDistance[i] = dist;
  26778. }
  26779. if (closeArray) {
  26780. path1 = pathArray[p];
  26781. path2 = pathArray[0];
  26782. if (i === minlg) {
  26783. vertex2 = path2[0];
  26784. }
  26785. vectlg = vertex2.subtract(vertex1).length();
  26786. dist = vectlg + vTotalDistance[i];
  26787. vTotalDistance[i] = dist;
  26788. }
  26789. }
  26790. // uvs
  26791. var u;
  26792. var v;
  26793. if (customUV) {
  26794. for (p = 0; p < customUV.length; p++) {
  26795. uvs.push(customUV[p].x, customUV[p].y);
  26796. }
  26797. }
  26798. else {
  26799. for (p = 0; p < pathArray.length; p++) {
  26800. for (i = 0; i < minlg + closePathCorr; i++) {
  26801. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  26802. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  26803. if (invertUV) {
  26804. uvs.push(v, u);
  26805. }
  26806. else {
  26807. uvs.push(u, v);
  26808. }
  26809. }
  26810. }
  26811. }
  26812. // indices
  26813. p = 0; // path index
  26814. var pi = 0; // positions array index
  26815. var l1 = lg[p] - 1; // path1 length
  26816. var l2 = lg[p + 1] - 1; // path2 length
  26817. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26818. var shft = idx[1] - idx[0]; // shift
  26819. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26820. while (pi <= min && p < path1nb) {
  26821. // 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
  26822. indices.push(pi, pi + shft, pi + 1);
  26823. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26824. pi += 1;
  26825. if (pi === min) {
  26826. p++;
  26827. if (p === lg.length - 1) {
  26828. shft = idx[0] - idx[p];
  26829. l1 = lg[p] - 1;
  26830. l2 = lg[0] - 1;
  26831. }
  26832. else {
  26833. shft = idx[p + 1] - idx[p];
  26834. l1 = lg[p] - 1;
  26835. l2 = lg[p + 1] - 1;
  26836. }
  26837. pi = idx[p];
  26838. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26839. }
  26840. }
  26841. // normals
  26842. VertexData.ComputeNormals(positions, indices, normals);
  26843. if (closePath) {
  26844. var indexFirst = 0;
  26845. var indexLast = 0;
  26846. for (p = 0; p < pathArray.length; p++) {
  26847. indexFirst = idx[p] * 3;
  26848. if (p + 1 < pathArray.length) {
  26849. indexLast = (idx[p + 1] - 1) * 3;
  26850. }
  26851. else {
  26852. indexLast = normals.length - 3;
  26853. }
  26854. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26855. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26856. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26857. normals[indexLast] = normals[indexFirst];
  26858. normals[indexLast + 1] = normals[indexFirst + 1];
  26859. normals[indexLast + 2] = normals[indexFirst + 2];
  26860. }
  26861. }
  26862. // sides
  26863. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26864. // Colors
  26865. if (customColors) {
  26866. var colors = new Float32Array(customColors.length * 4);
  26867. for (var c = 0; c < customColors.length; c++) {
  26868. colors[c * 4] = customColors[c].r;
  26869. colors[c * 4 + 1] = customColors[c].g;
  26870. colors[c * 4 + 2] = customColors[c].b;
  26871. colors[c * 4 + 3] = customColors[c].a;
  26872. }
  26873. }
  26874. // Result
  26875. var vertexData = new VertexData();
  26876. var positions32 = new Float32Array(positions);
  26877. var normals32 = new Float32Array(normals);
  26878. var uvs32 = new Float32Array(uvs);
  26879. vertexData.indices = indices;
  26880. vertexData.positions = positions32;
  26881. vertexData.normals = normals32;
  26882. vertexData.uvs = uvs32;
  26883. if (customColors) {
  26884. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  26885. }
  26886. if (closePath) {
  26887. vertexData._idx = idx;
  26888. }
  26889. return vertexData;
  26890. };
  26891. /**
  26892. * Creates the VertexData of the Box.
  26893. */
  26894. VertexData.CreateBox = function (options) {
  26895. var normalsSource = [
  26896. new BABYLON.Vector3(0, 0, 1),
  26897. new BABYLON.Vector3(0, 0, -1),
  26898. new BABYLON.Vector3(1, 0, 0),
  26899. new BABYLON.Vector3(-1, 0, 0),
  26900. new BABYLON.Vector3(0, 1, 0),
  26901. new BABYLON.Vector3(0, -1, 0)
  26902. ];
  26903. var indices = [];
  26904. var positions = [];
  26905. var normals = [];
  26906. var uvs = [];
  26907. var width = options.width || options.size || 1;
  26908. var height = options.height || options.size || 1;
  26909. var depth = options.depth || options.size || 1;
  26910. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26911. var faceUV = options.faceUV || new Array(6);
  26912. var faceColors = options.faceColors;
  26913. var colors = [];
  26914. // default face colors and UV if undefined
  26915. for (var f = 0; f < 6; f++) {
  26916. if (faceUV[f] === undefined) {
  26917. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26918. }
  26919. if (faceColors && faceColors[f] === undefined) {
  26920. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26921. }
  26922. }
  26923. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26924. // Create each face in turn.
  26925. for (var index = 0; index < normalsSource.length; index++) {
  26926. var normal = normalsSource[index];
  26927. // Get two vectors perpendicular to the face normal and to each other.
  26928. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26929. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26930. // Six indices (two triangles) per face.
  26931. var verticesLength = positions.length / 3;
  26932. indices.push(verticesLength);
  26933. indices.push(verticesLength + 1);
  26934. indices.push(verticesLength + 2);
  26935. indices.push(verticesLength);
  26936. indices.push(verticesLength + 2);
  26937. indices.push(verticesLength + 3);
  26938. // Four vertices per face.
  26939. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26940. positions.push(vertex.x, vertex.y, vertex.z);
  26941. normals.push(normal.x, normal.y, normal.z);
  26942. uvs.push(faceUV[index].z, faceUV[index].w);
  26943. if (faceColors) {
  26944. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26945. }
  26946. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26947. positions.push(vertex.x, vertex.y, vertex.z);
  26948. normals.push(normal.x, normal.y, normal.z);
  26949. uvs.push(faceUV[index].x, faceUV[index].w);
  26950. if (faceColors) {
  26951. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26952. }
  26953. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26954. positions.push(vertex.x, vertex.y, vertex.z);
  26955. normals.push(normal.x, normal.y, normal.z);
  26956. uvs.push(faceUV[index].x, faceUV[index].y);
  26957. if (faceColors) {
  26958. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26959. }
  26960. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26961. positions.push(vertex.x, vertex.y, vertex.z);
  26962. normals.push(normal.x, normal.y, normal.z);
  26963. uvs.push(faceUV[index].z, faceUV[index].y);
  26964. if (faceColors) {
  26965. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26966. }
  26967. }
  26968. // sides
  26969. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26970. // Result
  26971. var vertexData = new VertexData();
  26972. vertexData.indices = indices;
  26973. vertexData.positions = positions;
  26974. vertexData.normals = normals;
  26975. vertexData.uvs = uvs;
  26976. if (faceColors) {
  26977. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26978. vertexData.colors = totalColors;
  26979. }
  26980. return vertexData;
  26981. };
  26982. /**
  26983. * Creates the VertexData of the Sphere.
  26984. */
  26985. VertexData.CreateSphere = function (options) {
  26986. var segments = options.segments || 32;
  26987. var diameterX = options.diameterX || options.diameter || 1;
  26988. var diameterY = options.diameterY || options.diameter || 1;
  26989. var diameterZ = options.diameterZ || options.diameter || 1;
  26990. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26991. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26992. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26993. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26994. var totalZRotationSteps = 2 + segments;
  26995. var totalYRotationSteps = 2 * totalZRotationSteps;
  26996. var indices = [];
  26997. var positions = [];
  26998. var normals = [];
  26999. var uvs = [];
  27000. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27001. var normalizedZ = zRotationStep / totalZRotationSteps;
  27002. var angleZ = normalizedZ * Math.PI * slice;
  27003. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27004. var normalizedY = yRotationStep / totalYRotationSteps;
  27005. var angleY = normalizedY * Math.PI * 2 * arc;
  27006. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27007. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27008. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27009. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27010. var vertex = complete.multiply(radius);
  27011. var normal = complete.divide(radius).normalize();
  27012. positions.push(vertex.x, vertex.y, vertex.z);
  27013. normals.push(normal.x, normal.y, normal.z);
  27014. uvs.push(normalizedY, normalizedZ);
  27015. }
  27016. if (zRotationStep > 0) {
  27017. var verticesCount = positions.length / 3;
  27018. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27019. indices.push((firstIndex));
  27020. indices.push((firstIndex + 1));
  27021. indices.push(firstIndex + totalYRotationSteps + 1);
  27022. indices.push((firstIndex + totalYRotationSteps + 1));
  27023. indices.push((firstIndex + 1));
  27024. indices.push((firstIndex + totalYRotationSteps + 2));
  27025. }
  27026. }
  27027. }
  27028. // Sides
  27029. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27030. // Result
  27031. var vertexData = new VertexData();
  27032. vertexData.indices = indices;
  27033. vertexData.positions = positions;
  27034. vertexData.normals = normals;
  27035. vertexData.uvs = uvs;
  27036. return vertexData;
  27037. };
  27038. /**
  27039. * Creates the VertexData of the Cylinder or Cone.
  27040. */
  27041. VertexData.CreateCylinder = function (options) {
  27042. var height = options.height || 2;
  27043. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27044. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27045. var tessellation = options.tessellation || 24;
  27046. var subdivisions = options.subdivisions || 1;
  27047. var hasRings = options.hasRings;
  27048. var enclose = options.enclose;
  27049. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27050. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27051. var faceUV = options.faceUV || new Array(3);
  27052. var faceColors = options.faceColors;
  27053. // default face colors and UV if undefined
  27054. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27055. var ringNb = (hasRings) ? subdivisions : 1;
  27056. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27057. var f;
  27058. for (f = 0; f < surfaceNb; f++) {
  27059. if (faceColors && faceColors[f] === undefined) {
  27060. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27061. }
  27062. }
  27063. for (f = 0; f < surfaceNb; f++) {
  27064. if (faceUV && faceUV[f] === undefined) {
  27065. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27066. }
  27067. }
  27068. var indices = [];
  27069. var positions = [];
  27070. var normals = [];
  27071. var uvs = [];
  27072. var colors = [];
  27073. var angle_step = Math.PI * 2 * arc / tessellation;
  27074. var angle;
  27075. var h;
  27076. var radius;
  27077. var tan = (diameterBottom - diameterTop) / 2 / height;
  27078. var ringVertex = BABYLON.Vector3.Zero();
  27079. var ringNormal = BABYLON.Vector3.Zero();
  27080. var ringFirstVertex = BABYLON.Vector3.Zero();
  27081. var ringFirstNormal = BABYLON.Vector3.Zero();
  27082. var quadNormal = BABYLON.Vector3.Zero();
  27083. var Y = BABYLON.Axis.Y;
  27084. // positions, normals, uvs
  27085. var i;
  27086. var j;
  27087. var r;
  27088. var ringIdx = 1;
  27089. var s = 1; // surface index
  27090. var cs = 0;
  27091. var v = 0;
  27092. for (i = 0; i <= subdivisions; i++) {
  27093. h = i / subdivisions;
  27094. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27095. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27096. for (r = 0; r < ringIdx; r++) {
  27097. if (hasRings) {
  27098. s += r;
  27099. }
  27100. if (enclose) {
  27101. s += 2 * r;
  27102. }
  27103. for (j = 0; j <= tessellation; j++) {
  27104. angle = j * angle_step;
  27105. // position
  27106. ringVertex.x = Math.cos(-angle) * radius;
  27107. ringVertex.y = -height / 2 + h * height;
  27108. ringVertex.z = Math.sin(-angle) * radius;
  27109. // normal
  27110. if (diameterTop === 0 && i === subdivisions) {
  27111. // if no top cap, reuse former normals
  27112. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27113. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27114. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27115. }
  27116. else {
  27117. ringNormal.x = ringVertex.x;
  27118. ringNormal.z = ringVertex.z;
  27119. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27120. ringNormal.normalize();
  27121. }
  27122. // keep first ring vertex values for enclose
  27123. if (j === 0) {
  27124. ringFirstVertex.copyFrom(ringVertex);
  27125. ringFirstNormal.copyFrom(ringNormal);
  27126. }
  27127. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27128. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27129. if (hasRings) {
  27130. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27131. }
  27132. else {
  27133. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27134. }
  27135. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27136. if (faceColors) {
  27137. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27138. }
  27139. }
  27140. // if enclose, add four vertices and their dedicated normals
  27141. if (arc !== 1 && enclose) {
  27142. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27143. positions.push(0, ringVertex.y, 0);
  27144. positions.push(0, ringVertex.y, 0);
  27145. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27146. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27147. quadNormal.normalize();
  27148. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27149. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27150. quadNormal.normalize();
  27151. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27152. if (hasRings) {
  27153. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27154. }
  27155. else {
  27156. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27157. }
  27158. uvs.push(faceUV[s + 1].x, v);
  27159. uvs.push(faceUV[s + 1].z, v);
  27160. if (hasRings) {
  27161. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27162. }
  27163. else {
  27164. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27165. }
  27166. uvs.push(faceUV[s + 2].x, v);
  27167. uvs.push(faceUV[s + 2].z, v);
  27168. if (faceColors) {
  27169. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27170. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27171. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27172. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27173. }
  27174. }
  27175. if (cs !== s) {
  27176. cs = s;
  27177. }
  27178. }
  27179. }
  27180. // indices
  27181. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27182. var s;
  27183. i = 0;
  27184. for (s = 0; s < subdivisions; s++) {
  27185. for (j = 0; j < tessellation; j++) {
  27186. var i0 = i * (e + 1) + j;
  27187. var i1 = (i + 1) * (e + 1) + j;
  27188. var i2 = i * (e + 1) + (j + 1);
  27189. var i3 = (i + 1) * (e + 1) + (j + 1);
  27190. indices.push(i0, i1, i2);
  27191. indices.push(i3, i2, i1);
  27192. }
  27193. if (arc !== 1 && enclose) {
  27194. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27195. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27196. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27197. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27198. }
  27199. i = (hasRings) ? (i + 2) : (i + 1);
  27200. }
  27201. // Caps
  27202. var createCylinderCap = function (isTop) {
  27203. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27204. if (radius === 0) {
  27205. return;
  27206. }
  27207. // Cap positions, normals & uvs
  27208. var angle;
  27209. var circleVector;
  27210. var i;
  27211. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27212. var c;
  27213. if (faceColors) {
  27214. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27215. }
  27216. // cap center
  27217. var vbase = positions.length / 3;
  27218. var offset = isTop ? height / 2 : -height / 2;
  27219. var center = new BABYLON.Vector3(0, offset, 0);
  27220. positions.push(center.x, center.y, center.z);
  27221. normals.push(0, isTop ? 1 : -1, 0);
  27222. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27223. if (faceColors) {
  27224. colors.push(c.r, c.g, c.b, c.a);
  27225. }
  27226. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27227. for (i = 0; i <= tessellation; i++) {
  27228. angle = Math.PI * 2 * i * arc / tessellation;
  27229. var cos = Math.cos(-angle);
  27230. var sin = Math.sin(-angle);
  27231. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27232. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27233. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27234. normals.push(0, isTop ? 1 : -1, 0);
  27235. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27236. if (faceColors) {
  27237. colors.push(c.r, c.g, c.b, c.a);
  27238. }
  27239. }
  27240. // Cap indices
  27241. for (i = 0; i < tessellation; i++) {
  27242. if (!isTop) {
  27243. indices.push(vbase);
  27244. indices.push(vbase + (i + 1));
  27245. indices.push(vbase + (i + 2));
  27246. }
  27247. else {
  27248. indices.push(vbase);
  27249. indices.push(vbase + (i + 2));
  27250. indices.push(vbase + (i + 1));
  27251. }
  27252. }
  27253. };
  27254. // add caps to geometry
  27255. createCylinderCap(false);
  27256. createCylinderCap(true);
  27257. // Sides
  27258. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27259. var vertexData = new VertexData();
  27260. vertexData.indices = indices;
  27261. vertexData.positions = positions;
  27262. vertexData.normals = normals;
  27263. vertexData.uvs = uvs;
  27264. if (faceColors) {
  27265. vertexData.colors = colors;
  27266. }
  27267. return vertexData;
  27268. };
  27269. /**
  27270. * Creates the VertexData of the Torus.
  27271. */
  27272. VertexData.CreateTorus = function (options) {
  27273. var indices = [];
  27274. var positions = [];
  27275. var normals = [];
  27276. var uvs = [];
  27277. var diameter = options.diameter || 1;
  27278. var thickness = options.thickness || 0.5;
  27279. var tessellation = options.tessellation || 16;
  27280. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27281. var stride = tessellation + 1;
  27282. for (var i = 0; i <= tessellation; i++) {
  27283. var u = i / tessellation;
  27284. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27285. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27286. for (var j = 0; j <= tessellation; j++) {
  27287. var v = 1 - j / tessellation;
  27288. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27289. var dx = Math.cos(innerAngle);
  27290. var dy = Math.sin(innerAngle);
  27291. // Create a vertex.
  27292. var normal = new BABYLON.Vector3(dx, dy, 0);
  27293. var position = normal.scale(thickness / 2);
  27294. var textureCoordinate = new BABYLON.Vector2(u, v);
  27295. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27296. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27297. positions.push(position.x, position.y, position.z);
  27298. normals.push(normal.x, normal.y, normal.z);
  27299. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27300. // And create indices for two triangles.
  27301. var nextI = (i + 1) % stride;
  27302. var nextJ = (j + 1) % stride;
  27303. indices.push(i * stride + j);
  27304. indices.push(i * stride + nextJ);
  27305. indices.push(nextI * stride + j);
  27306. indices.push(i * stride + nextJ);
  27307. indices.push(nextI * stride + nextJ);
  27308. indices.push(nextI * stride + j);
  27309. }
  27310. }
  27311. // Sides
  27312. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27313. // Result
  27314. var vertexData = new VertexData();
  27315. vertexData.indices = indices;
  27316. vertexData.positions = positions;
  27317. vertexData.normals = normals;
  27318. vertexData.uvs = uvs;
  27319. return vertexData;
  27320. };
  27321. /**
  27322. * Creates the VertexData of the LineSystem.
  27323. */
  27324. VertexData.CreateLineSystem = function (options) {
  27325. var indices = [];
  27326. var positions = [];
  27327. var lines = options.lines;
  27328. var idx = 0;
  27329. for (var l = 0; l < lines.length; l++) {
  27330. var points = lines[l];
  27331. for (var index = 0; index < points.length; index++) {
  27332. positions.push(points[index].x, points[index].y, points[index].z);
  27333. if (index > 0) {
  27334. indices.push(idx - 1);
  27335. indices.push(idx);
  27336. }
  27337. idx++;
  27338. }
  27339. }
  27340. var vertexData = new VertexData();
  27341. vertexData.indices = indices;
  27342. vertexData.positions = positions;
  27343. return vertexData;
  27344. };
  27345. /**
  27346. * Create the VertexData of the DashedLines.
  27347. */
  27348. VertexData.CreateDashedLines = function (options) {
  27349. var dashSize = options.dashSize || 3;
  27350. var gapSize = options.gapSize || 1;
  27351. var dashNb = options.dashNb || 200;
  27352. var points = options.points;
  27353. var positions = new Array();
  27354. var indices = new Array();
  27355. var curvect = BABYLON.Vector3.Zero();
  27356. var lg = 0;
  27357. var nb = 0;
  27358. var shft = 0;
  27359. var dashshft = 0;
  27360. var curshft = 0;
  27361. var idx = 0;
  27362. var i = 0;
  27363. for (i = 0; i < points.length - 1; i++) {
  27364. points[i + 1].subtractToRef(points[i], curvect);
  27365. lg += curvect.length();
  27366. }
  27367. shft = lg / dashNb;
  27368. dashshft = dashSize * shft / (dashSize + gapSize);
  27369. for (i = 0; i < points.length - 1; i++) {
  27370. points[i + 1].subtractToRef(points[i], curvect);
  27371. nb = Math.floor(curvect.length() / shft);
  27372. curvect.normalize();
  27373. for (var j = 0; j < nb; j++) {
  27374. curshft = shft * j;
  27375. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27376. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27377. indices.push(idx, idx + 1);
  27378. idx += 2;
  27379. }
  27380. }
  27381. // Result
  27382. var vertexData = new VertexData();
  27383. vertexData.positions = positions;
  27384. vertexData.indices = indices;
  27385. return vertexData;
  27386. };
  27387. /**
  27388. * Creates the VertexData of the Ground.
  27389. */
  27390. VertexData.CreateGround = function (options) {
  27391. var indices = [];
  27392. var positions = [];
  27393. var normals = [];
  27394. var uvs = [];
  27395. var row, col;
  27396. var width = options.width || 1;
  27397. var height = options.height || 1;
  27398. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27399. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27400. for (row = 0; row <= subdivisionsY; row++) {
  27401. for (col = 0; col <= subdivisionsX; col++) {
  27402. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27403. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27404. positions.push(position.x, position.y, position.z);
  27405. normals.push(normal.x, normal.y, normal.z);
  27406. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27407. }
  27408. }
  27409. for (row = 0; row < subdivisionsY; row++) {
  27410. for (col = 0; col < subdivisionsX; col++) {
  27411. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27412. indices.push(col + 1 + row * (subdivisionsX + 1));
  27413. indices.push(col + row * (subdivisionsX + 1));
  27414. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27415. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27416. indices.push(col + row * (subdivisionsX + 1));
  27417. }
  27418. }
  27419. // Result
  27420. var vertexData = new VertexData();
  27421. vertexData.indices = indices;
  27422. vertexData.positions = positions;
  27423. vertexData.normals = normals;
  27424. vertexData.uvs = uvs;
  27425. return vertexData;
  27426. };
  27427. /**
  27428. * Creates the VertexData of the TiledGround.
  27429. */
  27430. VertexData.CreateTiledGround = function (options) {
  27431. var xmin = options.xmin || -1.0;
  27432. var zmin = options.zmin || -1.0;
  27433. var xmax = options.xmax || 1.0;
  27434. var zmax = options.zmax || 1.0;
  27435. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27436. var precision = options.precision || { w: 1, h: 1 };
  27437. var indices = [];
  27438. var positions = [];
  27439. var normals = [];
  27440. var uvs = [];
  27441. var row, col, tileRow, tileCol;
  27442. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27443. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27444. precision.w = (precision.w < 1) ? 1 : precision.w;
  27445. precision.h = (precision.h < 1) ? 1 : precision.h;
  27446. var tileSize = {
  27447. 'w': (xmax - xmin) / subdivisions.w,
  27448. 'h': (zmax - zmin) / subdivisions.h
  27449. };
  27450. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27451. // Indices
  27452. var base = positions.length / 3;
  27453. var rowLength = precision.w + 1;
  27454. for (row = 0; row < precision.h; row++) {
  27455. for (col = 0; col < precision.w; col++) {
  27456. var square = [
  27457. base + col + row * rowLength,
  27458. base + (col + 1) + row * rowLength,
  27459. base + (col + 1) + (row + 1) * rowLength,
  27460. base + col + (row + 1) * rowLength
  27461. ];
  27462. indices.push(square[1]);
  27463. indices.push(square[2]);
  27464. indices.push(square[3]);
  27465. indices.push(square[0]);
  27466. indices.push(square[1]);
  27467. indices.push(square[3]);
  27468. }
  27469. }
  27470. // Position, normals and uvs
  27471. var position = BABYLON.Vector3.Zero();
  27472. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27473. for (row = 0; row <= precision.h; row++) {
  27474. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27475. for (col = 0; col <= precision.w; col++) {
  27476. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27477. position.y = 0;
  27478. positions.push(position.x, position.y, position.z);
  27479. normals.push(normal.x, normal.y, normal.z);
  27480. uvs.push(col / precision.w, row / precision.h);
  27481. }
  27482. }
  27483. }
  27484. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27485. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27486. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27487. }
  27488. }
  27489. // Result
  27490. var vertexData = new VertexData();
  27491. vertexData.indices = indices;
  27492. vertexData.positions = positions;
  27493. vertexData.normals = normals;
  27494. vertexData.uvs = uvs;
  27495. return vertexData;
  27496. };
  27497. /**
  27498. * Creates the VertexData of the Ground designed from a heightmap.
  27499. */
  27500. VertexData.CreateGroundFromHeightMap = function (options) {
  27501. var indices = [];
  27502. var positions = [];
  27503. var normals = [];
  27504. var uvs = [];
  27505. var row, col;
  27506. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27507. // Vertices
  27508. for (row = 0; row <= options.subdivisions; row++) {
  27509. for (col = 0; col <= options.subdivisions; col++) {
  27510. 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));
  27511. // Compute height
  27512. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27513. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27514. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27515. var r = options.buffer[pos] / 255.0;
  27516. var g = options.buffer[pos + 1] / 255.0;
  27517. var b = options.buffer[pos + 2] / 255.0;
  27518. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27519. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27520. // Add vertex
  27521. positions.push(position.x, position.y, position.z);
  27522. normals.push(0, 0, 0);
  27523. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27524. }
  27525. }
  27526. // Indices
  27527. for (row = 0; row < options.subdivisions; row++) {
  27528. for (col = 0; col < options.subdivisions; col++) {
  27529. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27530. indices.push(col + 1 + row * (options.subdivisions + 1));
  27531. indices.push(col + row * (options.subdivisions + 1));
  27532. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27533. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27534. indices.push(col + row * (options.subdivisions + 1));
  27535. }
  27536. }
  27537. // Normals
  27538. VertexData.ComputeNormals(positions, indices, normals);
  27539. // Result
  27540. var vertexData = new VertexData();
  27541. vertexData.indices = indices;
  27542. vertexData.positions = positions;
  27543. vertexData.normals = normals;
  27544. vertexData.uvs = uvs;
  27545. return vertexData;
  27546. };
  27547. /**
  27548. * Creates the VertexData of the Plane.
  27549. */
  27550. VertexData.CreatePlane = function (options) {
  27551. var indices = [];
  27552. var positions = [];
  27553. var normals = [];
  27554. var uvs = [];
  27555. var width = options.width || options.size || 1;
  27556. var height = options.height || options.size || 1;
  27557. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27558. // Vertices
  27559. var halfWidth = width / 2.0;
  27560. var halfHeight = height / 2.0;
  27561. positions.push(-halfWidth, -halfHeight, 0);
  27562. normals.push(0, 0, -1.0);
  27563. uvs.push(0.0, 0.0);
  27564. positions.push(halfWidth, -halfHeight, 0);
  27565. normals.push(0, 0, -1.0);
  27566. uvs.push(1.0, 0.0);
  27567. positions.push(halfWidth, halfHeight, 0);
  27568. normals.push(0, 0, -1.0);
  27569. uvs.push(1.0, 1.0);
  27570. positions.push(-halfWidth, halfHeight, 0);
  27571. normals.push(0, 0, -1.0);
  27572. uvs.push(0.0, 1.0);
  27573. // Indices
  27574. indices.push(0);
  27575. indices.push(1);
  27576. indices.push(2);
  27577. indices.push(0);
  27578. indices.push(2);
  27579. indices.push(3);
  27580. // Sides
  27581. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27582. // Result
  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. * Creates the VertexData of the Disc or regular Polygon.
  27592. */
  27593. VertexData.CreateDisc = function (options) {
  27594. var positions = [];
  27595. var indices = [];
  27596. var normals = [];
  27597. var uvs = [];
  27598. var radius = options.radius || 0.5;
  27599. var tessellation = options.tessellation || 64;
  27600. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27601. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27602. // positions and uvs
  27603. positions.push(0, 0, 0); // disc center first
  27604. uvs.push(0.5, 0.5);
  27605. var theta = Math.PI * 2 * arc;
  27606. var step = theta / tessellation;
  27607. for (var a = 0; a < theta; a += step) {
  27608. var x = Math.cos(a);
  27609. var y = Math.sin(a);
  27610. var u = (x + 1) / 2;
  27611. var v = (1 - y) / 2;
  27612. positions.push(radius * x, radius * y, 0);
  27613. uvs.push(u, v);
  27614. }
  27615. if (arc === 1) {
  27616. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27617. uvs.push(uvs[2], uvs[3]);
  27618. }
  27619. //indices
  27620. var vertexNb = positions.length / 3;
  27621. for (var i = 1; i < vertexNb - 1; i++) {
  27622. indices.push(i + 1, 0, i);
  27623. }
  27624. // result
  27625. VertexData.ComputeNormals(positions, indices, normals);
  27626. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27627. var vertexData = new VertexData();
  27628. vertexData.indices = indices;
  27629. vertexData.positions = positions;
  27630. vertexData.normals = normals;
  27631. vertexData.uvs = uvs;
  27632. return vertexData;
  27633. };
  27634. /**
  27635. * Re-creates the VertexData of the Polygon for sideOrientation.
  27636. */
  27637. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  27638. var faceUV = fUV || new Array(3);
  27639. var faceColors = fColors;
  27640. var colors = [];
  27641. // default face colors and UV if undefined
  27642. for (var f = 0; f < 3; f++) {
  27643. if (faceUV[f] === undefined) {
  27644. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27645. }
  27646. if (faceColors && faceColors[f] === undefined) {
  27647. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27648. }
  27649. }
  27650. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27651. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27652. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27653. var indices = polygon.getIndices();
  27654. // set face colours and textures
  27655. var idx = 0;
  27656. var face = 0;
  27657. for (var index = 0; index < normals.length; index += 3) {
  27658. //Edge Face no. 1
  27659. if (Math.abs(normals[index + 1]) < 0.001) {
  27660. face = 1;
  27661. }
  27662. //Top Face no. 0
  27663. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  27664. face = 0;
  27665. }
  27666. //Bottom Face no. 2
  27667. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  27668. face = 2;
  27669. }
  27670. idx = index / 3;
  27671. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  27672. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  27673. if (faceColors) {
  27674. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  27675. }
  27676. }
  27677. // sides
  27678. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  27679. // Result
  27680. var vertexData = new VertexData();
  27681. vertexData.indices = indices;
  27682. vertexData.positions = positions;
  27683. vertexData.normals = normals;
  27684. vertexData.uvs = uvs;
  27685. if (faceColors) {
  27686. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27687. vertexData.colors = totalColors;
  27688. }
  27689. return vertexData;
  27690. };
  27691. /**
  27692. * Creates the VertexData of the IcoSphere.
  27693. */
  27694. VertexData.CreateIcoSphere = function (options) {
  27695. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27696. var radius = options.radius || 1;
  27697. var flat = (options.flat === undefined) ? true : options.flat;
  27698. var subdivisions = options.subdivisions || 4;
  27699. var radiusX = options.radiusX || radius;
  27700. var radiusY = options.radiusY || radius;
  27701. var radiusZ = options.radiusZ || radius;
  27702. var t = (1 + Math.sqrt(5)) / 2;
  27703. // 12 vertex x,y,z
  27704. var ico_vertices = [
  27705. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27706. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27707. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27708. ];
  27709. // index of 3 vertex makes a face of icopshere
  27710. var ico_indices = [
  27711. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27712. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27713. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27714. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27715. ];
  27716. // vertex for uv have aliased position, not for UV
  27717. var vertices_unalias_id = [
  27718. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27719. // vertex alias
  27720. 0,
  27721. 2,
  27722. 3,
  27723. 3,
  27724. 3,
  27725. 4,
  27726. 7,
  27727. 8,
  27728. 9,
  27729. 9,
  27730. 10,
  27731. 11 // 23: B + 12
  27732. ];
  27733. // uv as integer step (not pixels !)
  27734. var ico_vertexuv = [
  27735. 5, 1, 3, 1, 6, 4, 0, 0,
  27736. 5, 3, 4, 2, 2, 2, 4, 0,
  27737. 2, 0, 1, 1, 6, 0, 6, 2,
  27738. // vertex alias (for same vertex on different faces)
  27739. 0, 4,
  27740. 3, 3,
  27741. 4, 4,
  27742. 3, 1,
  27743. 4, 2,
  27744. 4, 4,
  27745. 0, 2,
  27746. 1, 1,
  27747. 2, 2,
  27748. 3, 3,
  27749. 1, 3,
  27750. 2, 4 // 23: B + 12
  27751. ];
  27752. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27753. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27754. // First island of uv mapping
  27755. // v = 4h 3+ 2
  27756. // v = 3h 9+ 4
  27757. // v = 2h 9+ 5 B
  27758. // v = 1h 9 1 0
  27759. // v = 0h 3 8 7 A
  27760. // u = 0 1 2 3 4 5 6 *a
  27761. // Second island of uv mapping
  27762. // v = 4h 0+ B+ 4+
  27763. // v = 3h A+ 2+
  27764. // v = 2h 7+ 6 3+
  27765. // v = 1h 8+ 3+
  27766. // v = 0h
  27767. // u = 0 1 2 3 4 5 6 *a
  27768. // Face layout on texture UV mapping
  27769. // ============
  27770. // \ 4 /\ 16 / ======
  27771. // \ / \ / /\ 11 /
  27772. // \/ 7 \/ / \ /
  27773. // ======= / 10 \/
  27774. // /\ 17 /\ =======
  27775. // / \ / \ \ 15 /\
  27776. // / 8 \/ 12 \ \ / \
  27777. // ============ \/ 6 \
  27778. // \ 18 /\ ============
  27779. // \ / \ \ 5 /\ 0 /
  27780. // \/ 13 \ \ / \ /
  27781. // ======= \/ 1 \/
  27782. // =============
  27783. // /\ 19 /\ 2 /\
  27784. // / \ / \ / \
  27785. // / 14 \/ 9 \/ 3 \
  27786. // ===================
  27787. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27788. var ustep = 138 / 1024;
  27789. var vstep = 239 / 1024;
  27790. var uoffset = 60 / 1024;
  27791. var voffset = 26 / 1024;
  27792. // Second island should have margin, not to touch the first island
  27793. // avoid any borderline artefact in pixel rounding
  27794. var island_u_offset = -40 / 1024;
  27795. var island_v_offset = +20 / 1024;
  27796. // face is either island 0 or 1 :
  27797. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27798. var island = [
  27799. 0, 0, 0, 0, 1,
  27800. 0, 0, 1, 1, 0,
  27801. 0, 0, 1, 1, 0,
  27802. 0, 1, 1, 1, 0 // 15 - 19
  27803. ];
  27804. var indices = [];
  27805. var positions = [];
  27806. var normals = [];
  27807. var uvs = [];
  27808. var current_indice = 0;
  27809. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27810. var face_vertex_pos = new Array(3);
  27811. var face_vertex_uv = new Array(3);
  27812. var v012;
  27813. for (v012 = 0; v012 < 3; v012++) {
  27814. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27815. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27816. }
  27817. // create all with normals
  27818. for (var face = 0; face < 20; face++) {
  27819. // 3 vertex per face
  27820. for (v012 = 0; v012 < 3; v012++) {
  27821. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27822. var v_id = ico_indices[3 * face + v012];
  27823. // vertex have 3D position (x,y,z)
  27824. 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]);
  27825. // Normalize to get normal, then scale to radius
  27826. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27827. // uv Coordinates from vertex ID
  27828. 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);
  27829. }
  27830. // Subdivide the face (interpolate pos, norm, uv)
  27831. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27832. // - norm is linear interpolation of vertex corner normal
  27833. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27834. // - uv is linear interpolation
  27835. //
  27836. // Topology is as below for sub-divide by 2
  27837. // vertex shown as v0,v1,v2
  27838. // interp index is i1 to progress in range [v0,v1[
  27839. // interp index is i2 to progress in range [v0,v2[
  27840. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27841. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27842. //
  27843. //
  27844. // i2 v2
  27845. // ^ ^
  27846. // / / \
  27847. // / / \
  27848. // / / \
  27849. // / / (0,1) \
  27850. // / #---------\
  27851. // / / \ (0,0)'/ \
  27852. // / / \ / \
  27853. // / / \ / \
  27854. // / / (0,0) \ / (1,0) \
  27855. // / #---------#---------\
  27856. // v0 v1
  27857. //
  27858. // --------------------> i1
  27859. //
  27860. // interp of (i1,i2):
  27861. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27862. // along i1 : lerp(x0,x1, i1/(S-i2))
  27863. //
  27864. // centroid of triangle is needed to get help normal computation
  27865. // (c1,c2) are used for centroid location
  27866. var interp_vertex = function (i1, i2, c1, c2) {
  27867. // vertex is interpolated from
  27868. // - face_vertex_pos[0..2]
  27869. // - face_vertex_uv[0..2]
  27870. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  27871. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  27872. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  27873. pos_interp.normalize();
  27874. var vertex_normal;
  27875. if (flat) {
  27876. // in flat mode, recalculate normal as face centroid normal
  27877. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  27878. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  27879. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  27880. }
  27881. else {
  27882. // in smooth mode, recalculate normal from each single vertex position
  27883. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  27884. }
  27885. // Vertex normal need correction due to X,Y,Z radius scaling
  27886. vertex_normal.x /= radiusX;
  27887. vertex_normal.y /= radiusY;
  27888. vertex_normal.z /= radiusZ;
  27889. vertex_normal.normalize();
  27890. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  27891. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  27892. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  27893. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  27894. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  27895. uvs.push(uv_interp.x, uv_interp.y);
  27896. // push each vertex has member of a face
  27897. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  27898. indices.push(current_indice);
  27899. current_indice++;
  27900. };
  27901. for (var i2 = 0; i2 < subdivisions; i2++) {
  27902. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  27903. // face : (i1,i2) for /\ :
  27904. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  27905. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27906. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27907. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27908. if (i1 + i2 + 1 < subdivisions) {
  27909. // face : (i1,i2)' for \/ :
  27910. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27911. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27912. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27913. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27914. }
  27915. }
  27916. }
  27917. }
  27918. // Sides
  27919. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27920. // Result
  27921. var vertexData = new VertexData();
  27922. vertexData.indices = indices;
  27923. vertexData.positions = positions;
  27924. vertexData.normals = normals;
  27925. vertexData.uvs = uvs;
  27926. return vertexData;
  27927. };
  27928. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  27929. /**
  27930. * Creates the VertexData of the Polyhedron.
  27931. */
  27932. VertexData.CreatePolyhedron = function (options) {
  27933. // provided polyhedron types :
  27934. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  27935. // 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)
  27936. var polyhedra = [];
  27937. 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]] };
  27938. 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]] };
  27939. polyhedra[2] = {
  27940. 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]],
  27941. 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]]
  27942. };
  27943. polyhedra[3] = {
  27944. 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]],
  27945. 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]]
  27946. };
  27947. polyhedra[4] = {
  27948. 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]],
  27949. 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]]
  27950. };
  27951. 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]] };
  27952. 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]] };
  27953. 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]] };
  27954. 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]] };
  27955. 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]] };
  27956. 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]] };
  27957. 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]] };
  27958. 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]] };
  27959. 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]] };
  27960. polyhedra[14] = {
  27961. 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]],
  27962. 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]]
  27963. };
  27964. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  27965. var size = options.size;
  27966. var sizeX = options.sizeX || size || 1;
  27967. var sizeY = options.sizeY || size || 1;
  27968. var sizeZ = options.sizeZ || size || 1;
  27969. var data = options.custom || polyhedra[type];
  27970. var nbfaces = data.face.length;
  27971. var faceUV = options.faceUV || new Array(nbfaces);
  27972. var faceColors = options.faceColors;
  27973. var flat = (options.flat === undefined) ? true : options.flat;
  27974. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27975. var positions = [];
  27976. var indices = [];
  27977. var normals = [];
  27978. var uvs = [];
  27979. var colors = [];
  27980. var index = 0;
  27981. var faceIdx = 0; // face cursor in the array "indexes"
  27982. var indexes = [];
  27983. var i = 0;
  27984. var f = 0;
  27985. var u, v, ang, x, y, tmp;
  27986. // default face colors and UV if undefined
  27987. if (flat) {
  27988. for (f = 0; f < nbfaces; f++) {
  27989. if (faceColors && faceColors[f] === undefined) {
  27990. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27991. }
  27992. if (faceUV && faceUV[f] === undefined) {
  27993. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27994. }
  27995. }
  27996. }
  27997. if (!flat) {
  27998. for (i = 0; i < data.vertex.length; i++) {
  27999. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28000. uvs.push(0, 0);
  28001. }
  28002. for (f = 0; f < nbfaces; f++) {
  28003. for (i = 0; i < data.face[f].length - 2; i++) {
  28004. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28005. }
  28006. }
  28007. }
  28008. else {
  28009. for (f = 0; f < nbfaces; f++) {
  28010. var fl = data.face[f].length; // number of vertices of the current face
  28011. ang = 2 * Math.PI / fl;
  28012. x = 0.5 * Math.tan(ang / 2);
  28013. y = 0.5;
  28014. // positions, uvs, colors
  28015. for (i = 0; i < fl; i++) {
  28016. // positions
  28017. 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);
  28018. indexes.push(index);
  28019. index++;
  28020. // uvs
  28021. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28022. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28023. uvs.push(u, v);
  28024. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28025. y = x * Math.sin(ang) + y * Math.cos(ang);
  28026. x = tmp;
  28027. // colors
  28028. if (faceColors) {
  28029. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28030. }
  28031. }
  28032. // indices from indexes
  28033. for (i = 0; i < fl - 2; i++) {
  28034. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28035. }
  28036. faceIdx += fl;
  28037. }
  28038. }
  28039. VertexData.ComputeNormals(positions, indices, normals);
  28040. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28041. var vertexData = new VertexData();
  28042. vertexData.positions = positions;
  28043. vertexData.indices = indices;
  28044. vertexData.normals = normals;
  28045. vertexData.uvs = uvs;
  28046. if (faceColors && flat) {
  28047. vertexData.colors = colors;
  28048. }
  28049. return vertexData;
  28050. };
  28051. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28052. /**
  28053. * Creates the VertexData of the Torus Knot.
  28054. */
  28055. VertexData.CreateTorusKnot = function (options) {
  28056. var indices = [];
  28057. var positions = [];
  28058. var normals = [];
  28059. var uvs = [];
  28060. var radius = options.radius || 2;
  28061. var tube = options.tube || 0.5;
  28062. var radialSegments = options.radialSegments || 32;
  28063. var tubularSegments = options.tubularSegments || 32;
  28064. var p = options.p || 2;
  28065. var q = options.q || 3;
  28066. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28067. // Helper
  28068. var getPos = function (angle) {
  28069. var cu = Math.cos(angle);
  28070. var su = Math.sin(angle);
  28071. var quOverP = q / p * angle;
  28072. var cs = Math.cos(quOverP);
  28073. var tx = radius * (2 + cs) * 0.5 * cu;
  28074. var ty = radius * (2 + cs) * su * 0.5;
  28075. var tz = radius * Math.sin(quOverP) * 0.5;
  28076. return new BABYLON.Vector3(tx, ty, tz);
  28077. };
  28078. // Vertices
  28079. var i;
  28080. var j;
  28081. for (i = 0; i <= radialSegments; i++) {
  28082. var modI = i % radialSegments;
  28083. var u = modI / radialSegments * 2 * p * Math.PI;
  28084. var p1 = getPos(u);
  28085. var p2 = getPos(u + 0.01);
  28086. var tang = p2.subtract(p1);
  28087. var n = p2.add(p1);
  28088. var bitan = BABYLON.Vector3.Cross(tang, n);
  28089. n = BABYLON.Vector3.Cross(bitan, tang);
  28090. bitan.normalize();
  28091. n.normalize();
  28092. for (j = 0; j < tubularSegments; j++) {
  28093. var modJ = j % tubularSegments;
  28094. var v = modJ / tubularSegments * 2 * Math.PI;
  28095. var cx = -tube * Math.cos(v);
  28096. var cy = tube * Math.sin(v);
  28097. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28098. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28099. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28100. uvs.push(i / radialSegments);
  28101. uvs.push(j / tubularSegments);
  28102. }
  28103. }
  28104. for (i = 0; i < radialSegments; i++) {
  28105. for (j = 0; j < tubularSegments; j++) {
  28106. var jNext = (j + 1) % tubularSegments;
  28107. var a = i * tubularSegments + j;
  28108. var b = (i + 1) * tubularSegments + j;
  28109. var c = (i + 1) * tubularSegments + jNext;
  28110. var d = i * tubularSegments + jNext;
  28111. indices.push(d);
  28112. indices.push(b);
  28113. indices.push(a);
  28114. indices.push(d);
  28115. indices.push(c);
  28116. indices.push(b);
  28117. }
  28118. }
  28119. // Normals
  28120. VertexData.ComputeNormals(positions, indices, normals);
  28121. // Sides
  28122. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28123. // Result
  28124. var vertexData = new VertexData();
  28125. vertexData.indices = indices;
  28126. vertexData.positions = positions;
  28127. vertexData.normals = normals;
  28128. vertexData.uvs = uvs;
  28129. return vertexData;
  28130. };
  28131. // Tools
  28132. /**
  28133. * @param {any} - positions (number[] or Float32Array)
  28134. * @param {any} - indices (number[] or Uint16Array)
  28135. * @param {any} - normals (number[] or Float32Array)
  28136. * options (optional) :
  28137. * facetPositions : optional array of facet positions (vector3)
  28138. * facetNormals : optional array of facet normals (vector3)
  28139. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28140. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28141. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28142. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28143. * bInfo : optional bounding info, required for facetPartitioning computation
  28144. */
  28145. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28146. // temporary scalar variables
  28147. var index = 0; // facet index
  28148. var p1p2x = 0.0; // p1p2 vector x coordinate
  28149. var p1p2y = 0.0; // p1p2 vector y coordinate
  28150. var p1p2z = 0.0; // p1p2 vector z coordinate
  28151. var p3p2x = 0.0; // p3p2 vector x coordinate
  28152. var p3p2y = 0.0; // p3p2 vector y coordinate
  28153. var p3p2z = 0.0; // p3p2 vector z coordinate
  28154. var faceNormalx = 0.0; // facet normal x coordinate
  28155. var faceNormaly = 0.0; // facet normal y coordinate
  28156. var faceNormalz = 0.0; // facet normal z coordinate
  28157. var length = 0.0; // facet normal length before normalization
  28158. var v1x = 0; // vector1 x index in the positions array
  28159. var v1y = 0; // vector1 y index in the positions array
  28160. var v1z = 0; // vector1 z index in the positions array
  28161. var v2x = 0; // vector2 x index in the positions array
  28162. var v2y = 0; // vector2 y index in the positions array
  28163. var v2z = 0; // vector2 z index in the positions array
  28164. var v3x = 0; // vector3 x index in the positions array
  28165. var v3y = 0; // vector3 y index in the positions array
  28166. var v3z = 0; // vector3 z index in the positions array
  28167. var computeFacetNormals = false;
  28168. var computeFacetPositions = false;
  28169. var computeFacetPartitioning = false;
  28170. var faceNormalSign = 1;
  28171. if (options) {
  28172. computeFacetNormals = (options.facetNormals) ? true : false;
  28173. computeFacetPositions = (options.facetPositions) ? true : false;
  28174. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28175. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28176. }
  28177. // facetPartitioning reinit if needed
  28178. if (computeFacetPartitioning) {
  28179. var ox = 0; // X partitioning index for facet position
  28180. var oy = 0; // Y partinioning index for facet position
  28181. var oz = 0; // Z partinioning index for facet position
  28182. var b1x = 0; // X partitioning index for facet v1 vertex
  28183. var b1y = 0; // Y partitioning index for facet v1 vertex
  28184. var b1z = 0; // z partitioning index for facet v1 vertex
  28185. var b2x = 0; // X partitioning index for facet v2 vertex
  28186. var b2y = 0; // Y partitioning index for facet v2 vertex
  28187. var b2z = 0; // Z partitioning index for facet v2 vertex
  28188. var b3x = 0; // X partitioning index for facet v3 vertex
  28189. var b3y = 0; // Y partitioning index for facet v3 vertex
  28190. var b3z = 0; // Z partitioning index for facet v3 vertex
  28191. var block_idx_o = 0; // facet barycenter block index
  28192. var block_idx_v1 = 0; // v1 vertex block index
  28193. var block_idx_v2 = 0; // v2 vertex block index
  28194. var block_idx_v3 = 0; // v3 vertex block index
  28195. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28196. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28197. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28198. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28199. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28200. var subSq = options.subDiv.max * options.subDiv.max;
  28201. options.facetPartitioning.length = 0;
  28202. }
  28203. // reset the normals
  28204. for (index = 0; index < positions.length; index++) {
  28205. normals[index] = 0.0;
  28206. }
  28207. // Loop : 1 indice triplet = 1 facet
  28208. var nbFaces = indices.length / 3;
  28209. for (index = 0; index < nbFaces; index++) {
  28210. // get the indexes of the coordinates of each vertex of the facet
  28211. v1x = indices[index * 3] * 3;
  28212. v1y = v1x + 1;
  28213. v1z = v1x + 2;
  28214. v2x = indices[index * 3 + 1] * 3;
  28215. v2y = v2x + 1;
  28216. v2z = v2x + 2;
  28217. v3x = indices[index * 3 + 2] * 3;
  28218. v3y = v3x + 1;
  28219. v3z = v3x + 2;
  28220. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28221. p1p2y = positions[v1y] - positions[v2y];
  28222. p1p2z = positions[v1z] - positions[v2z];
  28223. p3p2x = positions[v3x] - positions[v2x];
  28224. p3p2y = positions[v3y] - positions[v2y];
  28225. p3p2z = positions[v3z] - positions[v2z];
  28226. // compute the face normal with the cross product
  28227. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28228. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28229. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28230. // normalize this normal and store it in the array facetData
  28231. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28232. length = (length === 0) ? 1.0 : length;
  28233. faceNormalx /= length;
  28234. faceNormaly /= length;
  28235. faceNormalz /= length;
  28236. if (computeFacetNormals) {
  28237. options.facetNormals[index].x = faceNormalx;
  28238. options.facetNormals[index].y = faceNormaly;
  28239. options.facetNormals[index].z = faceNormalz;
  28240. }
  28241. if (computeFacetPositions) {
  28242. // compute and the facet barycenter coordinates in the array facetPositions
  28243. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28244. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28245. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28246. }
  28247. if (computeFacetPartitioning) {
  28248. // store the facet indexes in arrays in the main facetPartitioning array :
  28249. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28250. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28251. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28252. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28253. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28254. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28255. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28256. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28257. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28258. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28259. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28260. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28261. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28262. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28263. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28264. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28265. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28266. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28267. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28268. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28269. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28270. // push each facet index in each block containing the vertex
  28271. options.facetPartitioning[block_idx_v1].push(index);
  28272. if (block_idx_v2 != block_idx_v1) {
  28273. options.facetPartitioning[block_idx_v2].push(index);
  28274. }
  28275. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28276. options.facetPartitioning[block_idx_v3].push(index);
  28277. }
  28278. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28279. options.facetPartitioning[block_idx_o].push(index);
  28280. }
  28281. }
  28282. // compute the normals anyway
  28283. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28284. normals[v1y] += faceNormaly;
  28285. normals[v1z] += faceNormalz;
  28286. normals[v2x] += faceNormalx;
  28287. normals[v2y] += faceNormaly;
  28288. normals[v2z] += faceNormalz;
  28289. normals[v3x] += faceNormalx;
  28290. normals[v3y] += faceNormaly;
  28291. normals[v3z] += faceNormalz;
  28292. }
  28293. // last normalization of each normal
  28294. for (index = 0; index < normals.length / 3; index++) {
  28295. faceNormalx = normals[index * 3];
  28296. faceNormaly = normals[index * 3 + 1];
  28297. faceNormalz = normals[index * 3 + 2];
  28298. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28299. length = (length === 0) ? 1.0 : length;
  28300. faceNormalx /= length;
  28301. faceNormaly /= length;
  28302. faceNormalz /= length;
  28303. normals[index * 3] = faceNormalx;
  28304. normals[index * 3 + 1] = faceNormaly;
  28305. normals[index * 3 + 2] = faceNormalz;
  28306. }
  28307. };
  28308. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28309. var li = indices.length;
  28310. var ln = normals.length;
  28311. var i;
  28312. var n;
  28313. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28314. switch (sideOrientation) {
  28315. case BABYLON.Mesh.FRONTSIDE:
  28316. // nothing changed
  28317. break;
  28318. case BABYLON.Mesh.BACKSIDE:
  28319. var tmp;
  28320. // indices
  28321. for (i = 0; i < li; i += 3) {
  28322. tmp = indices[i];
  28323. indices[i] = indices[i + 2];
  28324. indices[i + 2] = tmp;
  28325. }
  28326. // normals
  28327. for (n = 0; n < ln; n++) {
  28328. normals[n] = -normals[n];
  28329. }
  28330. break;
  28331. case BABYLON.Mesh.DOUBLESIDE:
  28332. // positions
  28333. var lp = positions.length;
  28334. var l = lp / 3;
  28335. for (var p = 0; p < lp; p++) {
  28336. positions[lp + p] = positions[p];
  28337. }
  28338. // indices
  28339. for (i = 0; i < li; i += 3) {
  28340. indices[i + li] = indices[i + 2] + l;
  28341. indices[i + 1 + li] = indices[i + 1] + l;
  28342. indices[i + 2 + li] = indices[i] + l;
  28343. }
  28344. // normals
  28345. for (n = 0; n < ln; n++) {
  28346. normals[ln + n] = -normals[n];
  28347. }
  28348. // uvs
  28349. var lu = uvs.length;
  28350. var u = 0;
  28351. for (u = 0; u < lu; u++) {
  28352. uvs[u + lu] = uvs[u];
  28353. }
  28354. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28355. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28356. u = 0;
  28357. for (i = 0; i < lu / 2; i++) {
  28358. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28359. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28360. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28361. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28362. u += 2;
  28363. }
  28364. break;
  28365. }
  28366. };
  28367. /**
  28368. * Creates a new VertexData from the imported parameters.
  28369. */
  28370. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28371. var vertexData = new VertexData();
  28372. // positions
  28373. var positions = parsedVertexData.positions;
  28374. if (positions) {
  28375. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28376. }
  28377. // normals
  28378. var normals = parsedVertexData.normals;
  28379. if (normals) {
  28380. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28381. }
  28382. // tangents
  28383. var tangents = parsedVertexData.tangents;
  28384. if (tangents) {
  28385. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28386. }
  28387. // uvs
  28388. var uvs = parsedVertexData.uvs;
  28389. if (uvs) {
  28390. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28391. }
  28392. // uv2s
  28393. var uv2s = parsedVertexData.uv2s;
  28394. if (uv2s) {
  28395. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28396. }
  28397. // uv3s
  28398. var uv3s = parsedVertexData.uv3s;
  28399. if (uv3s) {
  28400. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28401. }
  28402. // uv4s
  28403. var uv4s = parsedVertexData.uv4s;
  28404. if (uv4s) {
  28405. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28406. }
  28407. // uv5s
  28408. var uv5s = parsedVertexData.uv5s;
  28409. if (uv5s) {
  28410. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28411. }
  28412. // uv6s
  28413. var uv6s = parsedVertexData.uv6s;
  28414. if (uv6s) {
  28415. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28416. }
  28417. // colors
  28418. var colors = parsedVertexData.colors;
  28419. if (colors) {
  28420. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28421. }
  28422. // matricesIndices
  28423. var matricesIndices = parsedVertexData.matricesIndices;
  28424. if (matricesIndices) {
  28425. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28426. }
  28427. // matricesWeights
  28428. var matricesWeights = parsedVertexData.matricesWeights;
  28429. if (matricesWeights) {
  28430. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28431. }
  28432. // indices
  28433. var indices = parsedVertexData.indices;
  28434. if (indices) {
  28435. vertexData.indices = indices;
  28436. }
  28437. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28438. };
  28439. return VertexData;
  28440. }());
  28441. BABYLON.VertexData = VertexData;
  28442. })(BABYLON || (BABYLON = {}));
  28443. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28444. var BABYLON;
  28445. (function (BABYLON) {
  28446. var Geometry = (function () {
  28447. function Geometry(id, scene, vertexData, updatable, mesh) {
  28448. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28449. this._totalVertices = 0;
  28450. this._isDisposed = false;
  28451. this.id = id;
  28452. this._engine = scene.getEngine();
  28453. this._meshes = [];
  28454. this._scene = scene;
  28455. //Init vertex buffer cache
  28456. this._vertexBuffers = {};
  28457. this._indices = [];
  28458. this._updatable = updatable;
  28459. // vertexData
  28460. if (vertexData) {
  28461. this.setAllVerticesData(vertexData, updatable);
  28462. }
  28463. else {
  28464. this._totalVertices = 0;
  28465. this._indices = [];
  28466. }
  28467. if (this._engine.getCaps().vertexArrayObject) {
  28468. this._vertexArrayObjects = {};
  28469. }
  28470. // applyToMesh
  28471. if (mesh) {
  28472. if (mesh.getClassName() === "LinesMesh") {
  28473. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28474. this.updateExtend();
  28475. }
  28476. this.applyToMesh(mesh);
  28477. mesh.computeWorldMatrix(true);
  28478. }
  28479. }
  28480. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28481. /**
  28482. * 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
  28483. * @returns The Bias Vector
  28484. */
  28485. get: function () {
  28486. return this._boundingBias;
  28487. },
  28488. set: function (value) {
  28489. if (this._boundingBias && this._boundingBias.equals(value)) {
  28490. return;
  28491. }
  28492. this._boundingBias = value.clone();
  28493. this.updateBoundingInfo(true, null);
  28494. },
  28495. enumerable: true,
  28496. configurable: true
  28497. });
  28498. Object.defineProperty(Geometry.prototype, "extend", {
  28499. get: function () {
  28500. return this._extend;
  28501. },
  28502. enumerable: true,
  28503. configurable: true
  28504. });
  28505. Geometry.prototype.getScene = function () {
  28506. return this._scene;
  28507. };
  28508. Geometry.prototype.getEngine = function () {
  28509. return this._engine;
  28510. };
  28511. Geometry.prototype.isReady = function () {
  28512. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28513. };
  28514. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28515. get: function () {
  28516. for (var index = 0; index < this._meshes.length; index++) {
  28517. if (!this._meshes[index].doNotSerialize) {
  28518. return false;
  28519. }
  28520. }
  28521. return true;
  28522. },
  28523. enumerable: true,
  28524. configurable: true
  28525. });
  28526. Geometry.prototype._rebuild = function () {
  28527. if (this._vertexArrayObjects) {
  28528. this._vertexArrayObjects = {};
  28529. }
  28530. // Index buffer
  28531. if (this._meshes.length !== 0 && this._indices) {
  28532. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28533. }
  28534. // Vertex buffers
  28535. for (var key in this._vertexBuffers) {
  28536. var vertexBuffer = this._vertexBuffers[key];
  28537. vertexBuffer._rebuild();
  28538. }
  28539. };
  28540. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28541. vertexData.applyToGeometry(this, updatable);
  28542. this.notifyUpdate();
  28543. };
  28544. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28545. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28546. this.setVerticesBuffer(buffer);
  28547. };
  28548. Geometry.prototype.removeVerticesData = function (kind) {
  28549. if (this._vertexBuffers[kind]) {
  28550. this._vertexBuffers[kind].dispose();
  28551. delete this._vertexBuffers[kind];
  28552. }
  28553. };
  28554. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28555. var kind = buffer.getKind();
  28556. if (this._vertexBuffers[kind]) {
  28557. this._vertexBuffers[kind].dispose();
  28558. }
  28559. this._vertexBuffers[kind] = buffer;
  28560. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28561. var data = buffer.getData();
  28562. var stride = buffer.getStrideSize();
  28563. this._totalVertices = data.length / stride;
  28564. this.updateExtend(data, stride);
  28565. this._resetPointsArrayCache();
  28566. var meshes = this._meshes;
  28567. var numOfMeshes = meshes.length;
  28568. for (var index = 0; index < numOfMeshes; index++) {
  28569. var mesh = meshes[index];
  28570. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28571. mesh._createGlobalSubMesh(false);
  28572. mesh.computeWorldMatrix(true);
  28573. }
  28574. }
  28575. this.notifyUpdate(kind);
  28576. if (this._vertexArrayObjects) {
  28577. this._disposeVertexArrayObjects();
  28578. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28579. }
  28580. };
  28581. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28582. var vertexBuffer = this.getVertexBuffer(kind);
  28583. if (!vertexBuffer) {
  28584. return;
  28585. }
  28586. vertexBuffer.updateDirectly(data, offset);
  28587. this.notifyUpdate(kind);
  28588. };
  28589. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28590. var vertexBuffer = this.getVertexBuffer(kind);
  28591. if (!vertexBuffer) {
  28592. return;
  28593. }
  28594. vertexBuffer.update(data);
  28595. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28596. var stride = vertexBuffer.getStrideSize();
  28597. this._totalVertices = data.length / stride;
  28598. this.updateBoundingInfo(updateExtends, data);
  28599. }
  28600. this.notifyUpdate(kind);
  28601. };
  28602. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28603. if (updateExtends) {
  28604. this.updateExtend(data);
  28605. }
  28606. var meshes = this._meshes;
  28607. var numOfMeshes = meshes.length;
  28608. this._resetPointsArrayCache();
  28609. for (var index = 0; index < numOfMeshes; index++) {
  28610. var mesh = meshes[index];
  28611. if (updateExtends) {
  28612. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28613. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28614. var subMesh = mesh.subMeshes[subIndex];
  28615. subMesh.refreshBoundingInfo();
  28616. }
  28617. }
  28618. }
  28619. };
  28620. Geometry.prototype._bind = function (effect, indexToBind) {
  28621. if (indexToBind === void 0) { indexToBind = undefined; }
  28622. if (indexToBind === undefined) {
  28623. indexToBind = this._indexBuffer;
  28624. }
  28625. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  28626. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  28627. return;
  28628. }
  28629. // Using VAO
  28630. if (!this._vertexArrayObjects[effect.key]) {
  28631. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  28632. }
  28633. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  28634. };
  28635. Geometry.prototype.getTotalVertices = function () {
  28636. if (!this.isReady()) {
  28637. return 0;
  28638. }
  28639. return this._totalVertices;
  28640. };
  28641. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28642. var vertexBuffer = this.getVertexBuffer(kind);
  28643. if (!vertexBuffer) {
  28644. return null;
  28645. }
  28646. var orig = vertexBuffer.getData();
  28647. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  28648. return orig;
  28649. }
  28650. else {
  28651. var len = orig.length;
  28652. var copy = [];
  28653. for (var i = 0; i < len; i++) {
  28654. copy.push(orig[i]);
  28655. }
  28656. return copy;
  28657. }
  28658. };
  28659. Geometry.prototype.getVertexBuffer = function (kind) {
  28660. if (!this.isReady()) {
  28661. return null;
  28662. }
  28663. return this._vertexBuffers[kind];
  28664. };
  28665. Geometry.prototype.getVertexBuffers = function () {
  28666. if (!this.isReady()) {
  28667. return null;
  28668. }
  28669. return this._vertexBuffers;
  28670. };
  28671. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28672. if (!this._vertexBuffers) {
  28673. if (this._delayInfo) {
  28674. return this._delayInfo.indexOf(kind) !== -1;
  28675. }
  28676. return false;
  28677. }
  28678. return this._vertexBuffers[kind] !== undefined;
  28679. };
  28680. Geometry.prototype.getVerticesDataKinds = function () {
  28681. var result = [];
  28682. var kind;
  28683. if (!this._vertexBuffers && this._delayInfo) {
  28684. for (kind in this._delayInfo) {
  28685. result.push(kind);
  28686. }
  28687. }
  28688. else {
  28689. for (kind in this._vertexBuffers) {
  28690. result.push(kind);
  28691. }
  28692. }
  28693. return result;
  28694. };
  28695. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28696. if (this._indexBuffer) {
  28697. this._engine._releaseBuffer(this._indexBuffer);
  28698. }
  28699. this._disposeVertexArrayObjects();
  28700. this._indices = indices;
  28701. if (this._meshes.length !== 0 && this._indices) {
  28702. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28703. }
  28704. if (totalVertices !== undefined) {
  28705. this._totalVertices = totalVertices;
  28706. }
  28707. var meshes = this._meshes;
  28708. var numOfMeshes = meshes.length;
  28709. for (var index = 0; index < numOfMeshes; index++) {
  28710. meshes[index]._createGlobalSubMesh(true);
  28711. }
  28712. this.notifyUpdate();
  28713. };
  28714. Geometry.prototype.getTotalIndices = function () {
  28715. if (!this.isReady()) {
  28716. return 0;
  28717. }
  28718. return this._indices.length;
  28719. };
  28720. Geometry.prototype.getIndices = function (copyWhenShared) {
  28721. if (!this.isReady()) {
  28722. return null;
  28723. }
  28724. var orig = this._indices;
  28725. if (!copyWhenShared || this._meshes.length === 1) {
  28726. return orig;
  28727. }
  28728. else {
  28729. var len = orig.length;
  28730. var copy = [];
  28731. for (var i = 0; i < len; i++) {
  28732. copy.push(orig[i]);
  28733. }
  28734. return copy;
  28735. }
  28736. };
  28737. Geometry.prototype.getIndexBuffer = function () {
  28738. if (!this.isReady()) {
  28739. return null;
  28740. }
  28741. return this._indexBuffer;
  28742. };
  28743. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  28744. if (!effect || !this._vertexArrayObjects) {
  28745. return;
  28746. }
  28747. if (this._vertexArrayObjects[effect.key]) {
  28748. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  28749. delete this._vertexArrayObjects[effect.key];
  28750. }
  28751. };
  28752. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28753. var meshes = this._meshes;
  28754. var index = meshes.indexOf(mesh);
  28755. if (index === -1) {
  28756. return;
  28757. }
  28758. meshes.splice(index, 1);
  28759. mesh._geometry = null;
  28760. if (meshes.length === 0 && shouldDispose) {
  28761. this.dispose();
  28762. }
  28763. };
  28764. Geometry.prototype.applyToMesh = function (mesh) {
  28765. if (mesh._geometry === this) {
  28766. return;
  28767. }
  28768. var previousGeometry = mesh._geometry;
  28769. if (previousGeometry) {
  28770. previousGeometry.releaseForMesh(mesh);
  28771. }
  28772. var meshes = this._meshes;
  28773. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28774. mesh._geometry = this;
  28775. this._scene.pushGeometry(this);
  28776. meshes.push(mesh);
  28777. if (this.isReady()) {
  28778. this._applyToMesh(mesh);
  28779. }
  28780. else {
  28781. mesh._boundingInfo = this._boundingInfo;
  28782. }
  28783. };
  28784. Geometry.prototype.updateExtend = function (data, stride) {
  28785. if (data === void 0) { data = null; }
  28786. if (!data) {
  28787. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  28788. }
  28789. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  28790. };
  28791. Geometry.prototype._applyToMesh = function (mesh) {
  28792. var numOfMeshes = this._meshes.length;
  28793. // vertexBuffers
  28794. for (var kind in this._vertexBuffers) {
  28795. if (numOfMeshes === 1) {
  28796. this._vertexBuffers[kind].create();
  28797. }
  28798. var buffer = this._vertexBuffers[kind].getBuffer();
  28799. if (buffer)
  28800. buffer.references = numOfMeshes;
  28801. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28802. if (!this._extend) {
  28803. this.updateExtend(this._vertexBuffers[kind].getData());
  28804. }
  28805. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28806. mesh._createGlobalSubMesh(false);
  28807. //bounding info was just created again, world matrix should be applied again.
  28808. mesh._updateBoundingInfo();
  28809. }
  28810. }
  28811. // indexBuffer
  28812. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  28813. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28814. }
  28815. if (this._indexBuffer) {
  28816. this._indexBuffer.references = numOfMeshes;
  28817. }
  28818. };
  28819. Geometry.prototype.notifyUpdate = function (kind) {
  28820. if (this.onGeometryUpdated) {
  28821. this.onGeometryUpdated(this, kind);
  28822. }
  28823. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  28824. var mesh = _a[_i];
  28825. mesh._markSubMeshesAsAttributesDirty();
  28826. }
  28827. };
  28828. Geometry.prototype.load = function (scene, onLoaded) {
  28829. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28830. return;
  28831. }
  28832. if (this.isReady()) {
  28833. if (onLoaded) {
  28834. onLoaded();
  28835. }
  28836. return;
  28837. }
  28838. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28839. this._queueLoad(scene, onLoaded);
  28840. };
  28841. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  28842. var _this = this;
  28843. scene._addPendingData(this);
  28844. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28845. _this._delayLoadingFunction(JSON.parse(data), _this);
  28846. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28847. _this._delayInfo = [];
  28848. scene._removePendingData(_this);
  28849. var meshes = _this._meshes;
  28850. var numOfMeshes = meshes.length;
  28851. for (var index = 0; index < numOfMeshes; index++) {
  28852. _this._applyToMesh(meshes[index]);
  28853. }
  28854. if (onLoaded) {
  28855. onLoaded();
  28856. }
  28857. }, function () { }, scene.database);
  28858. };
  28859. /**
  28860. * Invert the geometry to move from a right handed system to a left handed one.
  28861. */
  28862. Geometry.prototype.toLeftHanded = function () {
  28863. // Flip faces
  28864. var tIndices = this.getIndices(false);
  28865. if (tIndices != null && tIndices.length > 0) {
  28866. for (var i = 0; i < tIndices.length; i += 3) {
  28867. var tTemp = tIndices[i + 0];
  28868. tIndices[i + 0] = tIndices[i + 2];
  28869. tIndices[i + 2] = tTemp;
  28870. }
  28871. this.setIndices(tIndices);
  28872. }
  28873. // Negate position.z
  28874. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  28875. if (tPositions != null && tPositions.length > 0) {
  28876. for (var i = 0; i < tPositions.length; i += 3) {
  28877. tPositions[i + 2] = -tPositions[i + 2];
  28878. }
  28879. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  28880. }
  28881. // Negate normal.z
  28882. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  28883. if (tNormals != null && tNormals.length > 0) {
  28884. for (var i = 0; i < tNormals.length; i += 3) {
  28885. tNormals[i + 2] = -tNormals[i + 2];
  28886. }
  28887. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  28888. }
  28889. };
  28890. // Cache
  28891. Geometry.prototype._resetPointsArrayCache = function () {
  28892. this._positions = null;
  28893. };
  28894. Geometry.prototype._generatePointsArray = function () {
  28895. if (this._positions)
  28896. return true;
  28897. this._positions = [];
  28898. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28899. if (!data) {
  28900. return false;
  28901. }
  28902. for (var index = 0; index < data.length; index += 3) {
  28903. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  28904. }
  28905. return true;
  28906. };
  28907. Geometry.prototype.isDisposed = function () {
  28908. return this._isDisposed;
  28909. };
  28910. Geometry.prototype._disposeVertexArrayObjects = function () {
  28911. if (this._vertexArrayObjects) {
  28912. for (var kind in this._vertexArrayObjects) {
  28913. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  28914. }
  28915. this._vertexArrayObjects = {};
  28916. }
  28917. };
  28918. Geometry.prototype.dispose = function () {
  28919. var meshes = this._meshes;
  28920. var numOfMeshes = meshes.length;
  28921. var index;
  28922. for (index = 0; index < numOfMeshes; index++) {
  28923. this.releaseForMesh(meshes[index]);
  28924. }
  28925. this._meshes = [];
  28926. this._disposeVertexArrayObjects();
  28927. for (var kind in this._vertexBuffers) {
  28928. this._vertexBuffers[kind].dispose();
  28929. }
  28930. this._vertexBuffers = {};
  28931. this._totalVertices = 0;
  28932. if (this._indexBuffer) {
  28933. this._engine._releaseBuffer(this._indexBuffer);
  28934. }
  28935. this._indexBuffer = null;
  28936. this._indices = [];
  28937. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28938. this.delayLoadingFile = null;
  28939. this._delayLoadingFunction = null;
  28940. this._delayInfo = [];
  28941. this._boundingInfo = null;
  28942. this._scene.removeGeometry(this);
  28943. this._isDisposed = true;
  28944. };
  28945. Geometry.prototype.copy = function (id) {
  28946. var vertexData = new BABYLON.VertexData();
  28947. vertexData.indices = [];
  28948. var indices = this.getIndices();
  28949. for (var index = 0; index < indices.length; index++) {
  28950. vertexData.indices.push(indices[index]);
  28951. }
  28952. var updatable = false;
  28953. var stopChecking = false;
  28954. var kind;
  28955. for (kind in this._vertexBuffers) {
  28956. // using slice() to make a copy of the array and not just reference it
  28957. var data = this.getVerticesData(kind);
  28958. if (data instanceof Float32Array) {
  28959. vertexData.set(new Float32Array(data), kind);
  28960. }
  28961. else {
  28962. vertexData.set(data.slice(0), kind);
  28963. }
  28964. if (!stopChecking) {
  28965. updatable = this.getVertexBuffer(kind).isUpdatable();
  28966. stopChecking = !updatable;
  28967. }
  28968. }
  28969. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28970. geometry.delayLoadState = this.delayLoadState;
  28971. geometry.delayLoadingFile = this.delayLoadingFile;
  28972. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28973. for (kind in this._delayInfo) {
  28974. geometry._delayInfo = geometry._delayInfo || [];
  28975. geometry._delayInfo.push(kind);
  28976. }
  28977. // Bounding info
  28978. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28979. return geometry;
  28980. };
  28981. Geometry.prototype.serialize = function () {
  28982. var serializationObject = {};
  28983. serializationObject.id = this.id;
  28984. serializationObject.updatable = this._updatable;
  28985. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28986. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28987. }
  28988. return serializationObject;
  28989. };
  28990. Geometry.prototype.toNumberArray = function (origin) {
  28991. if (Array.isArray(origin)) {
  28992. return origin;
  28993. }
  28994. else {
  28995. return Array.prototype.slice.call(origin);
  28996. }
  28997. };
  28998. Geometry.prototype.serializeVerticeData = function () {
  28999. var serializationObject = this.serialize();
  29000. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29001. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  29002. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  29003. serializationObject.positions._updatable = true;
  29004. }
  29005. }
  29006. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29007. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29008. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29009. serializationObject.normals._updatable = true;
  29010. }
  29011. }
  29012. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29013. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29014. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29015. serializationObject.uvs._updatable = true;
  29016. }
  29017. }
  29018. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29019. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29020. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29021. serializationObject.uv2s._updatable = true;
  29022. }
  29023. }
  29024. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29025. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29026. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29027. serializationObject.uv3s._updatable = true;
  29028. }
  29029. }
  29030. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29031. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29032. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29033. serializationObject.uv4s._updatable = true;
  29034. }
  29035. }
  29036. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29037. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29038. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29039. serializationObject.uv5s._updatable = true;
  29040. }
  29041. }
  29042. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29043. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29044. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29045. serializationObject.uv6s._updatable = true;
  29046. }
  29047. }
  29048. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29049. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29050. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29051. serializationObject.colors._updatable = true;
  29052. }
  29053. }
  29054. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29055. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29056. serializationObject.matricesIndices._isExpanded = true;
  29057. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29058. serializationObject.matricesIndices._updatable = true;
  29059. }
  29060. }
  29061. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29062. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29063. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29064. serializationObject.matricesWeights._updatable = true;
  29065. }
  29066. }
  29067. serializationObject.indices = this.toNumberArray(this.getIndices());
  29068. return serializationObject;
  29069. };
  29070. // Statics
  29071. Geometry.ExtractFromMesh = function (mesh, id) {
  29072. var geometry = mesh._geometry;
  29073. if (!geometry) {
  29074. return null;
  29075. }
  29076. return geometry.copy(id);
  29077. };
  29078. /**
  29079. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29080. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29081. * Be aware Math.random() could cause collisions, but:
  29082. * "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"
  29083. */
  29084. Geometry.RandomId = function () {
  29085. return BABYLON.Tools.RandomId();
  29086. };
  29087. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29088. var scene = mesh.getScene();
  29089. // Geometry
  29090. var geometryId = parsedGeometry.geometryId;
  29091. if (geometryId) {
  29092. var geometry = scene.getGeometryByID(geometryId);
  29093. if (geometry) {
  29094. geometry.applyToMesh(mesh);
  29095. }
  29096. }
  29097. else if (parsedGeometry instanceof ArrayBuffer) {
  29098. var binaryInfo = mesh._binaryInfo;
  29099. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29100. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29101. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29102. }
  29103. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29104. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29105. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29106. }
  29107. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29108. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29109. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29110. }
  29111. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29112. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29113. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29114. }
  29115. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29116. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29117. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29118. }
  29119. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29120. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29121. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29122. }
  29123. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29124. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29125. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29126. }
  29127. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29128. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29129. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29130. }
  29131. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29132. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29133. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29134. }
  29135. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29136. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29137. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29138. }
  29139. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29140. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29141. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29142. }
  29143. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29144. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29145. mesh.setIndices(indicesData);
  29146. }
  29147. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29148. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29149. mesh.subMeshes = [];
  29150. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29151. var materialIndex = subMeshesData[(i * 5) + 0];
  29152. var verticesStart = subMeshesData[(i * 5) + 1];
  29153. var verticesCount = subMeshesData[(i * 5) + 2];
  29154. var indexStart = subMeshesData[(i * 5) + 3];
  29155. var indexCount = subMeshesData[(i * 5) + 4];
  29156. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29157. }
  29158. }
  29159. }
  29160. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29161. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29162. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29163. if (parsedGeometry.uvs) {
  29164. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29165. }
  29166. if (parsedGeometry.uvs2) {
  29167. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29168. }
  29169. if (parsedGeometry.uvs3) {
  29170. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29171. }
  29172. if (parsedGeometry.uvs4) {
  29173. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29174. }
  29175. if (parsedGeometry.uvs5) {
  29176. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29177. }
  29178. if (parsedGeometry.uvs6) {
  29179. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29180. }
  29181. if (parsedGeometry.colors) {
  29182. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29183. }
  29184. if (parsedGeometry.matricesIndices) {
  29185. if (!parsedGeometry.matricesIndices._isExpanded) {
  29186. var floatIndices = [];
  29187. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29188. var matricesIndex = parsedGeometry.matricesIndices[i];
  29189. floatIndices.push(matricesIndex & 0x000000FF);
  29190. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29191. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29192. floatIndices.push(matricesIndex >> 24);
  29193. }
  29194. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29195. }
  29196. else {
  29197. delete parsedGeometry.matricesIndices._isExpanded;
  29198. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29199. }
  29200. }
  29201. if (parsedGeometry.matricesIndicesExtra) {
  29202. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29203. var floatIndices = [];
  29204. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29205. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29206. floatIndices.push(matricesIndex & 0x000000FF);
  29207. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29208. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29209. floatIndices.push(matricesIndex >> 24);
  29210. }
  29211. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29212. }
  29213. else {
  29214. delete parsedGeometry.matricesIndices._isExpanded;
  29215. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29216. }
  29217. }
  29218. if (parsedGeometry.matricesWeights) {
  29219. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29220. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29221. }
  29222. if (parsedGeometry.matricesWeightsExtra) {
  29223. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29224. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29225. }
  29226. mesh.setIndices(parsedGeometry.indices);
  29227. }
  29228. // SubMeshes
  29229. if (parsedGeometry.subMeshes) {
  29230. mesh.subMeshes = [];
  29231. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29232. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29233. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29234. }
  29235. }
  29236. // Flat shading
  29237. if (mesh._shouldGenerateFlatShading) {
  29238. mesh.convertToFlatShadedMesh();
  29239. delete mesh._shouldGenerateFlatShading;
  29240. }
  29241. // Update
  29242. mesh.computeWorldMatrix(true);
  29243. // Octree
  29244. if (scene['_selectionOctree']) {
  29245. scene['_selectionOctree'].addMesh(mesh);
  29246. }
  29247. };
  29248. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29249. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29250. return;
  29251. }
  29252. var size = matricesWeights.length;
  29253. for (var i = 0; i < size; i += influencers) {
  29254. var weight = 0;
  29255. var biggerIndex = i;
  29256. var biggerWeight = 0;
  29257. for (var j = 0; j < influencers - 1; j++) {
  29258. weight += matricesWeights[i + j];
  29259. if (matricesWeights[i + j] > biggerWeight) {
  29260. biggerWeight = matricesWeights[i + j];
  29261. biggerIndex = i + j;
  29262. }
  29263. }
  29264. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29265. }
  29266. };
  29267. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29268. if (scene.getGeometryByID(parsedVertexData.id)) {
  29269. return null; // null since geometry could be something else than a box...
  29270. }
  29271. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29272. if (BABYLON.Tags) {
  29273. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29274. }
  29275. if (parsedVertexData.delayLoadingFile) {
  29276. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29277. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29278. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29279. geometry._delayInfo = [];
  29280. if (parsedVertexData.hasUVs) {
  29281. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29282. }
  29283. if (parsedVertexData.hasUVs2) {
  29284. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29285. }
  29286. if (parsedVertexData.hasUVs3) {
  29287. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29288. }
  29289. if (parsedVertexData.hasUVs4) {
  29290. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29291. }
  29292. if (parsedVertexData.hasUVs5) {
  29293. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29294. }
  29295. if (parsedVertexData.hasUVs6) {
  29296. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29297. }
  29298. if (parsedVertexData.hasColors) {
  29299. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29300. }
  29301. if (parsedVertexData.hasMatricesIndices) {
  29302. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29303. }
  29304. if (parsedVertexData.hasMatricesWeights) {
  29305. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29306. }
  29307. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29308. }
  29309. else {
  29310. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29311. }
  29312. scene.pushGeometry(geometry, true);
  29313. return geometry;
  29314. };
  29315. return Geometry;
  29316. }());
  29317. BABYLON.Geometry = Geometry;
  29318. /////// Primitives //////////////////////////////////////////////
  29319. (function (Geometry) {
  29320. var Primitives;
  29321. (function (Primitives) {
  29322. /// Abstract class
  29323. var _Primitive = (function (_super) {
  29324. __extends(_Primitive, _super);
  29325. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29326. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29327. _this._canBeRegenerated = _canBeRegenerated;
  29328. _this._beingRegenerated = true;
  29329. _this.regenerate();
  29330. _this._beingRegenerated = false;
  29331. return _this;
  29332. }
  29333. _Primitive.prototype.canBeRegenerated = function () {
  29334. return this._canBeRegenerated;
  29335. };
  29336. _Primitive.prototype.regenerate = function () {
  29337. if (!this._canBeRegenerated) {
  29338. return;
  29339. }
  29340. this._beingRegenerated = true;
  29341. this.setAllVerticesData(this._regenerateVertexData(), false);
  29342. this._beingRegenerated = false;
  29343. };
  29344. _Primitive.prototype.asNewGeometry = function (id) {
  29345. return _super.prototype.copy.call(this, id);
  29346. };
  29347. // overrides
  29348. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29349. if (!this._beingRegenerated) {
  29350. return;
  29351. }
  29352. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29353. };
  29354. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29355. if (!this._beingRegenerated) {
  29356. return;
  29357. }
  29358. _super.prototype.setVerticesData.call(this, kind, data, false);
  29359. };
  29360. // to override
  29361. // protected
  29362. _Primitive.prototype._regenerateVertexData = function () {
  29363. throw new Error("Abstract method");
  29364. };
  29365. _Primitive.prototype.copy = function (id) {
  29366. throw new Error("Must be overriden in sub-classes.");
  29367. };
  29368. _Primitive.prototype.serialize = function () {
  29369. var serializationObject = _super.prototype.serialize.call(this);
  29370. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29371. return serializationObject;
  29372. };
  29373. return _Primitive;
  29374. }(Geometry));
  29375. Primitives._Primitive = _Primitive;
  29376. var Ribbon = (function (_super) {
  29377. __extends(Ribbon, _super);
  29378. // Members
  29379. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29380. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29381. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29382. _this.pathArray = pathArray;
  29383. _this.closeArray = closeArray;
  29384. _this.closePath = closePath;
  29385. _this.offset = offset;
  29386. _this.side = side;
  29387. return _this;
  29388. }
  29389. Ribbon.prototype._regenerateVertexData = function () {
  29390. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29391. };
  29392. Ribbon.prototype.copy = function (id) {
  29393. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29394. };
  29395. return Ribbon;
  29396. }(_Primitive));
  29397. Primitives.Ribbon = Ribbon;
  29398. var Box = (function (_super) {
  29399. __extends(Box, _super);
  29400. // Members
  29401. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29402. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29403. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29404. _this.size = size;
  29405. _this.side = side;
  29406. return _this;
  29407. }
  29408. Box.prototype._regenerateVertexData = function () {
  29409. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29410. };
  29411. Box.prototype.copy = function (id) {
  29412. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29413. };
  29414. Box.prototype.serialize = function () {
  29415. var serializationObject = _super.prototype.serialize.call(this);
  29416. serializationObject.size = this.size;
  29417. return serializationObject;
  29418. };
  29419. Box.Parse = function (parsedBox, scene) {
  29420. if (scene.getGeometryByID(parsedBox.id)) {
  29421. return null; // null since geometry could be something else than a box...
  29422. }
  29423. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29424. if (BABYLON.Tags) {
  29425. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29426. }
  29427. scene.pushGeometry(box, true);
  29428. return box;
  29429. };
  29430. return Box;
  29431. }(_Primitive));
  29432. Primitives.Box = Box;
  29433. var Sphere = (function (_super) {
  29434. __extends(Sphere, _super);
  29435. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29436. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29437. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29438. _this.segments = segments;
  29439. _this.diameter = diameter;
  29440. _this.side = side;
  29441. return _this;
  29442. }
  29443. Sphere.prototype._regenerateVertexData = function () {
  29444. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29445. };
  29446. Sphere.prototype.copy = function (id) {
  29447. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29448. };
  29449. Sphere.prototype.serialize = function () {
  29450. var serializationObject = _super.prototype.serialize.call(this);
  29451. serializationObject.segments = this.segments;
  29452. serializationObject.diameter = this.diameter;
  29453. return serializationObject;
  29454. };
  29455. Sphere.Parse = function (parsedSphere, scene) {
  29456. if (scene.getGeometryByID(parsedSphere.id)) {
  29457. return null; // null since geometry could be something else than a sphere...
  29458. }
  29459. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29460. if (BABYLON.Tags) {
  29461. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29462. }
  29463. scene.pushGeometry(sphere, true);
  29464. return sphere;
  29465. };
  29466. return Sphere;
  29467. }(_Primitive));
  29468. Primitives.Sphere = Sphere;
  29469. var Disc = (function (_super) {
  29470. __extends(Disc, _super);
  29471. // Members
  29472. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29473. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29474. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29475. _this.radius = radius;
  29476. _this.tessellation = tessellation;
  29477. _this.side = side;
  29478. return _this;
  29479. }
  29480. Disc.prototype._regenerateVertexData = function () {
  29481. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29482. };
  29483. Disc.prototype.copy = function (id) {
  29484. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29485. };
  29486. return Disc;
  29487. }(_Primitive));
  29488. Primitives.Disc = Disc;
  29489. var Cylinder = (function (_super) {
  29490. __extends(Cylinder, _super);
  29491. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29492. if (subdivisions === void 0) { subdivisions = 1; }
  29493. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29494. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29495. _this.height = height;
  29496. _this.diameterTop = diameterTop;
  29497. _this.diameterBottom = diameterBottom;
  29498. _this.tessellation = tessellation;
  29499. _this.subdivisions = subdivisions;
  29500. _this.side = side;
  29501. return _this;
  29502. }
  29503. Cylinder.prototype._regenerateVertexData = function () {
  29504. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29505. };
  29506. Cylinder.prototype.copy = function (id) {
  29507. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29508. };
  29509. Cylinder.prototype.serialize = function () {
  29510. var serializationObject = _super.prototype.serialize.call(this);
  29511. serializationObject.height = this.height;
  29512. serializationObject.diameterTop = this.diameterTop;
  29513. serializationObject.diameterBottom = this.diameterBottom;
  29514. serializationObject.tessellation = this.tessellation;
  29515. return serializationObject;
  29516. };
  29517. Cylinder.Parse = function (parsedCylinder, scene) {
  29518. if (scene.getGeometryByID(parsedCylinder.id)) {
  29519. return null; // null since geometry could be something else than a cylinder...
  29520. }
  29521. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29522. if (BABYLON.Tags) {
  29523. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29524. }
  29525. scene.pushGeometry(cylinder, true);
  29526. return cylinder;
  29527. };
  29528. return Cylinder;
  29529. }(_Primitive));
  29530. Primitives.Cylinder = Cylinder;
  29531. var Torus = (function (_super) {
  29532. __extends(Torus, _super);
  29533. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29534. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29535. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29536. _this.diameter = diameter;
  29537. _this.thickness = thickness;
  29538. _this.tessellation = tessellation;
  29539. _this.side = side;
  29540. return _this;
  29541. }
  29542. Torus.prototype._regenerateVertexData = function () {
  29543. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29544. };
  29545. Torus.prototype.copy = function (id) {
  29546. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29547. };
  29548. Torus.prototype.serialize = function () {
  29549. var serializationObject = _super.prototype.serialize.call(this);
  29550. serializationObject.diameter = this.diameter;
  29551. serializationObject.thickness = this.thickness;
  29552. serializationObject.tessellation = this.tessellation;
  29553. return serializationObject;
  29554. };
  29555. Torus.Parse = function (parsedTorus, scene) {
  29556. if (scene.getGeometryByID(parsedTorus.id)) {
  29557. return null; // null since geometry could be something else than a torus...
  29558. }
  29559. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29560. if (BABYLON.Tags) {
  29561. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29562. }
  29563. scene.pushGeometry(torus, true);
  29564. return torus;
  29565. };
  29566. return Torus;
  29567. }(_Primitive));
  29568. Primitives.Torus = Torus;
  29569. var Ground = (function (_super) {
  29570. __extends(Ground, _super);
  29571. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29572. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29573. _this.width = width;
  29574. _this.height = height;
  29575. _this.subdivisions = subdivisions;
  29576. return _this;
  29577. }
  29578. Ground.prototype._regenerateVertexData = function () {
  29579. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29580. };
  29581. Ground.prototype.copy = function (id) {
  29582. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29583. };
  29584. Ground.prototype.serialize = function () {
  29585. var serializationObject = _super.prototype.serialize.call(this);
  29586. serializationObject.width = this.width;
  29587. serializationObject.height = this.height;
  29588. serializationObject.subdivisions = this.subdivisions;
  29589. return serializationObject;
  29590. };
  29591. Ground.Parse = function (parsedGround, scene) {
  29592. if (scene.getGeometryByID(parsedGround.id)) {
  29593. return null; // null since geometry could be something else than a ground...
  29594. }
  29595. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29596. if (BABYLON.Tags) {
  29597. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29598. }
  29599. scene.pushGeometry(ground, true);
  29600. return ground;
  29601. };
  29602. return Ground;
  29603. }(_Primitive));
  29604. Primitives.Ground = Ground;
  29605. var TiledGround = (function (_super) {
  29606. __extends(TiledGround, _super);
  29607. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29608. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29609. _this.xmin = xmin;
  29610. _this.zmin = zmin;
  29611. _this.xmax = xmax;
  29612. _this.zmax = zmax;
  29613. _this.subdivisions = subdivisions;
  29614. _this.precision = precision;
  29615. return _this;
  29616. }
  29617. TiledGround.prototype._regenerateVertexData = function () {
  29618. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29619. };
  29620. TiledGround.prototype.copy = function (id) {
  29621. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29622. };
  29623. return TiledGround;
  29624. }(_Primitive));
  29625. Primitives.TiledGround = TiledGround;
  29626. var Plane = (function (_super) {
  29627. __extends(Plane, _super);
  29628. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29629. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29630. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29631. _this.size = size;
  29632. _this.side = side;
  29633. return _this;
  29634. }
  29635. Plane.prototype._regenerateVertexData = function () {
  29636. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29637. };
  29638. Plane.prototype.copy = function (id) {
  29639. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29640. };
  29641. Plane.prototype.serialize = function () {
  29642. var serializationObject = _super.prototype.serialize.call(this);
  29643. serializationObject.size = this.size;
  29644. return serializationObject;
  29645. };
  29646. Plane.Parse = function (parsedPlane, scene) {
  29647. if (scene.getGeometryByID(parsedPlane.id)) {
  29648. return null; // null since geometry could be something else than a ground...
  29649. }
  29650. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  29651. if (BABYLON.Tags) {
  29652. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  29653. }
  29654. scene.pushGeometry(plane, true);
  29655. return plane;
  29656. };
  29657. return Plane;
  29658. }(_Primitive));
  29659. Primitives.Plane = Plane;
  29660. var TorusKnot = (function (_super) {
  29661. __extends(TorusKnot, _super);
  29662. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29663. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29664. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29665. _this.radius = radius;
  29666. _this.tube = tube;
  29667. _this.radialSegments = radialSegments;
  29668. _this.tubularSegments = tubularSegments;
  29669. _this.p = p;
  29670. _this.q = q;
  29671. _this.side = side;
  29672. return _this;
  29673. }
  29674. TorusKnot.prototype._regenerateVertexData = function () {
  29675. 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 });
  29676. };
  29677. TorusKnot.prototype.copy = function (id) {
  29678. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29679. };
  29680. TorusKnot.prototype.serialize = function () {
  29681. var serializationObject = _super.prototype.serialize.call(this);
  29682. serializationObject.radius = this.radius;
  29683. serializationObject.tube = this.tube;
  29684. serializationObject.radialSegments = this.radialSegments;
  29685. serializationObject.tubularSegments = this.tubularSegments;
  29686. serializationObject.p = this.p;
  29687. serializationObject.q = this.q;
  29688. return serializationObject;
  29689. };
  29690. ;
  29691. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  29692. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  29693. return null; // null since geometry could be something else than a ground...
  29694. }
  29695. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  29696. if (BABYLON.Tags) {
  29697. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  29698. }
  29699. scene.pushGeometry(torusKnot, true);
  29700. return torusKnot;
  29701. };
  29702. return TorusKnot;
  29703. }(_Primitive));
  29704. Primitives.TorusKnot = TorusKnot;
  29705. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29706. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29707. })(BABYLON || (BABYLON = {}));
  29708. //# sourceMappingURL=babylon.geometry.js.map
  29709. var BABYLON;
  29710. (function (BABYLON) {
  29711. var PostProcessManager = (function () {
  29712. function PostProcessManager(scene) {
  29713. this._vertexBuffers = {};
  29714. this._scene = scene;
  29715. }
  29716. PostProcessManager.prototype._prepareBuffers = function () {
  29717. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29718. return;
  29719. }
  29720. // VBO
  29721. var vertices = [];
  29722. vertices.push(1, 1);
  29723. vertices.push(-1, 1);
  29724. vertices.push(-1, -1);
  29725. vertices.push(1, -1);
  29726. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29727. this._buildIndexBuffer();
  29728. };
  29729. PostProcessManager.prototype._buildIndexBuffer = function () {
  29730. // Indices
  29731. var indices = [];
  29732. indices.push(0);
  29733. indices.push(1);
  29734. indices.push(2);
  29735. indices.push(0);
  29736. indices.push(2);
  29737. indices.push(3);
  29738. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29739. };
  29740. PostProcessManager.prototype._rebuild = function () {
  29741. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29742. return;
  29743. }
  29744. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  29745. this._buildIndexBuffer();
  29746. };
  29747. // Methods
  29748. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  29749. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29750. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29751. return false;
  29752. }
  29753. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  29754. return true;
  29755. };
  29756. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  29757. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  29758. var engine = this._scene.getEngine();
  29759. for (var index = 0; index < postProcesses.length; index++) {
  29760. if (index < postProcesses.length - 1) {
  29761. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29762. }
  29763. else {
  29764. if (targetTexture) {
  29765. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  29766. }
  29767. else {
  29768. engine.restoreDefaultFramebuffer();
  29769. }
  29770. }
  29771. var pp = postProcesses[index];
  29772. var effect = pp.apply();
  29773. if (effect) {
  29774. pp.onBeforeRenderObservable.notifyObservers(effect);
  29775. // VBOs
  29776. this._prepareBuffers();
  29777. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29778. // Draw order
  29779. engine.draw(true, 0, 6);
  29780. pp.onAfterRenderObservable.notifyObservers(effect);
  29781. }
  29782. }
  29783. // Restore depth buffer
  29784. engine.setDepthBuffer(true);
  29785. engine.setDepthWrite(true);
  29786. };
  29787. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29788. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29789. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29790. return;
  29791. }
  29792. var engine = this._scene.getEngine();
  29793. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29794. if (index < len - 1) {
  29795. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29796. }
  29797. else {
  29798. if (targetTexture) {
  29799. engine.bindFramebuffer(targetTexture, faceIndex);
  29800. }
  29801. else {
  29802. engine.restoreDefaultFramebuffer();
  29803. }
  29804. }
  29805. if (doNotPresent) {
  29806. break;
  29807. }
  29808. var pp = postProcesses[index];
  29809. var effect = pp.apply();
  29810. if (effect) {
  29811. pp.onBeforeRenderObservable.notifyObservers(effect);
  29812. // VBOs
  29813. this._prepareBuffers();
  29814. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29815. // Draw order
  29816. engine.draw(true, 0, 6);
  29817. pp.onAfterRenderObservable.notifyObservers(effect);
  29818. }
  29819. }
  29820. // Restore states
  29821. engine.setDepthBuffer(true);
  29822. engine.setDepthWrite(true);
  29823. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29824. };
  29825. PostProcessManager.prototype.dispose = function () {
  29826. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29827. if (buffer) {
  29828. buffer.dispose();
  29829. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29830. }
  29831. if (this._indexBuffer) {
  29832. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29833. this._indexBuffer = null;
  29834. }
  29835. };
  29836. return PostProcessManager;
  29837. }());
  29838. BABYLON.PostProcessManager = PostProcessManager;
  29839. })(BABYLON || (BABYLON = {}));
  29840. //# sourceMappingURL=babylon.postProcessManager.js.map
  29841. var BABYLON;
  29842. (function (BABYLON) {
  29843. /**
  29844. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  29845. */
  29846. var PerformanceMonitor = (function () {
  29847. /**
  29848. * constructor
  29849. * @param frameSampleSize The number of samples required to saturate the sliding window
  29850. */
  29851. function PerformanceMonitor(frameSampleSize) {
  29852. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  29853. this._enabled = true;
  29854. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  29855. }
  29856. /**
  29857. * Samples current frame
  29858. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  29859. */
  29860. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  29861. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  29862. if (!this._enabled)
  29863. return;
  29864. if (this._lastFrameTimeMs != null) {
  29865. var dt = timeMs - this._lastFrameTimeMs;
  29866. this._rollingFrameTime.add(dt);
  29867. }
  29868. this._lastFrameTimeMs = timeMs;
  29869. };
  29870. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  29871. /**
  29872. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29873. * @return Average frame time in milliseconds
  29874. */
  29875. get: function () {
  29876. return this._rollingFrameTime.average;
  29877. },
  29878. enumerable: true,
  29879. configurable: true
  29880. });
  29881. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  29882. /**
  29883. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29884. * @return Frame time variance in milliseconds squared
  29885. */
  29886. get: function () {
  29887. return this._rollingFrameTime.variance;
  29888. },
  29889. enumerable: true,
  29890. configurable: true
  29891. });
  29892. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  29893. /**
  29894. * Returns the frame time of the most recent frame
  29895. * @return Frame time in milliseconds
  29896. */
  29897. get: function () {
  29898. return this._rollingFrameTime.history(0);
  29899. },
  29900. enumerable: true,
  29901. configurable: true
  29902. });
  29903. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  29904. /**
  29905. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  29906. * @return Framerate in frames per second
  29907. */
  29908. get: function () {
  29909. return 1000.0 / this._rollingFrameTime.average;
  29910. },
  29911. enumerable: true,
  29912. configurable: true
  29913. });
  29914. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  29915. /**
  29916. * Returns the average framerate in frames per second using the most recent frame time
  29917. * @return Framerate in frames per second
  29918. */
  29919. get: function () {
  29920. return 1000.0 / this._rollingFrameTime.history(0);
  29921. },
  29922. enumerable: true,
  29923. configurable: true
  29924. });
  29925. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  29926. /**
  29927. * Returns true if enough samples have been taken to completely fill the sliding window
  29928. * @return true if saturated
  29929. */
  29930. get: function () {
  29931. return this._rollingFrameTime.isSaturated();
  29932. },
  29933. enumerable: true,
  29934. configurable: true
  29935. });
  29936. /**
  29937. * Enables contributions to the sliding window sample set
  29938. */
  29939. PerformanceMonitor.prototype.enable = function () {
  29940. this._enabled = true;
  29941. };
  29942. /**
  29943. * Disables contributions to the sliding window sample set
  29944. * Samples will not be interpolated over the disabled period
  29945. */
  29946. PerformanceMonitor.prototype.disable = function () {
  29947. this._enabled = false;
  29948. //clear last sample to avoid interpolating over the disabled period when next enabled
  29949. this._lastFrameTimeMs = null;
  29950. this._lastChangeTimeMs = null;
  29951. };
  29952. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  29953. /**
  29954. * Returns true if sampling is enabled
  29955. * @return true if enabled
  29956. */
  29957. get: function () {
  29958. return this._enabled;
  29959. },
  29960. enumerable: true,
  29961. configurable: true
  29962. });
  29963. /**
  29964. * Resets performance monitor
  29965. */
  29966. PerformanceMonitor.prototype.reset = function () {
  29967. //clear last sample to avoid interpolating over the disabled period when next enabled
  29968. this._lastFrameTimeMs = null;
  29969. this._lastChangeTimeMs = null;
  29970. //wipe record
  29971. this._rollingFrameTime.reset();
  29972. };
  29973. return PerformanceMonitor;
  29974. }());
  29975. BABYLON.PerformanceMonitor = PerformanceMonitor;
  29976. /**
  29977. * RollingAverage
  29978. *
  29979. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  29980. */
  29981. var RollingAverage = (function () {
  29982. /**
  29983. * constructor
  29984. * @param length The number of samples required to saturate the sliding window
  29985. */
  29986. function RollingAverage(length) {
  29987. this._samples = new Array(length);
  29988. this.reset();
  29989. }
  29990. /**
  29991. * Adds a sample to the sample set
  29992. * @param v The sample value
  29993. */
  29994. RollingAverage.prototype.add = function (v) {
  29995. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  29996. var delta;
  29997. //we need to check if we've already wrapped round
  29998. if (this.isSaturated()) {
  29999. //remove bottom of stack from mean
  30000. var bottomValue = this._samples[this._pos];
  30001. delta = bottomValue - this.average;
  30002. this.average -= delta / (this._sampleCount - 1);
  30003. this._m2 -= delta * (bottomValue - this.average);
  30004. }
  30005. else {
  30006. this._sampleCount++;
  30007. }
  30008. //add new value to mean
  30009. delta = v - this.average;
  30010. this.average += delta / (this._sampleCount);
  30011. this._m2 += delta * (v - this.average);
  30012. //set the new variance
  30013. this.variance = this._m2 / (this._sampleCount - 1);
  30014. this._samples[this._pos] = v;
  30015. this._pos++;
  30016. this._pos %= this._samples.length; //positive wrap around
  30017. };
  30018. /**
  30019. * Returns previously added values or null if outside of history or outside the sliding window domain
  30020. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30021. * @return Value previously recorded with add() or null if outside of range
  30022. */
  30023. RollingAverage.prototype.history = function (i) {
  30024. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30025. return null;
  30026. }
  30027. var i0 = this._wrapPosition(this._pos - 1.0);
  30028. return this._samples[this._wrapPosition(i0 - i)];
  30029. };
  30030. /**
  30031. * Returns true if enough samples have been taken to completely fill the sliding window
  30032. * @return true if sample-set saturated
  30033. */
  30034. RollingAverage.prototype.isSaturated = function () {
  30035. return this._sampleCount >= this._samples.length;
  30036. };
  30037. /**
  30038. * Resets the rolling average (equivalent to 0 samples taken so far)
  30039. */
  30040. RollingAverage.prototype.reset = function () {
  30041. this.average = 0;
  30042. this.variance = 0;
  30043. this._sampleCount = 0;
  30044. this._pos = 0;
  30045. this._m2 = 0;
  30046. };
  30047. /**
  30048. * Wraps a value around the sample range boundaries
  30049. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30050. * @return Wrapped position in sample range
  30051. */
  30052. RollingAverage.prototype._wrapPosition = function (i) {
  30053. var max = this._samples.length;
  30054. return ((i % max) + max) % max;
  30055. };
  30056. return RollingAverage;
  30057. }());
  30058. BABYLON.RollingAverage = RollingAverage;
  30059. })(BABYLON || (BABYLON = {}));
  30060. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30061. var BABYLON;
  30062. (function (BABYLON) {
  30063. var AnimationRange = (function () {
  30064. function AnimationRange(name, from, to) {
  30065. this.name = name;
  30066. this.from = from;
  30067. this.to = to;
  30068. }
  30069. AnimationRange.prototype.clone = function () {
  30070. return new AnimationRange(this.name, this.from, this.to);
  30071. };
  30072. return AnimationRange;
  30073. }());
  30074. BABYLON.AnimationRange = AnimationRange;
  30075. /**
  30076. * Composed of a frame, and an action function
  30077. */
  30078. var AnimationEvent = (function () {
  30079. function AnimationEvent(frame, action, onlyOnce) {
  30080. this.frame = frame;
  30081. this.action = action;
  30082. this.onlyOnce = onlyOnce;
  30083. this.isDone = false;
  30084. }
  30085. return AnimationEvent;
  30086. }());
  30087. BABYLON.AnimationEvent = AnimationEvent;
  30088. var PathCursor = (function () {
  30089. function PathCursor(path) {
  30090. this.path = path;
  30091. this._onchange = new Array();
  30092. this.value = 0;
  30093. this.animations = new Array();
  30094. }
  30095. PathCursor.prototype.getPoint = function () {
  30096. var point = this.path.getPointAtLengthPosition(this.value);
  30097. return new BABYLON.Vector3(point.x, 0, point.y);
  30098. };
  30099. PathCursor.prototype.moveAhead = function (step) {
  30100. if (step === void 0) { step = 0.002; }
  30101. this.move(step);
  30102. return this;
  30103. };
  30104. PathCursor.prototype.moveBack = function (step) {
  30105. if (step === void 0) { step = 0.002; }
  30106. this.move(-step);
  30107. return this;
  30108. };
  30109. PathCursor.prototype.move = function (step) {
  30110. if (Math.abs(step) > 1) {
  30111. throw "step size should be less than 1.";
  30112. }
  30113. this.value += step;
  30114. this.ensureLimits();
  30115. this.raiseOnChange();
  30116. return this;
  30117. };
  30118. PathCursor.prototype.ensureLimits = function () {
  30119. while (this.value > 1) {
  30120. this.value -= 1;
  30121. }
  30122. while (this.value < 0) {
  30123. this.value += 1;
  30124. }
  30125. return this;
  30126. };
  30127. // used by animation engine
  30128. PathCursor.prototype.markAsDirty = function (propertyName) {
  30129. this.ensureLimits();
  30130. this.raiseOnChange();
  30131. return this;
  30132. };
  30133. PathCursor.prototype.raiseOnChange = function () {
  30134. var _this = this;
  30135. this._onchange.forEach(function (f) { return f(_this); });
  30136. return this;
  30137. };
  30138. PathCursor.prototype.onchange = function (f) {
  30139. this._onchange.push(f);
  30140. return this;
  30141. };
  30142. return PathCursor;
  30143. }());
  30144. BABYLON.PathCursor = PathCursor;
  30145. var Animation = (function () {
  30146. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  30147. this.name = name;
  30148. this.targetProperty = targetProperty;
  30149. this.framePerSecond = framePerSecond;
  30150. this.dataType = dataType;
  30151. this.loopMode = loopMode;
  30152. this.enableBlending = enableBlending;
  30153. this._offsetsCache = {};
  30154. this._highLimitsCache = {};
  30155. this._stopped = false;
  30156. this._blendingFactor = 0;
  30157. // The set of event that will be linked to this animation
  30158. this._events = new Array();
  30159. this.allowMatricesInterpolation = false;
  30160. this.blendingSpeed = 0.01;
  30161. this._ranges = {};
  30162. this.targetPropertyPath = targetProperty.split(".");
  30163. this.dataType = dataType;
  30164. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  30165. }
  30166. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  30167. var dataType = undefined;
  30168. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  30169. dataType = Animation.ANIMATIONTYPE_FLOAT;
  30170. }
  30171. else if (from instanceof BABYLON.Quaternion) {
  30172. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  30173. }
  30174. else if (from instanceof BABYLON.Vector3) {
  30175. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  30176. }
  30177. else if (from instanceof BABYLON.Vector2) {
  30178. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  30179. }
  30180. else if (from instanceof BABYLON.Color3) {
  30181. dataType = Animation.ANIMATIONTYPE_COLOR3;
  30182. }
  30183. else if (from instanceof BABYLON.Size) {
  30184. dataType = Animation.ANIMATIONTYPE_SIZE;
  30185. }
  30186. if (dataType == undefined) {
  30187. return null;
  30188. }
  30189. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  30190. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  30191. animation.setKeys(keys);
  30192. if (easingFunction !== undefined) {
  30193. animation.setEasingFunction(easingFunction);
  30194. }
  30195. return animation;
  30196. };
  30197. /**
  30198. * Sets up an animation.
  30199. * @param property the property to animate
  30200. * @param animationType the animation type to apply
  30201. * @param easingFunction the easing function used in the animation
  30202. * @returns The created animation
  30203. */
  30204. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  30205. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  30206. animation.setEasingFunction(easingFunction);
  30207. return animation;
  30208. };
  30209. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30210. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30211. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30212. };
  30213. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30214. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30215. node.animations.push(animation);
  30216. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30217. };
  30218. /**
  30219. * Transition property of the Camera to the target Value.
  30220. * @param property The property to transition
  30221. * @param targetValue The target Value of the property
  30222. * @param host The object where the property to animate belongs
  30223. * @param scene Scene used to run the animation
  30224. * @param frameRate Framerate (in frame/s) to use
  30225. * @param transition The transition type we want to use
  30226. * @param duration The duration of the animation, in milliseconds
  30227. * @param onAnimationEnd Call back trigger at the end of the animation.
  30228. */
  30229. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  30230. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  30231. if (duration <= 0) {
  30232. host[property] = targetValue;
  30233. if (onAnimationEnd) {
  30234. onAnimationEnd();
  30235. }
  30236. return;
  30237. }
  30238. var endFrame = frameRate * (duration / 1000);
  30239. transition.setKeys([{
  30240. frame: 0,
  30241. value: host[property].clone ? host[property].clone() : host[property]
  30242. },
  30243. {
  30244. frame: endFrame,
  30245. value: targetValue
  30246. }]);
  30247. if (!host.animations) {
  30248. host.animations = [];
  30249. }
  30250. host.animations.push(transition);
  30251. var animation = scene.beginAnimation(host, 0, endFrame, false);
  30252. animation.onAnimationEnd = onAnimationEnd;
  30253. return animation;
  30254. };
  30255. // Methods
  30256. /**
  30257. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30258. */
  30259. Animation.prototype.toString = function (fullDetails) {
  30260. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  30261. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  30262. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  30263. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  30264. if (fullDetails) {
  30265. ret += ", Ranges: {";
  30266. var first = true;
  30267. for (var name in this._ranges) {
  30268. if (first) {
  30269. ret += ", ";
  30270. first = false;
  30271. }
  30272. ret += name;
  30273. }
  30274. ret += "}";
  30275. }
  30276. return ret;
  30277. };
  30278. /**
  30279. * Add an event to this animation.
  30280. */
  30281. Animation.prototype.addEvent = function (event) {
  30282. this._events.push(event);
  30283. };
  30284. /**
  30285. * Remove all events found at the given frame
  30286. * @param frame
  30287. */
  30288. Animation.prototype.removeEvents = function (frame) {
  30289. for (var index = 0; index < this._events.length; index++) {
  30290. if (this._events[index].frame === frame) {
  30291. this._events.splice(index, 1);
  30292. index--;
  30293. }
  30294. }
  30295. };
  30296. Animation.prototype.createRange = function (name, from, to) {
  30297. // check name not already in use; could happen for bones after serialized
  30298. if (!this._ranges[name]) {
  30299. this._ranges[name] = new AnimationRange(name, from, to);
  30300. }
  30301. };
  30302. Animation.prototype.deleteRange = function (name, deleteFrames) {
  30303. if (deleteFrames === void 0) { deleteFrames = true; }
  30304. if (this._ranges[name]) {
  30305. if (deleteFrames) {
  30306. var from = this._ranges[name].from;
  30307. var to = this._ranges[name].to;
  30308. // this loop MUST go high to low for multiple splices to work
  30309. for (var key = this._keys.length - 1; key >= 0; key--) {
  30310. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  30311. this._keys.splice(key, 1);
  30312. }
  30313. }
  30314. }
  30315. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  30316. }
  30317. };
  30318. Animation.prototype.getRange = function (name) {
  30319. return this._ranges[name];
  30320. };
  30321. Animation.prototype.reset = function () {
  30322. this._offsetsCache = {};
  30323. this._highLimitsCache = {};
  30324. this.currentFrame = 0;
  30325. this._blendingFactor = 0;
  30326. this._originalBlendValue = null;
  30327. };
  30328. Animation.prototype.isStopped = function () {
  30329. return this._stopped;
  30330. };
  30331. Animation.prototype.getKeys = function () {
  30332. return this._keys;
  30333. };
  30334. Animation.prototype.getHighestFrame = function () {
  30335. var ret = 0;
  30336. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  30337. if (ret < this._keys[key].frame) {
  30338. ret = this._keys[key].frame;
  30339. }
  30340. }
  30341. return ret;
  30342. };
  30343. Animation.prototype.getEasingFunction = function () {
  30344. return this._easingFunction;
  30345. };
  30346. Animation.prototype.setEasingFunction = function (easingFunction) {
  30347. this._easingFunction = easingFunction;
  30348. };
  30349. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  30350. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  30351. };
  30352. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30353. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30354. };
  30355. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  30356. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  30357. };
  30358. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30359. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  30360. };
  30361. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  30362. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  30363. };
  30364. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30365. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30366. };
  30367. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  30368. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  30369. };
  30370. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30371. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30372. };
  30373. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  30374. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  30375. };
  30376. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  30377. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  30378. };
  30379. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  30380. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  30381. };
  30382. Animation.prototype.clone = function () {
  30383. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  30384. clone.enableBlending = this.enableBlending;
  30385. clone.blendingSpeed = this.blendingSpeed;
  30386. if (this._keys) {
  30387. clone.setKeys(this._keys);
  30388. }
  30389. if (this._ranges) {
  30390. clone._ranges = {};
  30391. for (var name in this._ranges) {
  30392. clone._ranges[name] = this._ranges[name].clone();
  30393. }
  30394. }
  30395. return clone;
  30396. };
  30397. Animation.prototype.setKeys = function (values) {
  30398. this._keys = values.slice(0);
  30399. this._offsetsCache = {};
  30400. this._highLimitsCache = {};
  30401. };
  30402. Animation.prototype._getKeyValue = function (value) {
  30403. if (typeof value === "function") {
  30404. return value();
  30405. }
  30406. return value;
  30407. };
  30408. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  30409. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  30410. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  30411. }
  30412. this.currentFrame = currentFrame;
  30413. // Try to get a hash to find the right key
  30414. 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));
  30415. if (this._keys[startKeyIndex].frame >= currentFrame) {
  30416. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  30417. startKeyIndex--;
  30418. }
  30419. }
  30420. for (var key = startKeyIndex; key < this._keys.length; key++) {
  30421. var endKey = this._keys[key + 1];
  30422. if (endKey.frame >= currentFrame) {
  30423. var startKey = this._keys[key];
  30424. var startValue = this._getKeyValue(startKey.value);
  30425. var endValue = this._getKeyValue(endKey.value);
  30426. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  30427. var frameDelta = endKey.frame - startKey.frame;
  30428. // gradient : percent of currentFrame between the frame inf and the frame sup
  30429. var gradient = (currentFrame - startKey.frame) / frameDelta;
  30430. // check for easingFunction and correction of gradient
  30431. if (this._easingFunction != null) {
  30432. gradient = this._easingFunction.ease(gradient);
  30433. }
  30434. switch (this.dataType) {
  30435. // Float
  30436. case Animation.ANIMATIONTYPE_FLOAT:
  30437. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  30438. switch (loopMode) {
  30439. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30440. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30441. return floatValue;
  30442. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30443. return offsetValue * repeatCount + floatValue;
  30444. }
  30445. break;
  30446. // Quaternion
  30447. case Animation.ANIMATIONTYPE_QUATERNION:
  30448. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30449. switch (loopMode) {
  30450. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30451. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30452. return quatValue;
  30453. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30454. return quatValue.add(offsetValue.scale(repeatCount));
  30455. }
  30456. return quatValue;
  30457. // Vector3
  30458. case Animation.ANIMATIONTYPE_VECTOR3:
  30459. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  30460. switch (loopMode) {
  30461. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30462. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30463. return vec3Value;
  30464. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30465. return vec3Value.add(offsetValue.scale(repeatCount));
  30466. }
  30467. // Vector2
  30468. case Animation.ANIMATIONTYPE_VECTOR2:
  30469. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  30470. switch (loopMode) {
  30471. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30472. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30473. return vec2Value;
  30474. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30475. return vec2Value.add(offsetValue.scale(repeatCount));
  30476. }
  30477. // Size
  30478. case Animation.ANIMATIONTYPE_SIZE:
  30479. switch (loopMode) {
  30480. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30481. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30482. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30483. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30484. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30485. }
  30486. // Color3
  30487. case Animation.ANIMATIONTYPE_COLOR3:
  30488. switch (loopMode) {
  30489. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30490. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30491. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30492. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30493. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30494. }
  30495. // Matrix
  30496. case Animation.ANIMATIONTYPE_MATRIX:
  30497. switch (loopMode) {
  30498. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30499. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30500. if (this.allowMatricesInterpolation) {
  30501. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30502. }
  30503. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30504. return startValue;
  30505. }
  30506. default:
  30507. break;
  30508. }
  30509. break;
  30510. }
  30511. }
  30512. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30513. };
  30514. Animation.prototype.setValue = function (currentValue, blend) {
  30515. if (blend === void 0) { blend = false; }
  30516. // Set value
  30517. var path;
  30518. var destination;
  30519. if (this.targetPropertyPath.length > 1) {
  30520. var property = this._target[this.targetPropertyPath[0]];
  30521. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30522. property = property[this.targetPropertyPath[index]];
  30523. }
  30524. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30525. destination = property;
  30526. }
  30527. else {
  30528. path = this.targetPropertyPath[0];
  30529. destination = this._target;
  30530. }
  30531. // Blending
  30532. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30533. if (!this._originalBlendValue) {
  30534. if (destination[path].clone) {
  30535. this._originalBlendValue = destination[path].clone();
  30536. }
  30537. else {
  30538. this._originalBlendValue = destination[path];
  30539. }
  30540. }
  30541. if (this._originalBlendValue.prototype) {
  30542. if (this._originalBlendValue.prototype.Lerp) {
  30543. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30544. }
  30545. else {
  30546. destination[path] = currentValue;
  30547. }
  30548. }
  30549. else if (this._originalBlendValue.m) {
  30550. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30551. }
  30552. else {
  30553. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30554. }
  30555. this._blendingFactor += this.blendingSpeed;
  30556. }
  30557. else {
  30558. destination[path] = currentValue;
  30559. }
  30560. if (this._target.markAsDirty) {
  30561. this._target.markAsDirty(this.targetProperty);
  30562. }
  30563. };
  30564. Animation.prototype.goToFrame = function (frame) {
  30565. if (frame < this._keys[0].frame) {
  30566. frame = this._keys[0].frame;
  30567. }
  30568. else if (frame > this._keys[this._keys.length - 1].frame) {
  30569. frame = this._keys[this._keys.length - 1].frame;
  30570. }
  30571. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30572. this.setValue(currentValue);
  30573. };
  30574. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30575. if (blend === void 0) { blend = false; }
  30576. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30577. this._stopped = true;
  30578. return false;
  30579. }
  30580. var returnValue = true;
  30581. // Adding a start key at frame 0 if missing
  30582. if (this._keys[0].frame !== 0) {
  30583. var newKey = { frame: 0, value: this._keys[0].value };
  30584. this._keys.splice(0, 0, newKey);
  30585. }
  30586. // Check limits
  30587. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30588. from = this._keys[0].frame;
  30589. }
  30590. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30591. to = this._keys[this._keys.length - 1].frame;
  30592. }
  30593. //to and from cannot be the same key
  30594. if (from === to) {
  30595. from++;
  30596. }
  30597. // Compute ratio
  30598. var range = to - from;
  30599. var offsetValue;
  30600. // ratio represents the frame delta between from and to
  30601. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30602. var highLimitValue = 0;
  30603. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  30604. returnValue = false;
  30605. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30606. }
  30607. else {
  30608. // Get max value if required
  30609. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30610. var keyOffset = to.toString() + from.toString();
  30611. if (!this._offsetsCache[keyOffset]) {
  30612. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30613. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30614. switch (this.dataType) {
  30615. // Float
  30616. case Animation.ANIMATIONTYPE_FLOAT:
  30617. this._offsetsCache[keyOffset] = toValue - fromValue;
  30618. break;
  30619. // Quaternion
  30620. case Animation.ANIMATIONTYPE_QUATERNION:
  30621. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30622. break;
  30623. // Vector3
  30624. case Animation.ANIMATIONTYPE_VECTOR3:
  30625. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30626. // Vector2
  30627. case Animation.ANIMATIONTYPE_VECTOR2:
  30628. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30629. // Size
  30630. case Animation.ANIMATIONTYPE_SIZE:
  30631. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30632. // Color3
  30633. case Animation.ANIMATIONTYPE_COLOR3:
  30634. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30635. default:
  30636. break;
  30637. }
  30638. this._highLimitsCache[keyOffset] = toValue;
  30639. }
  30640. highLimitValue = this._highLimitsCache[keyOffset];
  30641. offsetValue = this._offsetsCache[keyOffset];
  30642. }
  30643. }
  30644. if (offsetValue === undefined) {
  30645. switch (this.dataType) {
  30646. // Float
  30647. case Animation.ANIMATIONTYPE_FLOAT:
  30648. offsetValue = 0;
  30649. break;
  30650. // Quaternion
  30651. case Animation.ANIMATIONTYPE_QUATERNION:
  30652. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30653. break;
  30654. // Vector3
  30655. case Animation.ANIMATIONTYPE_VECTOR3:
  30656. offsetValue = BABYLON.Vector3.Zero();
  30657. break;
  30658. // Vector2
  30659. case Animation.ANIMATIONTYPE_VECTOR2:
  30660. offsetValue = BABYLON.Vector2.Zero();
  30661. break;
  30662. // Size
  30663. case Animation.ANIMATIONTYPE_SIZE:
  30664. offsetValue = BABYLON.Size.Zero();
  30665. break;
  30666. // Color3
  30667. case Animation.ANIMATIONTYPE_COLOR3:
  30668. offsetValue = BABYLON.Color3.Black();
  30669. }
  30670. }
  30671. // Compute value
  30672. var repeatCount = (ratio / range) >> 0;
  30673. var currentFrame = returnValue ? from + ratio % range : to;
  30674. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30675. // Set value
  30676. this.setValue(currentValue);
  30677. // Check events
  30678. for (var index = 0; index < this._events.length; index++) {
  30679. // Make sure current frame has passed event frame and that event frame is within the current range
  30680. // Also, handle both forward and reverse animations
  30681. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  30682. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  30683. var event = this._events[index];
  30684. if (!event.isDone) {
  30685. // If event should be done only once, remove it.
  30686. if (event.onlyOnce) {
  30687. this._events.splice(index, 1);
  30688. index--;
  30689. }
  30690. event.isDone = true;
  30691. event.action();
  30692. } // Don't do anything if the event has already be done.
  30693. }
  30694. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30695. // reset event, the animation is looping
  30696. this._events[index].isDone = false;
  30697. }
  30698. }
  30699. if (!returnValue) {
  30700. this._stopped = true;
  30701. }
  30702. return returnValue;
  30703. };
  30704. Animation.prototype.serialize = function () {
  30705. var serializationObject = {};
  30706. serializationObject.name = this.name;
  30707. serializationObject.property = this.targetProperty;
  30708. serializationObject.framePerSecond = this.framePerSecond;
  30709. serializationObject.dataType = this.dataType;
  30710. serializationObject.loopBehavior = this.loopMode;
  30711. serializationObject.enableBlending = this.enableBlending;
  30712. serializationObject.blendingSpeed = this.blendingSpeed;
  30713. var dataType = this.dataType;
  30714. serializationObject.keys = [];
  30715. var keys = this.getKeys();
  30716. for (var index = 0; index < keys.length; index++) {
  30717. var animationKey = keys[index];
  30718. var key = {};
  30719. key.frame = animationKey.frame;
  30720. switch (dataType) {
  30721. case Animation.ANIMATIONTYPE_FLOAT:
  30722. key.values = [animationKey.value];
  30723. break;
  30724. case Animation.ANIMATIONTYPE_QUATERNION:
  30725. case Animation.ANIMATIONTYPE_MATRIX:
  30726. case Animation.ANIMATIONTYPE_VECTOR3:
  30727. case Animation.ANIMATIONTYPE_COLOR3:
  30728. key.values = animationKey.value.asArray();
  30729. break;
  30730. }
  30731. serializationObject.keys.push(key);
  30732. }
  30733. serializationObject.ranges = [];
  30734. for (var name in this._ranges) {
  30735. var range = {};
  30736. range.name = name;
  30737. range.from = this._ranges[name].from;
  30738. range.to = this._ranges[name].to;
  30739. serializationObject.ranges.push(range);
  30740. }
  30741. return serializationObject;
  30742. };
  30743. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30744. get: function () {
  30745. return Animation._ANIMATIONTYPE_FLOAT;
  30746. },
  30747. enumerable: true,
  30748. configurable: true
  30749. });
  30750. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30751. get: function () {
  30752. return Animation._ANIMATIONTYPE_VECTOR3;
  30753. },
  30754. enumerable: true,
  30755. configurable: true
  30756. });
  30757. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30758. get: function () {
  30759. return Animation._ANIMATIONTYPE_VECTOR2;
  30760. },
  30761. enumerable: true,
  30762. configurable: true
  30763. });
  30764. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30765. get: function () {
  30766. return Animation._ANIMATIONTYPE_SIZE;
  30767. },
  30768. enumerable: true,
  30769. configurable: true
  30770. });
  30771. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30772. get: function () {
  30773. return Animation._ANIMATIONTYPE_QUATERNION;
  30774. },
  30775. enumerable: true,
  30776. configurable: true
  30777. });
  30778. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30779. get: function () {
  30780. return Animation._ANIMATIONTYPE_MATRIX;
  30781. },
  30782. enumerable: true,
  30783. configurable: true
  30784. });
  30785. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30786. get: function () {
  30787. return Animation._ANIMATIONTYPE_COLOR3;
  30788. },
  30789. enumerable: true,
  30790. configurable: true
  30791. });
  30792. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30793. get: function () {
  30794. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30795. },
  30796. enumerable: true,
  30797. configurable: true
  30798. });
  30799. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30800. get: function () {
  30801. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30802. },
  30803. enumerable: true,
  30804. configurable: true
  30805. });
  30806. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30807. get: function () {
  30808. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30809. },
  30810. enumerable: true,
  30811. configurable: true
  30812. });
  30813. Animation.Parse = function (parsedAnimation) {
  30814. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30815. var dataType = parsedAnimation.dataType;
  30816. var keys = [];
  30817. var data;
  30818. var index;
  30819. if (parsedAnimation.enableBlending) {
  30820. animation.enableBlending = parsedAnimation.enableBlending;
  30821. }
  30822. if (parsedAnimation.blendingSpeed) {
  30823. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30824. }
  30825. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30826. var key = parsedAnimation.keys[index];
  30827. switch (dataType) {
  30828. case Animation.ANIMATIONTYPE_FLOAT:
  30829. data = key.values[0];
  30830. break;
  30831. case Animation.ANIMATIONTYPE_QUATERNION:
  30832. data = BABYLON.Quaternion.FromArray(key.values);
  30833. break;
  30834. case Animation.ANIMATIONTYPE_MATRIX:
  30835. data = BABYLON.Matrix.FromArray(key.values);
  30836. break;
  30837. case Animation.ANIMATIONTYPE_COLOR3:
  30838. data = BABYLON.Color3.FromArray(key.values);
  30839. break;
  30840. case Animation.ANIMATIONTYPE_VECTOR3:
  30841. default:
  30842. data = BABYLON.Vector3.FromArray(key.values);
  30843. break;
  30844. }
  30845. keys.push({
  30846. frame: key.frame,
  30847. value: data
  30848. });
  30849. }
  30850. animation.setKeys(keys);
  30851. if (parsedAnimation.ranges) {
  30852. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30853. data = parsedAnimation.ranges[index];
  30854. animation.createRange(data.name, data.from, data.to);
  30855. }
  30856. }
  30857. return animation;
  30858. };
  30859. Animation.AppendSerializedAnimations = function (source, destination) {
  30860. if (source.animations) {
  30861. destination.animations = [];
  30862. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30863. var animation = source.animations[animationIndex];
  30864. destination.animations.push(animation.serialize());
  30865. }
  30866. }
  30867. };
  30868. // Statics
  30869. Animation._ANIMATIONTYPE_FLOAT = 0;
  30870. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  30871. Animation._ANIMATIONTYPE_QUATERNION = 2;
  30872. Animation._ANIMATIONTYPE_MATRIX = 3;
  30873. Animation._ANIMATIONTYPE_COLOR3 = 4;
  30874. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  30875. Animation._ANIMATIONTYPE_SIZE = 6;
  30876. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  30877. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  30878. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  30879. return Animation;
  30880. }());
  30881. BABYLON.Animation = Animation;
  30882. })(BABYLON || (BABYLON = {}));
  30883. //# sourceMappingURL=babylon.animation.js.map
  30884. var BABYLON;
  30885. (function (BABYLON) {
  30886. var Animatable = (function () {
  30887. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  30888. if (fromFrame === void 0) { fromFrame = 0; }
  30889. if (toFrame === void 0) { toFrame = 100; }
  30890. if (loopAnimation === void 0) { loopAnimation = false; }
  30891. if (speedRatio === void 0) { speedRatio = 1.0; }
  30892. this.target = target;
  30893. this.fromFrame = fromFrame;
  30894. this.toFrame = toFrame;
  30895. this.loopAnimation = loopAnimation;
  30896. this.speedRatio = speedRatio;
  30897. this.onAnimationEnd = onAnimationEnd;
  30898. this._localDelayOffset = null;
  30899. this._pausedDelay = null;
  30900. this._animations = new Array();
  30901. this._paused = false;
  30902. this.animationStarted = false;
  30903. if (animations) {
  30904. this.appendAnimations(target, animations);
  30905. }
  30906. this._scene = scene;
  30907. scene._activeAnimatables.push(this);
  30908. }
  30909. // Methods
  30910. Animatable.prototype.getAnimations = function () {
  30911. return this._animations;
  30912. };
  30913. Animatable.prototype.appendAnimations = function (target, animations) {
  30914. for (var index = 0; index < animations.length; index++) {
  30915. var animation = animations[index];
  30916. animation._target = target;
  30917. this._animations.push(animation);
  30918. }
  30919. };
  30920. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  30921. var animations = this._animations;
  30922. for (var index = 0; index < animations.length; index++) {
  30923. if (animations[index].targetProperty === property) {
  30924. return animations[index];
  30925. }
  30926. }
  30927. return null;
  30928. };
  30929. Animatable.prototype.reset = function () {
  30930. var animations = this._animations;
  30931. for (var index = 0; index < animations.length; index++) {
  30932. animations[index].reset();
  30933. }
  30934. this._localDelayOffset = null;
  30935. this._pausedDelay = null;
  30936. };
  30937. Animatable.prototype.enableBlending = function (blendingSpeed) {
  30938. var animations = this._animations;
  30939. for (var index = 0; index < animations.length; index++) {
  30940. animations[index].enableBlending = true;
  30941. animations[index].blendingSpeed = blendingSpeed;
  30942. }
  30943. };
  30944. Animatable.prototype.disableBlending = function () {
  30945. var animations = this._animations;
  30946. for (var index = 0; index < animations.length; index++) {
  30947. animations[index].enableBlending = false;
  30948. }
  30949. };
  30950. Animatable.prototype.goToFrame = function (frame) {
  30951. var animations = this._animations;
  30952. if (animations[0]) {
  30953. var fps = animations[0].framePerSecond;
  30954. var currentFrame = animations[0].currentFrame;
  30955. var adjustTime = frame - currentFrame;
  30956. var delay = adjustTime * 1000 / fps;
  30957. this._localDelayOffset -= delay;
  30958. }
  30959. for (var index = 0; index < animations.length; index++) {
  30960. animations[index].goToFrame(frame);
  30961. }
  30962. };
  30963. Animatable.prototype.pause = function () {
  30964. if (this._paused) {
  30965. return;
  30966. }
  30967. this._paused = true;
  30968. };
  30969. Animatable.prototype.restart = function () {
  30970. this._paused = false;
  30971. };
  30972. Animatable.prototype.stop = function (animationName) {
  30973. if (animationName) {
  30974. var idx = this._scene._activeAnimatables.indexOf(this);
  30975. if (idx > -1) {
  30976. var animations = this._animations;
  30977. for (var index = animations.length - 1; index >= 0; index--) {
  30978. if (typeof animationName === "string" && animations[index].name != animationName) {
  30979. continue;
  30980. }
  30981. animations[index].reset();
  30982. animations.splice(index, 1);
  30983. }
  30984. if (animations.length == 0) {
  30985. this._scene._activeAnimatables.splice(idx, 1);
  30986. if (this.onAnimationEnd) {
  30987. this.onAnimationEnd();
  30988. }
  30989. }
  30990. }
  30991. }
  30992. else {
  30993. var index = this._scene._activeAnimatables.indexOf(this);
  30994. if (index > -1) {
  30995. this._scene._activeAnimatables.splice(index, 1);
  30996. var animations = this._animations;
  30997. for (var index = 0; index < animations.length; index++) {
  30998. animations[index].reset();
  30999. }
  31000. if (this.onAnimationEnd) {
  31001. this.onAnimationEnd();
  31002. }
  31003. }
  31004. }
  31005. };
  31006. Animatable.prototype._animate = function (delay) {
  31007. if (this._paused) {
  31008. this.animationStarted = false;
  31009. if (this._pausedDelay === null) {
  31010. this._pausedDelay = delay;
  31011. }
  31012. return true;
  31013. }
  31014. if (this._localDelayOffset === null) {
  31015. this._localDelayOffset = delay;
  31016. }
  31017. else if (this._pausedDelay !== null) {
  31018. this._localDelayOffset += delay - this._pausedDelay;
  31019. this._pausedDelay = null;
  31020. }
  31021. // Animating
  31022. var running = false;
  31023. var animations = this._animations;
  31024. var index;
  31025. for (index = 0; index < animations.length; index++) {
  31026. var animation = animations[index];
  31027. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  31028. running = running || isRunning;
  31029. }
  31030. this.animationStarted = running;
  31031. if (!running) {
  31032. // Remove from active animatables
  31033. index = this._scene._activeAnimatables.indexOf(this);
  31034. this._scene._activeAnimatables.splice(index, 1);
  31035. }
  31036. if (!running && this.onAnimationEnd) {
  31037. this.onAnimationEnd();
  31038. this.onAnimationEnd = null;
  31039. }
  31040. return running;
  31041. };
  31042. return Animatable;
  31043. }());
  31044. BABYLON.Animatable = Animatable;
  31045. })(BABYLON || (BABYLON = {}));
  31046. //# sourceMappingURL=babylon.animatable.js.map
  31047. var BABYLON;
  31048. (function (BABYLON) {
  31049. var EasingFunction = (function () {
  31050. function EasingFunction() {
  31051. // Properties
  31052. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  31053. }
  31054. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  31055. get: function () {
  31056. return EasingFunction._EASINGMODE_EASEIN;
  31057. },
  31058. enumerable: true,
  31059. configurable: true
  31060. });
  31061. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  31062. get: function () {
  31063. return EasingFunction._EASINGMODE_EASEOUT;
  31064. },
  31065. enumerable: true,
  31066. configurable: true
  31067. });
  31068. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  31069. get: function () {
  31070. return EasingFunction._EASINGMODE_EASEINOUT;
  31071. },
  31072. enumerable: true,
  31073. configurable: true
  31074. });
  31075. EasingFunction.prototype.setEasingMode = function (easingMode) {
  31076. var n = Math.min(Math.max(easingMode, 0), 2);
  31077. this._easingMode = n;
  31078. };
  31079. EasingFunction.prototype.getEasingMode = function () {
  31080. return this._easingMode;
  31081. };
  31082. EasingFunction.prototype.easeInCore = function (gradient) {
  31083. throw new Error('You must implement this method');
  31084. };
  31085. EasingFunction.prototype.ease = function (gradient) {
  31086. switch (this._easingMode) {
  31087. case EasingFunction.EASINGMODE_EASEIN:
  31088. return this.easeInCore(gradient);
  31089. case EasingFunction.EASINGMODE_EASEOUT:
  31090. return (1 - this.easeInCore(1 - gradient));
  31091. }
  31092. if (gradient >= 0.5) {
  31093. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  31094. }
  31095. return (this.easeInCore(gradient * 2) * 0.5);
  31096. };
  31097. //Statics
  31098. EasingFunction._EASINGMODE_EASEIN = 0;
  31099. EasingFunction._EASINGMODE_EASEOUT = 1;
  31100. EasingFunction._EASINGMODE_EASEINOUT = 2;
  31101. return EasingFunction;
  31102. }());
  31103. BABYLON.EasingFunction = EasingFunction;
  31104. var CircleEase = (function (_super) {
  31105. __extends(CircleEase, _super);
  31106. function CircleEase() {
  31107. return _super !== null && _super.apply(this, arguments) || this;
  31108. }
  31109. CircleEase.prototype.easeInCore = function (gradient) {
  31110. gradient = Math.max(0, Math.min(1, gradient));
  31111. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  31112. };
  31113. return CircleEase;
  31114. }(EasingFunction));
  31115. BABYLON.CircleEase = CircleEase;
  31116. var BackEase = (function (_super) {
  31117. __extends(BackEase, _super);
  31118. function BackEase(amplitude) {
  31119. if (amplitude === void 0) { amplitude = 1; }
  31120. var _this = _super.call(this) || this;
  31121. _this.amplitude = amplitude;
  31122. return _this;
  31123. }
  31124. BackEase.prototype.easeInCore = function (gradient) {
  31125. var num = Math.max(0, this.amplitude);
  31126. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  31127. };
  31128. return BackEase;
  31129. }(EasingFunction));
  31130. BABYLON.BackEase = BackEase;
  31131. var BounceEase = (function (_super) {
  31132. __extends(BounceEase, _super);
  31133. function BounceEase(bounces, bounciness) {
  31134. if (bounces === void 0) { bounces = 3; }
  31135. if (bounciness === void 0) { bounciness = 2; }
  31136. var _this = _super.call(this) || this;
  31137. _this.bounces = bounces;
  31138. _this.bounciness = bounciness;
  31139. return _this;
  31140. }
  31141. BounceEase.prototype.easeInCore = function (gradient) {
  31142. var y = Math.max(0.0, this.bounces);
  31143. var bounciness = this.bounciness;
  31144. if (bounciness <= 1.0) {
  31145. bounciness = 1.001;
  31146. }
  31147. var num9 = Math.pow(bounciness, y);
  31148. var num5 = 1.0 - bounciness;
  31149. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  31150. var num15 = gradient * num4;
  31151. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  31152. var num3 = Math.floor(num65);
  31153. var num13 = num3 + 1.0;
  31154. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  31155. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  31156. var num7 = (num8 + num12) * 0.5;
  31157. var num6 = gradient - num7;
  31158. var num2 = num7 - num8;
  31159. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  31160. };
  31161. return BounceEase;
  31162. }(EasingFunction));
  31163. BABYLON.BounceEase = BounceEase;
  31164. var CubicEase = (function (_super) {
  31165. __extends(CubicEase, _super);
  31166. function CubicEase() {
  31167. return _super !== null && _super.apply(this, arguments) || this;
  31168. }
  31169. CubicEase.prototype.easeInCore = function (gradient) {
  31170. return (gradient * gradient * gradient);
  31171. };
  31172. return CubicEase;
  31173. }(EasingFunction));
  31174. BABYLON.CubicEase = CubicEase;
  31175. var ElasticEase = (function (_super) {
  31176. __extends(ElasticEase, _super);
  31177. function ElasticEase(oscillations, springiness) {
  31178. if (oscillations === void 0) { oscillations = 3; }
  31179. if (springiness === void 0) { springiness = 3; }
  31180. var _this = _super.call(this) || this;
  31181. _this.oscillations = oscillations;
  31182. _this.springiness = springiness;
  31183. return _this;
  31184. }
  31185. ElasticEase.prototype.easeInCore = function (gradient) {
  31186. var num2;
  31187. var num3 = Math.max(0.0, this.oscillations);
  31188. var num = Math.max(0.0, this.springiness);
  31189. if (num == 0) {
  31190. num2 = gradient;
  31191. }
  31192. else {
  31193. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  31194. }
  31195. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  31196. };
  31197. return ElasticEase;
  31198. }(EasingFunction));
  31199. BABYLON.ElasticEase = ElasticEase;
  31200. var ExponentialEase = (function (_super) {
  31201. __extends(ExponentialEase, _super);
  31202. function ExponentialEase(exponent) {
  31203. if (exponent === void 0) { exponent = 2; }
  31204. var _this = _super.call(this) || this;
  31205. _this.exponent = exponent;
  31206. return _this;
  31207. }
  31208. ExponentialEase.prototype.easeInCore = function (gradient) {
  31209. if (this.exponent <= 0) {
  31210. return gradient;
  31211. }
  31212. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  31213. };
  31214. return ExponentialEase;
  31215. }(EasingFunction));
  31216. BABYLON.ExponentialEase = ExponentialEase;
  31217. var PowerEase = (function (_super) {
  31218. __extends(PowerEase, _super);
  31219. function PowerEase(power) {
  31220. if (power === void 0) { power = 2; }
  31221. var _this = _super.call(this) || this;
  31222. _this.power = power;
  31223. return _this;
  31224. }
  31225. PowerEase.prototype.easeInCore = function (gradient) {
  31226. var y = Math.max(0.0, this.power);
  31227. return Math.pow(gradient, y);
  31228. };
  31229. return PowerEase;
  31230. }(EasingFunction));
  31231. BABYLON.PowerEase = PowerEase;
  31232. var QuadraticEase = (function (_super) {
  31233. __extends(QuadraticEase, _super);
  31234. function QuadraticEase() {
  31235. return _super !== null && _super.apply(this, arguments) || this;
  31236. }
  31237. QuadraticEase.prototype.easeInCore = function (gradient) {
  31238. return (gradient * gradient);
  31239. };
  31240. return QuadraticEase;
  31241. }(EasingFunction));
  31242. BABYLON.QuadraticEase = QuadraticEase;
  31243. var QuarticEase = (function (_super) {
  31244. __extends(QuarticEase, _super);
  31245. function QuarticEase() {
  31246. return _super !== null && _super.apply(this, arguments) || this;
  31247. }
  31248. QuarticEase.prototype.easeInCore = function (gradient) {
  31249. return (gradient * gradient * gradient * gradient);
  31250. };
  31251. return QuarticEase;
  31252. }(EasingFunction));
  31253. BABYLON.QuarticEase = QuarticEase;
  31254. var QuinticEase = (function (_super) {
  31255. __extends(QuinticEase, _super);
  31256. function QuinticEase() {
  31257. return _super !== null && _super.apply(this, arguments) || this;
  31258. }
  31259. QuinticEase.prototype.easeInCore = function (gradient) {
  31260. return (gradient * gradient * gradient * gradient * gradient);
  31261. };
  31262. return QuinticEase;
  31263. }(EasingFunction));
  31264. BABYLON.QuinticEase = QuinticEase;
  31265. var SineEase = (function (_super) {
  31266. __extends(SineEase, _super);
  31267. function SineEase() {
  31268. return _super !== null && _super.apply(this, arguments) || this;
  31269. }
  31270. SineEase.prototype.easeInCore = function (gradient) {
  31271. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  31272. };
  31273. return SineEase;
  31274. }(EasingFunction));
  31275. BABYLON.SineEase = SineEase;
  31276. var BezierCurveEase = (function (_super) {
  31277. __extends(BezierCurveEase, _super);
  31278. function BezierCurveEase(x1, y1, x2, y2) {
  31279. if (x1 === void 0) { x1 = 0; }
  31280. if (y1 === void 0) { y1 = 0; }
  31281. if (x2 === void 0) { x2 = 1; }
  31282. if (y2 === void 0) { y2 = 1; }
  31283. var _this = _super.call(this) || this;
  31284. _this.x1 = x1;
  31285. _this.y1 = y1;
  31286. _this.x2 = x2;
  31287. _this.y2 = y2;
  31288. return _this;
  31289. }
  31290. BezierCurveEase.prototype.easeInCore = function (gradient) {
  31291. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  31292. };
  31293. return BezierCurveEase;
  31294. }(EasingFunction));
  31295. BABYLON.BezierCurveEase = BezierCurveEase;
  31296. })(BABYLON || (BABYLON = {}));
  31297. //# sourceMappingURL=babylon.easing.js.map
  31298. var BABYLON;
  31299. (function (BABYLON) {
  31300. BABYLON.CameraInputTypes = {};
  31301. var CameraInputsManager = (function () {
  31302. function CameraInputsManager(camera) {
  31303. this.attached = {};
  31304. this.camera = camera;
  31305. this.checkInputs = function () { };
  31306. }
  31307. CameraInputsManager.prototype.add = function (input) {
  31308. var type = input.getSimpleName();
  31309. if (this.attached[type]) {
  31310. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  31311. return;
  31312. }
  31313. this.attached[type] = input;
  31314. input.camera = this.camera;
  31315. //for checkInputs, we are dynamically creating a function
  31316. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  31317. if (input.checkInputs) {
  31318. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31319. }
  31320. if (this.attachedElement) {
  31321. input.attachControl(this.attachedElement);
  31322. }
  31323. };
  31324. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31325. for (var cam in this.attached) {
  31326. var input = this.attached[cam];
  31327. if (input === inputToRemove) {
  31328. input.detachControl(this.attachedElement);
  31329. input.camera = null;
  31330. delete this.attached[cam];
  31331. this.rebuildInputCheck();
  31332. }
  31333. }
  31334. };
  31335. CameraInputsManager.prototype.removeByType = function (inputType) {
  31336. for (var cam in this.attached) {
  31337. var input = this.attached[cam];
  31338. if (input.getClassName() === inputType) {
  31339. input.detachControl(this.attachedElement);
  31340. input.camera = null;
  31341. delete this.attached[cam];
  31342. this.rebuildInputCheck();
  31343. }
  31344. }
  31345. };
  31346. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31347. var current = this.checkInputs;
  31348. return function () {
  31349. current();
  31350. fn();
  31351. };
  31352. };
  31353. CameraInputsManager.prototype.attachInput = function (input) {
  31354. input.attachControl(this.attachedElement, this.noPreventDefault);
  31355. };
  31356. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31357. if (this.attachedElement) {
  31358. return;
  31359. }
  31360. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31361. this.attachedElement = element;
  31362. this.noPreventDefault = noPreventDefault;
  31363. for (var cam in this.attached) {
  31364. var input = this.attached[cam];
  31365. this.attached[cam].attachControl(element, noPreventDefault);
  31366. }
  31367. };
  31368. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  31369. if (disconnect === void 0) { disconnect = false; }
  31370. if (this.attachedElement !== element) {
  31371. return;
  31372. }
  31373. for (var cam in this.attached) {
  31374. var input = this.attached[cam];
  31375. this.attached[cam].detachControl(element);
  31376. if (disconnect) {
  31377. this.attached[cam].camera = null;
  31378. }
  31379. }
  31380. this.attachedElement = null;
  31381. };
  31382. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31383. this.checkInputs = function () { };
  31384. for (var cam in this.attached) {
  31385. var input = this.attached[cam];
  31386. if (input.checkInputs) {
  31387. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31388. }
  31389. }
  31390. };
  31391. CameraInputsManager.prototype.clear = function () {
  31392. if (this.attachedElement) {
  31393. this.detachElement(this.attachedElement, true);
  31394. }
  31395. this.attached = {};
  31396. this.attachedElement = null;
  31397. this.checkInputs = function () { };
  31398. };
  31399. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31400. var inputs = {};
  31401. for (var cam in this.attached) {
  31402. var input = this.attached[cam];
  31403. var res = BABYLON.SerializationHelper.Serialize(input);
  31404. inputs[input.getClassName()] = res;
  31405. }
  31406. serializedCamera.inputsmgr = inputs;
  31407. };
  31408. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31409. var parsedInputs = parsedCamera.inputsmgr;
  31410. if (parsedInputs) {
  31411. this.clear();
  31412. for (var n in parsedInputs) {
  31413. var construct = BABYLON.CameraInputTypes[n];
  31414. if (construct) {
  31415. var parsedinput = parsedInputs[n];
  31416. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31417. this.add(input);
  31418. }
  31419. }
  31420. }
  31421. else {
  31422. //2016-03-08 this part is for managing backward compatibility
  31423. for (var n in this.attached) {
  31424. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  31425. if (construct) {
  31426. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31427. this.remove(this.attached[n]);
  31428. this.add(input);
  31429. }
  31430. }
  31431. }
  31432. };
  31433. return CameraInputsManager;
  31434. }());
  31435. BABYLON.CameraInputsManager = CameraInputsManager;
  31436. })(BABYLON || (BABYLON = {}));
  31437. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31438. /// <reference path="babylon.camera.ts" />
  31439. var BABYLON;
  31440. (function (BABYLON) {
  31441. var TargetCamera = (function (_super) {
  31442. __extends(TargetCamera, _super);
  31443. function TargetCamera(name, position, scene) {
  31444. var _this = _super.call(this, name, position, scene) || this;
  31445. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  31446. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  31447. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  31448. _this.speed = 2.0;
  31449. _this.noRotationConstraint = false;
  31450. _this.lockedTarget = null;
  31451. _this._currentTarget = BABYLON.Vector3.Zero();
  31452. _this._viewMatrix = BABYLON.Matrix.Zero();
  31453. _this._camMatrix = BABYLON.Matrix.Zero();
  31454. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  31455. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  31456. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  31457. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  31458. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  31459. _this._lookAtTemp = BABYLON.Matrix.Zero();
  31460. _this._tempMatrix = BABYLON.Matrix.Zero();
  31461. return _this;
  31462. }
  31463. TargetCamera.prototype.getFrontPosition = function (distance) {
  31464. var direction = this.getTarget().subtract(this.position);
  31465. direction.normalize();
  31466. direction.scaleInPlace(distance);
  31467. return this.globalPosition.add(direction);
  31468. };
  31469. TargetCamera.prototype._getLockedTargetPosition = function () {
  31470. if (!this.lockedTarget) {
  31471. return null;
  31472. }
  31473. if (this.lockedTarget.absolutePosition) {
  31474. this.lockedTarget.computeWorldMatrix();
  31475. }
  31476. return this.lockedTarget.absolutePosition || this.lockedTarget;
  31477. };
  31478. TargetCamera.prototype.storeState = function () {
  31479. this._storedPosition = this.position.clone();
  31480. this._storedRotation = this.rotation.clone();
  31481. if (this.rotationQuaternion) {
  31482. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  31483. }
  31484. return _super.prototype.storeState.call(this);
  31485. };
  31486. /**
  31487. * Restored camera state. You must call storeState() first
  31488. */
  31489. TargetCamera.prototype.restoreState = function () {
  31490. if (!_super.prototype.restoreState.call(this)) {
  31491. return false;
  31492. }
  31493. this.position = this._storedPosition.clone();
  31494. this.rotation = this._storedRotation.clone();
  31495. if (this.rotationQuaternion) {
  31496. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  31497. }
  31498. this.cameraDirection.copyFromFloats(0, 0, 0);
  31499. this.cameraRotation.copyFromFloats(0, 0);
  31500. return true;
  31501. };
  31502. // Cache
  31503. TargetCamera.prototype._initCache = function () {
  31504. _super.prototype._initCache.call(this);
  31505. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31506. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31507. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31508. };
  31509. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31510. if (!ignoreParentClass) {
  31511. _super.prototype._updateCache.call(this);
  31512. }
  31513. var lockedTargetPosition = this._getLockedTargetPosition();
  31514. if (!lockedTargetPosition) {
  31515. this._cache.lockedTarget = null;
  31516. }
  31517. else {
  31518. if (!this._cache.lockedTarget) {
  31519. this._cache.lockedTarget = lockedTargetPosition.clone();
  31520. }
  31521. else {
  31522. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31523. }
  31524. }
  31525. this._cache.rotation.copyFrom(this.rotation);
  31526. if (this.rotationQuaternion)
  31527. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31528. };
  31529. // Synchronized
  31530. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31531. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31532. return false;
  31533. }
  31534. var lockedTargetPosition = this._getLockedTargetPosition();
  31535. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31536. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31537. };
  31538. // Methods
  31539. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31540. var engine = this.getEngine();
  31541. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31542. };
  31543. // Target
  31544. TargetCamera.prototype.setTarget = function (target) {
  31545. this.upVector.normalize();
  31546. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31547. this._camMatrix.invert();
  31548. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31549. var vDir = target.subtract(this.position);
  31550. if (vDir.x >= 0.0) {
  31551. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31552. }
  31553. else {
  31554. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31555. }
  31556. this.rotation.z = 0;
  31557. if (isNaN(this.rotation.x)) {
  31558. this.rotation.x = 0;
  31559. }
  31560. if (isNaN(this.rotation.y)) {
  31561. this.rotation.y = 0;
  31562. }
  31563. if (isNaN(this.rotation.z)) {
  31564. this.rotation.z = 0;
  31565. }
  31566. if (this.rotationQuaternion) {
  31567. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31568. }
  31569. };
  31570. /**
  31571. * Return the current target position of the camera. This value is expressed in local space.
  31572. */
  31573. TargetCamera.prototype.getTarget = function () {
  31574. return this._currentTarget;
  31575. };
  31576. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31577. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31578. };
  31579. TargetCamera.prototype._updatePosition = function () {
  31580. if (this.parent) {
  31581. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31582. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31583. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31584. return;
  31585. }
  31586. this.position.addInPlace(this.cameraDirection);
  31587. };
  31588. TargetCamera.prototype._checkInputs = function () {
  31589. var needToMove = this._decideIfNeedsToMove();
  31590. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31591. // Move
  31592. if (needToMove) {
  31593. this._updatePosition();
  31594. }
  31595. // Rotate
  31596. if (needToRotate) {
  31597. this.rotation.x += this.cameraRotation.x;
  31598. this.rotation.y += this.cameraRotation.y;
  31599. //rotate, if quaternion is set and rotation was used
  31600. if (this.rotationQuaternion) {
  31601. var len = this.rotation.lengthSquared();
  31602. if (len) {
  31603. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31604. }
  31605. }
  31606. if (!this.noRotationConstraint) {
  31607. var limit = (Math.PI / 2) * 0.95;
  31608. if (this.rotation.x > limit)
  31609. this.rotation.x = limit;
  31610. if (this.rotation.x < -limit)
  31611. this.rotation.x = -limit;
  31612. }
  31613. }
  31614. // Inertia
  31615. if (needToMove) {
  31616. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31617. this.cameraDirection.x = 0;
  31618. }
  31619. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31620. this.cameraDirection.y = 0;
  31621. }
  31622. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31623. this.cameraDirection.z = 0;
  31624. }
  31625. this.cameraDirection.scaleInPlace(this.inertia);
  31626. }
  31627. if (needToRotate) {
  31628. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31629. this.cameraRotation.x = 0;
  31630. }
  31631. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31632. this.cameraRotation.y = 0;
  31633. }
  31634. this.cameraRotation.scaleInPlace(this.inertia);
  31635. }
  31636. _super.prototype._checkInputs.call(this);
  31637. };
  31638. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31639. if (this.rotationQuaternion) {
  31640. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31641. //update the up vector!
  31642. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31643. }
  31644. else {
  31645. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31646. }
  31647. };
  31648. TargetCamera.prototype._getViewMatrix = function () {
  31649. if (!this.lockedTarget) {
  31650. // Compute
  31651. this._updateCameraRotationMatrix();
  31652. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31653. // Computing target and final matrix
  31654. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  31655. }
  31656. else {
  31657. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  31658. }
  31659. if (this.getScene().useRightHandedSystem) {
  31660. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31661. }
  31662. else {
  31663. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31664. }
  31665. return this._viewMatrix;
  31666. };
  31667. /**
  31668. * @override
  31669. * Override Camera.createRigCamera
  31670. */
  31671. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31672. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  31673. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  31674. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  31675. if (!this.rotationQuaternion) {
  31676. this.rotationQuaternion = new BABYLON.Quaternion();
  31677. }
  31678. rigCamera._cameraRigParams = {};
  31679. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  31680. }
  31681. return rigCamera;
  31682. }
  31683. return null;
  31684. };
  31685. /**
  31686. * @override
  31687. * Override Camera._updateRigCameras
  31688. */
  31689. TargetCamera.prototype._updateRigCameras = function () {
  31690. var camLeft = this._rigCameras[0];
  31691. var camRight = this._rigCameras[1];
  31692. switch (this.cameraRigMode) {
  31693. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31694. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31695. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31696. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31697. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  31698. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  31699. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  31700. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  31701. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  31702. camLeft.setTarget(this.getTarget());
  31703. camRight.setTarget(this.getTarget());
  31704. break;
  31705. case BABYLON.Camera.RIG_MODE_VR:
  31706. if (camLeft.rotationQuaternion) {
  31707. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31708. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31709. }
  31710. else {
  31711. camLeft.rotation.copyFrom(this.rotation);
  31712. camRight.rotation.copyFrom(this.rotation);
  31713. }
  31714. camLeft.position.copyFrom(this.position);
  31715. camRight.position.copyFrom(this.position);
  31716. break;
  31717. }
  31718. _super.prototype._updateRigCameras.call(this);
  31719. };
  31720. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  31721. if (!this._rigCamTransformMatrix) {
  31722. this._rigCamTransformMatrix = new BABYLON.Matrix();
  31723. }
  31724. var target = this.getTarget();
  31725. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  31726. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  31727. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  31728. };
  31729. TargetCamera.prototype.getClassName = function () {
  31730. return "TargetCamera";
  31731. };
  31732. __decorate([
  31733. BABYLON.serializeAsVector3()
  31734. ], TargetCamera.prototype, "rotation", void 0);
  31735. __decorate([
  31736. BABYLON.serialize()
  31737. ], TargetCamera.prototype, "speed", void 0);
  31738. __decorate([
  31739. BABYLON.serializeAsMeshReference("lockedTargetId")
  31740. ], TargetCamera.prototype, "lockedTarget", void 0);
  31741. return TargetCamera;
  31742. }(BABYLON.Camera));
  31743. BABYLON.TargetCamera = TargetCamera;
  31744. })(BABYLON || (BABYLON = {}));
  31745. //# sourceMappingURL=babylon.targetCamera.js.map
  31746. var BABYLON;
  31747. (function (BABYLON) {
  31748. var ArcRotateCameraKeyboardMoveInput = (function () {
  31749. function ArcRotateCameraKeyboardMoveInput() {
  31750. this._keys = [];
  31751. this.keysUp = [38];
  31752. this.keysDown = [40];
  31753. this.keysLeft = [37];
  31754. this.keysRight = [39];
  31755. this.keysReset = [111];
  31756. this.panningSensibility = 50.0;
  31757. }
  31758. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31759. var _this = this;
  31760. element.tabIndex = 1;
  31761. this._onKeyDown = function (evt) {
  31762. _this._ctrlPressed = evt.ctrlKey;
  31763. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31764. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31765. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31766. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  31767. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  31768. var index = _this._keys.indexOf(evt.keyCode);
  31769. if (index === -1) {
  31770. _this._keys.push(evt.keyCode);
  31771. }
  31772. if (evt.preventDefault) {
  31773. if (!noPreventDefault) {
  31774. evt.preventDefault();
  31775. }
  31776. }
  31777. }
  31778. };
  31779. this._onKeyUp = function (evt) {
  31780. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31781. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31782. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31783. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  31784. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  31785. var index = _this._keys.indexOf(evt.keyCode);
  31786. if (index >= 0) {
  31787. _this._keys.splice(index, 1);
  31788. }
  31789. if (evt.preventDefault) {
  31790. if (!noPreventDefault) {
  31791. evt.preventDefault();
  31792. }
  31793. }
  31794. }
  31795. };
  31796. this._onLostFocus = function () {
  31797. _this._keys = [];
  31798. };
  31799. this._onFocus = function () {
  31800. element.addEventListener("keydown", _this._onKeyDown, false);
  31801. element.addEventListener("keyup", _this._onKeyUp, false);
  31802. };
  31803. this._onBlur = function () {
  31804. element.removeEventListener("keydown", _this._onKeyDown);
  31805. element.removeEventListener("keyup", _this._onKeyUp);
  31806. };
  31807. element.addEventListener("focus", this._onFocus);
  31808. element.addEventListener("blur", this._onBlur);
  31809. BABYLON.Tools.RegisterTopRootEvents([
  31810. { name: "blur", handler: this._onLostFocus }
  31811. ]);
  31812. };
  31813. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31814. if (element && this._onBlur) {
  31815. this._onBlur();
  31816. element.removeEventListener("focus", this._onFocus);
  31817. element.removeEventListener("blur", this._onBlur);
  31818. }
  31819. BABYLON.Tools.UnregisterTopRootEvents([
  31820. { name: "blur", handler: this._onLostFocus }
  31821. ]);
  31822. this._keys = [];
  31823. this._onKeyDown = null;
  31824. this._onKeyUp = null;
  31825. this._onLostFocus = null;
  31826. this._onBlur = null;
  31827. this._onFocus = null;
  31828. };
  31829. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31830. if (this._onKeyDown) {
  31831. var camera = this.camera;
  31832. for (var index = 0; index < this._keys.length; index++) {
  31833. var keyCode = this._keys[index];
  31834. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31835. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31836. camera.inertialPanningX -= 1 / this.panningSensibility;
  31837. }
  31838. else {
  31839. camera.inertialAlphaOffset -= 0.01;
  31840. }
  31841. }
  31842. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31843. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31844. camera.inertialPanningY += 1 / this.panningSensibility;
  31845. }
  31846. else {
  31847. camera.inertialBetaOffset -= 0.01;
  31848. }
  31849. }
  31850. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31851. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31852. camera.inertialPanningX += 1 / this.panningSensibility;
  31853. }
  31854. else {
  31855. camera.inertialAlphaOffset += 0.01;
  31856. }
  31857. }
  31858. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31859. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31860. camera.inertialPanningY -= 1 / this.panningSensibility;
  31861. }
  31862. else {
  31863. camera.inertialBetaOffset += 0.01;
  31864. }
  31865. }
  31866. else if (this.keysReset.indexOf(keyCode) !== -1) {
  31867. camera.restoreState();
  31868. }
  31869. }
  31870. }
  31871. };
  31872. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  31873. return "ArcRotateCameraKeyboardMoveInput";
  31874. };
  31875. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31876. return "keyboard";
  31877. };
  31878. __decorate([
  31879. BABYLON.serialize()
  31880. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  31881. __decorate([
  31882. BABYLON.serialize()
  31883. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  31884. __decorate([
  31885. BABYLON.serialize()
  31886. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  31887. __decorate([
  31888. BABYLON.serialize()
  31889. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  31890. __decorate([
  31891. BABYLON.serialize()
  31892. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  31893. __decorate([
  31894. BABYLON.serialize()
  31895. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  31896. return ArcRotateCameraKeyboardMoveInput;
  31897. }());
  31898. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  31899. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  31900. })(BABYLON || (BABYLON = {}));
  31901. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  31902. var BABYLON;
  31903. (function (BABYLON) {
  31904. var ArcRotateCameraMouseWheelInput = (function () {
  31905. function ArcRotateCameraMouseWheelInput() {
  31906. this.wheelPrecision = 3.0;
  31907. }
  31908. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  31909. var _this = this;
  31910. this._wheel = function (p, s) {
  31911. //sanity check - this should be a PointerWheel event.
  31912. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  31913. return;
  31914. var event = p.event;
  31915. var delta = 0;
  31916. if (event.wheelDelta) {
  31917. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  31918. }
  31919. else if (event.detail) {
  31920. delta = -event.detail / _this.wheelPrecision;
  31921. }
  31922. if (delta)
  31923. _this.camera.inertialRadiusOffset += delta;
  31924. if (event.preventDefault) {
  31925. if (!noPreventDefault) {
  31926. event.preventDefault();
  31927. }
  31928. }
  31929. };
  31930. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  31931. };
  31932. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  31933. if (this._observer && element) {
  31934. this.camera.getScene().onPointerObservable.remove(this._observer);
  31935. this._observer = null;
  31936. this._wheel = null;
  31937. }
  31938. };
  31939. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  31940. return "ArcRotateCameraMouseWheelInput";
  31941. };
  31942. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  31943. return "mousewheel";
  31944. };
  31945. __decorate([
  31946. BABYLON.serialize()
  31947. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  31948. return ArcRotateCameraMouseWheelInput;
  31949. }());
  31950. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  31951. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  31952. })(BABYLON || (BABYLON = {}));
  31953. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  31954. var BABYLON;
  31955. (function (BABYLON) {
  31956. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  31957. var ArcRotateCameraPointersInput = (function () {
  31958. function ArcRotateCameraPointersInput() {
  31959. this.buttons = [0, 1, 2];
  31960. this.angularSensibilityX = 1000.0;
  31961. this.angularSensibilityY = 1000.0;
  31962. this.pinchPrecision = 6.0;
  31963. this.panningSensibility = 50.0;
  31964. this._isPanClick = false;
  31965. this.pinchInwards = true;
  31966. }
  31967. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  31968. var _this = this;
  31969. var engine = this.camera.getEngine();
  31970. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  31971. var pointA, pointB;
  31972. var previousPinchDistance = 0;
  31973. this._pointerInput = function (p, s) {
  31974. var evt = p.event;
  31975. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31976. return;
  31977. }
  31978. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31979. try {
  31980. evt.srcElement.setPointerCapture(evt.pointerId);
  31981. }
  31982. catch (e) {
  31983. //Nothing to do with the error. Execution will continue.
  31984. }
  31985. // Manage panning with pan button click
  31986. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  31987. // manage pointers
  31988. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  31989. if (pointA === undefined) {
  31990. pointA = cacheSoloPointer;
  31991. }
  31992. else if (pointB === undefined) {
  31993. pointB = cacheSoloPointer;
  31994. }
  31995. if (!noPreventDefault) {
  31996. evt.preventDefault();
  31997. element.focus();
  31998. }
  31999. }
  32000. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  32001. _this.camera.restoreState();
  32002. }
  32003. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  32004. try {
  32005. evt.srcElement.releasePointerCapture(evt.pointerId);
  32006. }
  32007. catch (e) {
  32008. //Nothing to do with the error.
  32009. }
  32010. cacheSoloPointer = null;
  32011. previousPinchDistance = 0;
  32012. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  32013. //but emptying completly pointers collection is required to fix a bug on iPhone :
  32014. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  32015. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  32016. pointA = pointB = undefined;
  32017. if (!noPreventDefault) {
  32018. evt.preventDefault();
  32019. }
  32020. }
  32021. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  32022. if (!noPreventDefault) {
  32023. evt.preventDefault();
  32024. }
  32025. // One button down
  32026. if (pointA && pointB === undefined) {
  32027. if (_this.panningSensibility !== 0 &&
  32028. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  32029. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  32030. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  32031. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  32032. }
  32033. else {
  32034. var offsetX = evt.clientX - cacheSoloPointer.x;
  32035. var offsetY = evt.clientY - cacheSoloPointer.y;
  32036. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32037. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32038. }
  32039. cacheSoloPointer.x = evt.clientX;
  32040. cacheSoloPointer.y = evt.clientY;
  32041. }
  32042. else if (pointA && pointB) {
  32043. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  32044. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  32045. ed.x = evt.clientX;
  32046. ed.y = evt.clientY;
  32047. var direction = _this.pinchInwards ? 1 : -1;
  32048. var distX = pointA.x - pointB.x;
  32049. var distY = pointA.y - pointB.y;
  32050. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  32051. if (previousPinchDistance === 0) {
  32052. previousPinchDistance = pinchSquaredDistance;
  32053. return;
  32054. }
  32055. if (pinchSquaredDistance !== previousPinchDistance) {
  32056. _this.camera
  32057. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  32058. (_this.pinchPrecision *
  32059. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  32060. direction);
  32061. previousPinchDistance = pinchSquaredDistance;
  32062. }
  32063. }
  32064. }
  32065. };
  32066. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  32067. this._onContextMenu = function (evt) {
  32068. evt.preventDefault();
  32069. };
  32070. if (!this.camera._useCtrlForPanning) {
  32071. element.addEventListener("contextmenu", this._onContextMenu, false);
  32072. }
  32073. this._onLostFocus = function () {
  32074. //this._keys = [];
  32075. pointA = pointB = undefined;
  32076. previousPinchDistance = 0;
  32077. cacheSoloPointer = null;
  32078. };
  32079. this._onMouseMove = function (evt) {
  32080. if (!engine.isPointerLock) {
  32081. return;
  32082. }
  32083. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  32084. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  32085. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32086. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32087. if (!noPreventDefault) {
  32088. evt.preventDefault();
  32089. }
  32090. };
  32091. this._onGestureStart = function (e) {
  32092. if (window.MSGesture === undefined) {
  32093. return;
  32094. }
  32095. if (!_this._MSGestureHandler) {
  32096. _this._MSGestureHandler = new MSGesture();
  32097. _this._MSGestureHandler.target = element;
  32098. }
  32099. _this._MSGestureHandler.addPointer(e.pointerId);
  32100. };
  32101. this._onGesture = function (e) {
  32102. _this.camera.radius *= e.scale;
  32103. if (e.preventDefault) {
  32104. if (!noPreventDefault) {
  32105. e.stopPropagation();
  32106. e.preventDefault();
  32107. }
  32108. }
  32109. };
  32110. element.addEventListener("mousemove", this._onMouseMove, false);
  32111. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  32112. element.addEventListener("MSGestureChange", this._onGesture, false);
  32113. BABYLON.Tools.RegisterTopRootEvents([
  32114. { name: "blur", handler: this._onLostFocus }
  32115. ]);
  32116. };
  32117. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  32118. BABYLON.Tools.UnregisterTopRootEvents([
  32119. { name: "blur", handler: this._onLostFocus }
  32120. ]);
  32121. if (element && this._observer) {
  32122. this.camera.getScene().onPointerObservable.remove(this._observer);
  32123. this._observer = null;
  32124. element.removeEventListener("contextmenu", this._onContextMenu);
  32125. element.removeEventListener("mousemove", this._onMouseMove);
  32126. element.removeEventListener("MSPointerDown", this._onGestureStart);
  32127. element.removeEventListener("MSGestureChange", this._onGesture);
  32128. this._isPanClick = false;
  32129. this.pinchInwards = true;
  32130. this._onMouseMove = null;
  32131. this._onGestureStart = null;
  32132. this._onGesture = null;
  32133. this._MSGestureHandler = null;
  32134. this._onLostFocus = null;
  32135. this._onContextMenu = null;
  32136. }
  32137. };
  32138. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  32139. return "ArcRotateCameraPointersInput";
  32140. };
  32141. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  32142. return "pointers";
  32143. };
  32144. __decorate([
  32145. BABYLON.serialize()
  32146. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  32147. __decorate([
  32148. BABYLON.serialize()
  32149. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  32150. __decorate([
  32151. BABYLON.serialize()
  32152. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  32153. __decorate([
  32154. BABYLON.serialize()
  32155. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  32156. __decorate([
  32157. BABYLON.serialize()
  32158. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  32159. return ArcRotateCameraPointersInput;
  32160. }());
  32161. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  32162. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  32163. })(BABYLON || (BABYLON = {}));
  32164. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  32165. /// <reference path="babylon.targetCamera.ts" />
  32166. /// <reference path="..\Tools\babylon.tools.ts" />
  32167. var BABYLON;
  32168. (function (BABYLON) {
  32169. var ArcRotateCamera = (function (_super) {
  32170. __extends(ArcRotateCamera, _super);
  32171. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  32172. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  32173. _this.inertialAlphaOffset = 0;
  32174. _this.inertialBetaOffset = 0;
  32175. _this.inertialRadiusOffset = 0;
  32176. _this.lowerAlphaLimit = null;
  32177. _this.upperAlphaLimit = null;
  32178. _this.lowerBetaLimit = 0.01;
  32179. _this.upperBetaLimit = Math.PI;
  32180. _this.lowerRadiusLimit = null;
  32181. _this.upperRadiusLimit = null;
  32182. _this.inertialPanningX = 0;
  32183. _this.inertialPanningY = 0;
  32184. _this.panningInertia = 0.9;
  32185. //-- end properties for backward compatibility for inputs
  32186. _this.zoomOnFactor = 1;
  32187. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  32188. _this.allowUpsideDown = true;
  32189. _this._viewMatrix = new BABYLON.Matrix();
  32190. // Panning
  32191. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  32192. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  32193. _this.checkCollisions = false;
  32194. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  32195. _this._previousPosition = BABYLON.Vector3.Zero();
  32196. _this._collisionVelocity = BABYLON.Vector3.Zero();
  32197. _this._newPosition = BABYLON.Vector3.Zero();
  32198. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32199. if (collidedMesh === void 0) { collidedMesh = null; }
  32200. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  32201. newPosition.multiplyInPlace(_this._collider.radius);
  32202. }
  32203. if (!collidedMesh) {
  32204. _this._previousPosition.copyFrom(_this.position);
  32205. }
  32206. else {
  32207. _this.setPosition(newPosition);
  32208. if (_this.onCollide) {
  32209. _this.onCollide(collidedMesh);
  32210. }
  32211. }
  32212. // Recompute because of constraints
  32213. var cosa = Math.cos(_this.alpha);
  32214. var sina = Math.sin(_this.alpha);
  32215. var cosb = Math.cos(_this.beta);
  32216. var sinb = Math.sin(_this.beta);
  32217. if (sinb === 0) {
  32218. sinb = 0.0001;
  32219. }
  32220. var target = _this._getTargetPosition();
  32221. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  32222. _this.position.copyFrom(_this._newPosition);
  32223. var up = _this.upVector;
  32224. if (_this.allowUpsideDown && _this.beta < 0) {
  32225. up = up.clone();
  32226. up = up.negate();
  32227. }
  32228. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  32229. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  32230. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  32231. _this._collisionTriggered = false;
  32232. };
  32233. _this._target = BABYLON.Vector3.Zero();
  32234. if (target) {
  32235. _this.setTarget(target);
  32236. }
  32237. _this.alpha = alpha;
  32238. _this.beta = beta;
  32239. _this.radius = radius;
  32240. _this.getViewMatrix();
  32241. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  32242. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  32243. return _this;
  32244. }
  32245. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  32246. get: function () {
  32247. return this._target;
  32248. },
  32249. set: function (value) {
  32250. this.setTarget(value);
  32251. },
  32252. enumerable: true,
  32253. configurable: true
  32254. });
  32255. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  32256. //-- begin properties for backward compatibility for inputs
  32257. get: function () {
  32258. var pointers = this.inputs.attached["pointers"];
  32259. if (pointers)
  32260. return pointers.angularSensibilityX;
  32261. },
  32262. set: function (value) {
  32263. var pointers = this.inputs.attached["pointers"];
  32264. if (pointers) {
  32265. pointers.angularSensibilityX = value;
  32266. }
  32267. },
  32268. enumerable: true,
  32269. configurable: true
  32270. });
  32271. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  32272. get: function () {
  32273. var pointers = this.inputs.attached["pointers"];
  32274. if (pointers)
  32275. return pointers.angularSensibilityY;
  32276. },
  32277. set: function (value) {
  32278. var pointers = this.inputs.attached["pointers"];
  32279. if (pointers) {
  32280. pointers.angularSensibilityY = value;
  32281. }
  32282. },
  32283. enumerable: true,
  32284. configurable: true
  32285. });
  32286. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  32287. get: function () {
  32288. var pointers = this.inputs.attached["pointers"];
  32289. if (pointers)
  32290. return pointers.pinchPrecision;
  32291. },
  32292. set: function (value) {
  32293. var pointers = this.inputs.attached["pointers"];
  32294. if (pointers) {
  32295. pointers.pinchPrecision = value;
  32296. }
  32297. },
  32298. enumerable: true,
  32299. configurable: true
  32300. });
  32301. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  32302. get: function () {
  32303. var pointers = this.inputs.attached["pointers"];
  32304. if (pointers)
  32305. return pointers.panningSensibility;
  32306. },
  32307. set: function (value) {
  32308. var pointers = this.inputs.attached["pointers"];
  32309. if (pointers) {
  32310. pointers.panningSensibility = value;
  32311. }
  32312. },
  32313. enumerable: true,
  32314. configurable: true
  32315. });
  32316. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  32317. get: function () {
  32318. var keyboard = this.inputs.attached["keyboard"];
  32319. if (keyboard)
  32320. return keyboard.keysUp;
  32321. },
  32322. set: function (value) {
  32323. var keyboard = this.inputs.attached["keyboard"];
  32324. if (keyboard)
  32325. keyboard.keysUp = value;
  32326. },
  32327. enumerable: true,
  32328. configurable: true
  32329. });
  32330. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  32331. get: function () {
  32332. var keyboard = this.inputs.attached["keyboard"];
  32333. if (keyboard)
  32334. return keyboard.keysDown;
  32335. },
  32336. set: function (value) {
  32337. var keyboard = this.inputs.attached["keyboard"];
  32338. if (keyboard)
  32339. keyboard.keysDown = value;
  32340. },
  32341. enumerable: true,
  32342. configurable: true
  32343. });
  32344. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  32345. get: function () {
  32346. var keyboard = this.inputs.attached["keyboard"];
  32347. if (keyboard)
  32348. return keyboard.keysLeft;
  32349. },
  32350. set: function (value) {
  32351. var keyboard = this.inputs.attached["keyboard"];
  32352. if (keyboard)
  32353. keyboard.keysLeft = value;
  32354. },
  32355. enumerable: true,
  32356. configurable: true
  32357. });
  32358. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  32359. get: function () {
  32360. var keyboard = this.inputs.attached["keyboard"];
  32361. if (keyboard)
  32362. return keyboard.keysRight;
  32363. },
  32364. set: function (value) {
  32365. var keyboard = this.inputs.attached["keyboard"];
  32366. if (keyboard)
  32367. keyboard.keysRight = value;
  32368. },
  32369. enumerable: true,
  32370. configurable: true
  32371. });
  32372. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  32373. get: function () {
  32374. var mousewheel = this.inputs.attached["mousewheel"];
  32375. if (mousewheel)
  32376. return mousewheel.wheelPrecision;
  32377. },
  32378. set: function (value) {
  32379. var mousewheel = this.inputs.attached["mousewheel"];
  32380. if (mousewheel)
  32381. mousewheel.wheelPrecision = value;
  32382. },
  32383. enumerable: true,
  32384. configurable: true
  32385. });
  32386. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  32387. get: function () {
  32388. return this._bouncingBehavior;
  32389. },
  32390. enumerable: true,
  32391. configurable: true
  32392. });
  32393. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  32394. get: function () {
  32395. return this._bouncingBehavior != null;
  32396. },
  32397. set: function (value) {
  32398. if (value === this.useBouncingBehavior) {
  32399. return;
  32400. }
  32401. if (value) {
  32402. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  32403. this.addBehavior(this._bouncingBehavior);
  32404. }
  32405. else {
  32406. this.removeBehavior(this._bouncingBehavior);
  32407. this._bouncingBehavior = null;
  32408. }
  32409. },
  32410. enumerable: true,
  32411. configurable: true
  32412. });
  32413. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  32414. get: function () {
  32415. return this._framingBehavior;
  32416. },
  32417. enumerable: true,
  32418. configurable: true
  32419. });
  32420. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  32421. get: function () {
  32422. return this._framingBehavior != null;
  32423. },
  32424. set: function (value) {
  32425. if (value === this.useFramingBehavior) {
  32426. return;
  32427. }
  32428. if (value) {
  32429. this._framingBehavior = new BABYLON.FramingBehavior();
  32430. this.addBehavior(this._framingBehavior);
  32431. }
  32432. else {
  32433. this.removeBehavior(this._framingBehavior);
  32434. this._framingBehavior = null;
  32435. }
  32436. },
  32437. enumerable: true,
  32438. configurable: true
  32439. });
  32440. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  32441. get: function () {
  32442. return this._autoRotationBehavior;
  32443. },
  32444. enumerable: true,
  32445. configurable: true
  32446. });
  32447. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  32448. get: function () {
  32449. return this._autoRotationBehavior != null;
  32450. },
  32451. set: function (value) {
  32452. if (value === this.useAutoRotationBehavior) {
  32453. return;
  32454. }
  32455. if (value) {
  32456. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  32457. this.addBehavior(this._autoRotationBehavior);
  32458. }
  32459. else {
  32460. this.removeBehavior(this._autoRotationBehavior);
  32461. this._autoRotationBehavior = null;
  32462. }
  32463. },
  32464. enumerable: true,
  32465. configurable: true
  32466. });
  32467. // Cache
  32468. ArcRotateCamera.prototype._initCache = function () {
  32469. _super.prototype._initCache.call(this);
  32470. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32471. this._cache.alpha = undefined;
  32472. this._cache.beta = undefined;
  32473. this._cache.radius = undefined;
  32474. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  32475. };
  32476. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  32477. if (!ignoreParentClass) {
  32478. _super.prototype._updateCache.call(this);
  32479. }
  32480. this._cache._target.copyFrom(this._getTargetPosition());
  32481. this._cache.alpha = this.alpha;
  32482. this._cache.beta = this.beta;
  32483. this._cache.radius = this.radius;
  32484. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  32485. };
  32486. ArcRotateCamera.prototype._getTargetPosition = function () {
  32487. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  32488. var pos = this._targetHost.getAbsolutePosition();
  32489. if (this._targetBoundingCenter) {
  32490. pos.addToRef(this._targetBoundingCenter, this._target);
  32491. }
  32492. else {
  32493. this._target.copyFrom(pos);
  32494. }
  32495. }
  32496. var lockedTargetPosition = this._getLockedTargetPosition();
  32497. if (lockedTargetPosition) {
  32498. return lockedTargetPosition;
  32499. }
  32500. return this._target;
  32501. };
  32502. ArcRotateCamera.prototype.storeState = function () {
  32503. this._storedAlpha = this.alpha;
  32504. this._storedBeta = this.beta;
  32505. this._storedRadius = this.radius;
  32506. this._storedTarget = this._getTargetPosition().clone();
  32507. return _super.prototype.storeState.call(this);
  32508. };
  32509. /**
  32510. * Restored camera state. You must call storeState() first
  32511. */
  32512. ArcRotateCamera.prototype.restoreState = function () {
  32513. if (!_super.prototype.restoreState.call(this)) {
  32514. return false;
  32515. }
  32516. this.alpha = this._storedAlpha;
  32517. this.beta = this._storedBeta;
  32518. this.radius = this._storedRadius;
  32519. this.setTarget(this._storedTarget);
  32520. this.inertialAlphaOffset = 0;
  32521. this.inertialBetaOffset = 0;
  32522. this.inertialRadiusOffset = 0;
  32523. this.inertialPanningX = 0;
  32524. this.inertialPanningY = 0;
  32525. return true;
  32526. };
  32527. // Synchronized
  32528. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  32529. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  32530. return false;
  32531. return this._cache._target.equals(this._getTargetPosition())
  32532. && this._cache.alpha === this.alpha
  32533. && this._cache.beta === this.beta
  32534. && this._cache.radius === this.radius
  32535. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  32536. };
  32537. // Methods
  32538. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  32539. var _this = this;
  32540. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  32541. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  32542. this._useCtrlForPanning = useCtrlForPanning;
  32543. this._panningMouseButton = panningMouseButton;
  32544. this.inputs.attachElement(element, noPreventDefault);
  32545. this._reset = function () {
  32546. _this.inertialAlphaOffset = 0;
  32547. _this.inertialBetaOffset = 0;
  32548. _this.inertialRadiusOffset = 0;
  32549. _this.inertialPanningX = 0;
  32550. _this.inertialPanningY = 0;
  32551. };
  32552. };
  32553. ArcRotateCamera.prototype.detachControl = function (element) {
  32554. this.inputs.detachElement(element);
  32555. if (this._reset) {
  32556. this._reset();
  32557. }
  32558. };
  32559. ArcRotateCamera.prototype._checkInputs = function () {
  32560. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  32561. if (this._collisionTriggered) {
  32562. return;
  32563. }
  32564. this.inputs.checkInputs();
  32565. // Inertia
  32566. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  32567. if (this.getScene().useRightHandedSystem) {
  32568. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32569. }
  32570. else {
  32571. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32572. }
  32573. this.beta += this.inertialBetaOffset;
  32574. this.radius -= this.inertialRadiusOffset;
  32575. this.inertialAlphaOffset *= this.inertia;
  32576. this.inertialBetaOffset *= this.inertia;
  32577. this.inertialRadiusOffset *= this.inertia;
  32578. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  32579. this.inertialAlphaOffset = 0;
  32580. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  32581. this.inertialBetaOffset = 0;
  32582. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  32583. this.inertialRadiusOffset = 0;
  32584. }
  32585. // Panning inertia
  32586. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  32587. if (!this._localDirection) {
  32588. this._localDirection = BABYLON.Vector3.Zero();
  32589. this._transformedDirection = BABYLON.Vector3.Zero();
  32590. }
  32591. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  32592. this._localDirection.multiplyInPlace(this.panningAxis);
  32593. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  32594. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  32595. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  32596. if (!this.panningAxis.y) {
  32597. this._transformedDirection.y = 0;
  32598. }
  32599. if (!this._targetHost) {
  32600. this._target.addInPlace(this._transformedDirection);
  32601. }
  32602. this.inertialPanningX *= this.panningInertia;
  32603. this.inertialPanningY *= this.panningInertia;
  32604. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  32605. this.inertialPanningX = 0;
  32606. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  32607. this.inertialPanningY = 0;
  32608. }
  32609. // Limits
  32610. this._checkLimits();
  32611. _super.prototype._checkInputs.call(this);
  32612. };
  32613. ArcRotateCamera.prototype._checkLimits = function () {
  32614. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32615. if (this.allowUpsideDown && this.beta > Math.PI) {
  32616. this.beta = this.beta - (2 * Math.PI);
  32617. }
  32618. }
  32619. else {
  32620. if (this.beta < this.lowerBetaLimit) {
  32621. this.beta = this.lowerBetaLimit;
  32622. }
  32623. }
  32624. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  32625. if (this.allowUpsideDown && this.beta < -Math.PI) {
  32626. this.beta = this.beta + (2 * Math.PI);
  32627. }
  32628. }
  32629. else {
  32630. if (this.beta > this.upperBetaLimit) {
  32631. this.beta = this.upperBetaLimit;
  32632. }
  32633. }
  32634. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  32635. this.alpha = this.lowerAlphaLimit;
  32636. }
  32637. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  32638. this.alpha = this.upperAlphaLimit;
  32639. }
  32640. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  32641. this.radius = this.lowerRadiusLimit;
  32642. }
  32643. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  32644. this.radius = this.upperRadiusLimit;
  32645. }
  32646. };
  32647. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  32648. var radiusv3 = this.position.subtract(this._getTargetPosition());
  32649. this.radius = radiusv3.length();
  32650. if (this.radius === 0) {
  32651. this.radius = 0.0001; // Just to avoid division by zero
  32652. }
  32653. // Alpha
  32654. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  32655. if (radiusv3.z < 0) {
  32656. this.alpha = 2 * Math.PI - this.alpha;
  32657. }
  32658. // Beta
  32659. this.beta = Math.acos(radiusv3.y / this.radius);
  32660. this._checkLimits();
  32661. };
  32662. ArcRotateCamera.prototype.setPosition = function (position) {
  32663. if (this.position.equals(position)) {
  32664. return;
  32665. }
  32666. this.position.copyFrom(position);
  32667. this.rebuildAnglesAndRadius();
  32668. };
  32669. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  32670. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  32671. if (allowSamePosition === void 0) { allowSamePosition = false; }
  32672. if (target.getBoundingInfo) {
  32673. if (toBoundingCenter) {
  32674. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  32675. }
  32676. else {
  32677. this._targetBoundingCenter = null;
  32678. }
  32679. this._targetHost = target;
  32680. this._target = this._getTargetPosition();
  32681. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  32682. }
  32683. else {
  32684. var newTarget = target;
  32685. var currentTarget = this._getTargetPosition();
  32686. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  32687. return;
  32688. }
  32689. this._targetHost = null;
  32690. this._target = newTarget;
  32691. this._targetBoundingCenter = null;
  32692. this.onMeshTargetChangedObservable.notifyObservers(null);
  32693. }
  32694. this.rebuildAnglesAndRadius();
  32695. };
  32696. ArcRotateCamera.prototype._getViewMatrix = function () {
  32697. // Compute
  32698. var cosa = Math.cos(this.alpha);
  32699. var sina = Math.sin(this.alpha);
  32700. var cosb = Math.cos(this.beta);
  32701. var sinb = Math.sin(this.beta);
  32702. if (sinb === 0) {
  32703. sinb = 0.0001;
  32704. }
  32705. var target = this._getTargetPosition();
  32706. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  32707. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  32708. if (!this._collider) {
  32709. this._collider = new BABYLON.Collider();
  32710. }
  32711. this._collider.radius = this.collisionRadius;
  32712. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  32713. this._collisionTriggered = true;
  32714. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32715. }
  32716. else {
  32717. this.position.copyFrom(this._newPosition);
  32718. var up = this.upVector;
  32719. if (this.allowUpsideDown && sinb < 0) {
  32720. up = up.clone();
  32721. up = up.negate();
  32722. }
  32723. if (this.getScene().useRightHandedSystem) {
  32724. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  32725. }
  32726. else {
  32727. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  32728. }
  32729. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  32730. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  32731. }
  32732. this._currentTarget = target;
  32733. return this._viewMatrix;
  32734. };
  32735. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  32736. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32737. meshes = meshes || this.getScene().meshes;
  32738. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  32739. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  32740. this.radius = distance * this.zoomOnFactor;
  32741. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  32742. };
  32743. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  32744. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32745. var meshesOrMinMaxVector;
  32746. var distance;
  32747. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  32748. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  32749. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  32750. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  32751. }
  32752. else {
  32753. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  32754. distance = meshesOrMinMaxVectorAndDistance.distance;
  32755. }
  32756. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  32757. if (!doNotUpdateMaxZ) {
  32758. this.maxZ = distance * 2;
  32759. }
  32760. };
  32761. /**
  32762. * @override
  32763. * Override Camera.createRigCamera
  32764. */
  32765. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32766. var alphaShift;
  32767. switch (this.cameraRigMode) {
  32768. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32769. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32770. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32771. case BABYLON.Camera.RIG_MODE_VR:
  32772. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  32773. break;
  32774. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32775. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  32776. break;
  32777. }
  32778. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  32779. rigCam._cameraRigParams = {};
  32780. return rigCam;
  32781. };
  32782. /**
  32783. * @override
  32784. * Override Camera._updateRigCameras
  32785. */
  32786. ArcRotateCamera.prototype._updateRigCameras = function () {
  32787. var camLeft = this._rigCameras[0];
  32788. var camRight = this._rigCameras[1];
  32789. camLeft.beta = camRight.beta = this.beta;
  32790. camLeft.radius = camRight.radius = this.radius;
  32791. switch (this.cameraRigMode) {
  32792. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32793. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32794. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32795. case BABYLON.Camera.RIG_MODE_VR:
  32796. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32797. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32798. break;
  32799. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32800. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32801. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32802. break;
  32803. }
  32804. _super.prototype._updateRigCameras.call(this);
  32805. };
  32806. ArcRotateCamera.prototype.dispose = function () {
  32807. this.inputs.clear();
  32808. _super.prototype.dispose.call(this);
  32809. };
  32810. ArcRotateCamera.prototype.getClassName = function () {
  32811. return "ArcRotateCamera";
  32812. };
  32813. __decorate([
  32814. BABYLON.serialize()
  32815. ], ArcRotateCamera.prototype, "alpha", void 0);
  32816. __decorate([
  32817. BABYLON.serialize()
  32818. ], ArcRotateCamera.prototype, "beta", void 0);
  32819. __decorate([
  32820. BABYLON.serialize()
  32821. ], ArcRotateCamera.prototype, "radius", void 0);
  32822. __decorate([
  32823. BABYLON.serializeAsVector3("target")
  32824. ], ArcRotateCamera.prototype, "_target", void 0);
  32825. __decorate([
  32826. BABYLON.serialize()
  32827. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  32828. __decorate([
  32829. BABYLON.serialize()
  32830. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  32831. __decorate([
  32832. BABYLON.serialize()
  32833. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  32834. __decorate([
  32835. BABYLON.serialize()
  32836. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  32837. __decorate([
  32838. BABYLON.serialize()
  32839. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  32840. __decorate([
  32841. BABYLON.serialize()
  32842. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  32843. __decorate([
  32844. BABYLON.serialize()
  32845. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  32846. __decorate([
  32847. BABYLON.serialize()
  32848. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  32849. __decorate([
  32850. BABYLON.serialize()
  32851. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  32852. __decorate([
  32853. BABYLON.serialize()
  32854. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  32855. __decorate([
  32856. BABYLON.serialize()
  32857. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  32858. __decorate([
  32859. BABYLON.serialize()
  32860. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  32861. __decorate([
  32862. BABYLON.serialize()
  32863. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  32864. __decorate([
  32865. BABYLON.serialize()
  32866. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  32867. return ArcRotateCamera;
  32868. }(BABYLON.TargetCamera));
  32869. BABYLON.ArcRotateCamera = ArcRotateCamera;
  32870. })(BABYLON || (BABYLON = {}));
  32871. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  32872. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  32873. var BABYLON;
  32874. (function (BABYLON) {
  32875. var ArcRotateCameraInputsManager = (function (_super) {
  32876. __extends(ArcRotateCameraInputsManager, _super);
  32877. function ArcRotateCameraInputsManager(camera) {
  32878. return _super.call(this, camera) || this;
  32879. }
  32880. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  32881. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  32882. return this;
  32883. };
  32884. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  32885. this.add(new BABYLON.ArcRotateCameraPointersInput());
  32886. return this;
  32887. };
  32888. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  32889. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  32890. return this;
  32891. };
  32892. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  32893. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  32894. return this;
  32895. };
  32896. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  32897. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  32898. return this;
  32899. };
  32900. return ArcRotateCameraInputsManager;
  32901. }(BABYLON.CameraInputsManager));
  32902. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  32903. })(BABYLON || (BABYLON = {}));
  32904. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  32905. var BABYLON;
  32906. (function (BABYLON) {
  32907. var CubeTexture = (function (_super) {
  32908. __extends(CubeTexture, _super);
  32909. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  32910. if (onLoad === void 0) { onLoad = null; }
  32911. if (onError === void 0) { onError = null; }
  32912. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32913. if (prefiltered === void 0) { prefiltered = false; }
  32914. if (forcedExtension === void 0) { forcedExtension = null; }
  32915. var _this = _super.call(this, scene) || this;
  32916. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  32917. _this.name = rootUrl;
  32918. _this.url = rootUrl;
  32919. _this._noMipmap = noMipmap;
  32920. _this.hasAlpha = false;
  32921. _this._format = format;
  32922. _this._prefiltered = prefiltered;
  32923. _this.isCube = true;
  32924. _this._textureMatrix = BABYLON.Matrix.Identity();
  32925. if (prefiltered) {
  32926. _this.gammaSpace = false;
  32927. }
  32928. if (!rootUrl && !files) {
  32929. return _this;
  32930. }
  32931. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  32932. if (!files) {
  32933. if (!extensions) {
  32934. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  32935. }
  32936. files = [];
  32937. for (var index = 0; index < extensions.length; index++) {
  32938. files.push(rootUrl + extensions[index]);
  32939. }
  32940. _this._extensions = extensions;
  32941. }
  32942. _this._files = files;
  32943. if (!_this._texture) {
  32944. if (!scene.useDelayedTextureLoading) {
  32945. if (prefiltered) {
  32946. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  32947. }
  32948. else {
  32949. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  32950. }
  32951. }
  32952. else {
  32953. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32954. }
  32955. }
  32956. else if (onLoad) {
  32957. if (_this._texture.isReady) {
  32958. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  32959. }
  32960. else {
  32961. _this._texture.onLoadedObservable.add(onLoad);
  32962. }
  32963. }
  32964. return _this;
  32965. }
  32966. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  32967. return new CubeTexture("", scene, null, noMipmap, files);
  32968. };
  32969. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  32970. if (forcedExtension === void 0) { forcedExtension = null; }
  32971. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  32972. };
  32973. // Methods
  32974. CubeTexture.prototype.delayLoad = function () {
  32975. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32976. return;
  32977. }
  32978. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32979. this._texture = this._getFromCache(this.url, this._noMipmap);
  32980. if (!this._texture) {
  32981. if (this._prefiltered) {
  32982. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  32983. }
  32984. else {
  32985. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  32986. }
  32987. }
  32988. };
  32989. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  32990. return this._textureMatrix;
  32991. };
  32992. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  32993. this._textureMatrix = value;
  32994. };
  32995. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32996. var texture = BABYLON.SerializationHelper.Parse(function () {
  32997. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  32998. }, parsedTexture, scene);
  32999. // Animations
  33000. if (parsedTexture.animations) {
  33001. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  33002. var parsedAnimation = parsedTexture.animations[animationIndex];
  33003. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33004. }
  33005. }
  33006. return texture;
  33007. };
  33008. CubeTexture.prototype.clone = function () {
  33009. var _this = this;
  33010. return BABYLON.SerializationHelper.Clone(function () {
  33011. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  33012. }, this);
  33013. };
  33014. return CubeTexture;
  33015. }(BABYLON.BaseTexture));
  33016. BABYLON.CubeTexture = CubeTexture;
  33017. })(BABYLON || (BABYLON = {}));
  33018. //# sourceMappingURL=babylon.cubeTexture.js.map
  33019. var BABYLON;
  33020. (function (BABYLON) {
  33021. var RenderTargetTexture = (function (_super) {
  33022. __extends(RenderTargetTexture, _super);
  33023. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  33024. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  33025. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33026. if (isCube === void 0) { isCube = false; }
  33027. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33028. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  33029. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  33030. if (isMulti === void 0) { isMulti = false; }
  33031. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  33032. _this.isCube = isCube;
  33033. /**
  33034. * Use this list to define the list of mesh you want to render.
  33035. */
  33036. _this.renderList = new Array();
  33037. _this.renderParticles = true;
  33038. _this.renderSprites = false;
  33039. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  33040. _this.ignoreCameraViewport = false;
  33041. // Events
  33042. /**
  33043. * An event triggered when the texture is unbind.
  33044. * @type {BABYLON.Observable}
  33045. */
  33046. _this.onBeforeBindObservable = new BABYLON.Observable();
  33047. /**
  33048. * An event triggered when the texture is unbind.
  33049. * @type {BABYLON.Observable}
  33050. */
  33051. _this.onAfterUnbindObservable = new BABYLON.Observable();
  33052. /**
  33053. * An event triggered before rendering the texture
  33054. * @type {BABYLON.Observable}
  33055. */
  33056. _this.onBeforeRenderObservable = new BABYLON.Observable();
  33057. /**
  33058. * An event triggered after rendering the texture
  33059. * @type {BABYLON.Observable}
  33060. */
  33061. _this.onAfterRenderObservable = new BABYLON.Observable();
  33062. /**
  33063. * An event triggered after the texture clear
  33064. * @type {BABYLON.Observable}
  33065. */
  33066. _this.onClearObservable = new BABYLON.Observable();
  33067. _this._currentRefreshId = -1;
  33068. _this._refreshRate = 1;
  33069. _this._samples = 1;
  33070. scene = _this.getScene();
  33071. _this.name = name;
  33072. _this.isRenderTarget = true;
  33073. _this._size = size;
  33074. _this._generateMipMaps = generateMipMaps;
  33075. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  33076. // Rendering groups
  33077. _this._renderingManager = new BABYLON.RenderingManager(scene);
  33078. if (isMulti) {
  33079. return _this;
  33080. }
  33081. _this._renderTargetOptions = {
  33082. generateMipMaps: generateMipMaps,
  33083. type: type,
  33084. samplingMode: samplingMode,
  33085. generateDepthBuffer: generateDepthBuffer,
  33086. generateStencilBuffer: generateStencilBuffer
  33087. };
  33088. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  33089. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33090. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33091. }
  33092. if (isCube) {
  33093. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  33094. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  33095. _this._textureMatrix = BABYLON.Matrix.Identity();
  33096. }
  33097. else {
  33098. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  33099. }
  33100. return _this;
  33101. }
  33102. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  33103. get: function () {
  33104. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  33105. },
  33106. enumerable: true,
  33107. configurable: true
  33108. });
  33109. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  33110. get: function () {
  33111. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  33112. },
  33113. enumerable: true,
  33114. configurable: true
  33115. });
  33116. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  33117. get: function () {
  33118. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  33119. },
  33120. enumerable: true,
  33121. configurable: true
  33122. });
  33123. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  33124. set: function (callback) {
  33125. if (this._onAfterUnbindObserver) {
  33126. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  33127. }
  33128. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  33129. },
  33130. enumerable: true,
  33131. configurable: true
  33132. });
  33133. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  33134. set: function (callback) {
  33135. if (this._onBeforeRenderObserver) {
  33136. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  33137. }
  33138. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  33139. },
  33140. enumerable: true,
  33141. configurable: true
  33142. });
  33143. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  33144. set: function (callback) {
  33145. if (this._onAfterRenderObserver) {
  33146. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  33147. }
  33148. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  33149. },
  33150. enumerable: true,
  33151. configurable: true
  33152. });
  33153. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  33154. set: function (callback) {
  33155. if (this._onClearObserver) {
  33156. this.onClearObservable.remove(this._onClearObserver);
  33157. }
  33158. this._onClearObserver = this.onClearObservable.add(callback);
  33159. },
  33160. enumerable: true,
  33161. configurable: true
  33162. });
  33163. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  33164. get: function () {
  33165. return this._renderTargetOptions;
  33166. },
  33167. enumerable: true,
  33168. configurable: true
  33169. });
  33170. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  33171. get: function () {
  33172. return this._samples;
  33173. },
  33174. set: function (value) {
  33175. if (this._samples === value) {
  33176. return;
  33177. }
  33178. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  33179. },
  33180. enumerable: true,
  33181. configurable: true
  33182. });
  33183. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  33184. this._currentRefreshId = -1;
  33185. };
  33186. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  33187. get: function () {
  33188. return this._refreshRate;
  33189. },
  33190. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  33191. set: function (value) {
  33192. this._refreshRate = value;
  33193. this.resetRefreshCounter();
  33194. },
  33195. enumerable: true,
  33196. configurable: true
  33197. });
  33198. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  33199. if (!this._postProcessManager) {
  33200. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  33201. this._postProcesses = new Array();
  33202. }
  33203. this._postProcesses.push(postProcess);
  33204. this._postProcesses[0].autoClear = false;
  33205. };
  33206. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  33207. if (!this._postProcesses) {
  33208. return;
  33209. }
  33210. if (dispose) {
  33211. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  33212. var postProcess = _a[_i];
  33213. postProcess.dispose();
  33214. postProcess = null;
  33215. }
  33216. }
  33217. this._postProcesses = [];
  33218. };
  33219. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  33220. if (!this._postProcesses) {
  33221. return;
  33222. }
  33223. var index = this._postProcesses.indexOf(postProcess);
  33224. if (index === -1) {
  33225. return;
  33226. }
  33227. this._postProcesses.splice(index, 1);
  33228. if (this._postProcesses.length > 0) {
  33229. this._postProcesses[0].autoClear = false;
  33230. }
  33231. };
  33232. RenderTargetTexture.prototype._shouldRender = function () {
  33233. if (this._currentRefreshId === -1) {
  33234. this._currentRefreshId = 1;
  33235. return true;
  33236. }
  33237. if (this.refreshRate === this._currentRefreshId) {
  33238. this._currentRefreshId = 1;
  33239. return true;
  33240. }
  33241. this._currentRefreshId++;
  33242. return false;
  33243. };
  33244. RenderTargetTexture.prototype.getRenderSize = function () {
  33245. return this._size;
  33246. };
  33247. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  33248. get: function () {
  33249. return true;
  33250. },
  33251. enumerable: true,
  33252. configurable: true
  33253. });
  33254. RenderTargetTexture.prototype.scale = function (ratio) {
  33255. var newSize = this._size * ratio;
  33256. this.resize(newSize);
  33257. };
  33258. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  33259. if (this.isCube) {
  33260. return this._textureMatrix;
  33261. }
  33262. return _super.prototype.getReflectionTextureMatrix.call(this);
  33263. };
  33264. RenderTargetTexture.prototype.resize = function (size) {
  33265. this.releaseInternalTexture();
  33266. if (this.isCube) {
  33267. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  33268. }
  33269. else {
  33270. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  33271. }
  33272. };
  33273. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  33274. var scene = this.getScene();
  33275. var engine = scene.getEngine();
  33276. if (this.useCameraPostProcesses !== undefined) {
  33277. useCameraPostProcess = this.useCameraPostProcesses;
  33278. }
  33279. if (this._waitingRenderList) {
  33280. this.renderList = [];
  33281. for (var index = 0; index < this._waitingRenderList.length; index++) {
  33282. var id = this._waitingRenderList[index];
  33283. this.renderList.push(scene.getMeshByID(id));
  33284. }
  33285. delete this._waitingRenderList;
  33286. }
  33287. // Is predicate defined?
  33288. if (this.renderListPredicate) {
  33289. this.renderList.splice(0); // Clear previous renderList
  33290. var sceneMeshes = this.getScene().meshes;
  33291. for (var index = 0; index < sceneMeshes.length; index++) {
  33292. var mesh = sceneMeshes[index];
  33293. if (this.renderListPredicate(mesh)) {
  33294. this.renderList.push(mesh);
  33295. }
  33296. }
  33297. }
  33298. if (this.renderList && this.renderList.length === 0) {
  33299. return;
  33300. }
  33301. this.onBeforeBindObservable.notifyObservers(this);
  33302. // Set custom projection.
  33303. // Needs to be before binding to prevent changing the aspect ratio.
  33304. var camera;
  33305. if (this.activeCamera) {
  33306. camera = this.activeCamera;
  33307. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  33308. if (this.activeCamera !== scene.activeCamera) {
  33309. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  33310. }
  33311. }
  33312. else {
  33313. camera = scene.activeCamera;
  33314. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  33315. }
  33316. // Prepare renderingManager
  33317. this._renderingManager.reset();
  33318. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  33319. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  33320. var sceneRenderId = scene.getRenderId();
  33321. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  33322. var mesh = currentRenderList[meshIndex];
  33323. if (mesh) {
  33324. if (!mesh.isReady()) {
  33325. // Reset _currentRefreshId
  33326. this.resetRefreshCounter();
  33327. continue;
  33328. }
  33329. mesh._preActivateForIntermediateRendering(sceneRenderId);
  33330. var isMasked = void 0;
  33331. if (!this.renderList) {
  33332. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  33333. }
  33334. else {
  33335. isMasked = false;
  33336. }
  33337. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  33338. mesh._activate(sceneRenderId);
  33339. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33340. var subMesh = mesh.subMeshes[subIndex];
  33341. scene._activeIndices.addCount(subMesh.indexCount, false);
  33342. this._renderingManager.dispatch(subMesh);
  33343. }
  33344. }
  33345. }
  33346. }
  33347. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  33348. var particleSystem = scene.particleSystems[particleIndex];
  33349. var emitter = particleSystem.emitter;
  33350. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  33351. continue;
  33352. }
  33353. if (currentRenderList.indexOf(emitter) >= 0) {
  33354. this._renderingManager.dispatchParticles(particleSystem);
  33355. }
  33356. }
  33357. if (this.isCube) {
  33358. for (var face = 0; face < 6; face++) {
  33359. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  33360. scene.incrementRenderId();
  33361. scene.resetCachedMaterial();
  33362. }
  33363. }
  33364. else {
  33365. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  33366. }
  33367. this.onAfterUnbindObservable.notifyObservers(this);
  33368. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  33369. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  33370. }
  33371. engine.setViewport(scene.activeCamera.viewport);
  33372. scene.resetCachedMaterial();
  33373. };
  33374. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  33375. var _this = this;
  33376. var scene = this.getScene();
  33377. var engine = scene.getEngine();
  33378. // Bind
  33379. if (this._postProcessManager) {
  33380. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  33381. }
  33382. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  33383. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  33384. }
  33385. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  33386. // Clear
  33387. if (this.onClearObservable.hasObservers()) {
  33388. this.onClearObservable.notifyObservers(engine);
  33389. }
  33390. else {
  33391. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  33392. }
  33393. if (!this._doNotChangeAspectRatio) {
  33394. scene.updateTransformMatrix(true);
  33395. }
  33396. // Render
  33397. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  33398. if (this._postProcessManager) {
  33399. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  33400. }
  33401. else if (useCameraPostProcess) {
  33402. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  33403. }
  33404. if (!this._doNotChangeAspectRatio) {
  33405. scene.updateTransformMatrix(true);
  33406. }
  33407. // Dump ?
  33408. if (dumpForDebug) {
  33409. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  33410. }
  33411. // Unbind
  33412. if (!this.isCube || faceIndex === 5) {
  33413. if (this.isCube) {
  33414. if (faceIndex === 5) {
  33415. engine.generateMipMapsForCubemap(this._texture);
  33416. }
  33417. }
  33418. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  33419. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  33420. });
  33421. }
  33422. else {
  33423. this.onAfterRenderObservable.notifyObservers(faceIndex);
  33424. }
  33425. };
  33426. /**
  33427. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  33428. * This allowed control for front to back rendering or reversly depending of the special needs.
  33429. *
  33430. * @param renderingGroupId The rendering group id corresponding to its index
  33431. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  33432. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  33433. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  33434. */
  33435. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  33436. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  33437. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  33438. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  33439. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  33440. };
  33441. /**
  33442. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  33443. *
  33444. * @param renderingGroupId The rendering group id corresponding to its index
  33445. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  33446. */
  33447. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  33448. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  33449. };
  33450. RenderTargetTexture.prototype.clone = function () {
  33451. var textureSize = this.getSize();
  33452. 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);
  33453. // Base texture
  33454. newTexture.hasAlpha = this.hasAlpha;
  33455. newTexture.level = this.level;
  33456. // RenderTarget Texture
  33457. newTexture.coordinatesMode = this.coordinatesMode;
  33458. newTexture.renderList = this.renderList.slice(0);
  33459. return newTexture;
  33460. };
  33461. RenderTargetTexture.prototype.serialize = function () {
  33462. if (!this.name) {
  33463. return null;
  33464. }
  33465. var serializationObject = _super.prototype.serialize.call(this);
  33466. serializationObject.renderTargetSize = this.getRenderSize();
  33467. serializationObject.renderList = [];
  33468. for (var index = 0; index < this.renderList.length; index++) {
  33469. serializationObject.renderList.push(this.renderList[index].id);
  33470. }
  33471. return serializationObject;
  33472. };
  33473. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  33474. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  33475. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  33476. };
  33477. RenderTargetTexture.prototype.dispose = function () {
  33478. if (this._postProcessManager) {
  33479. this._postProcessManager.dispose();
  33480. this._postProcessManager = null;
  33481. }
  33482. this.clearPostProcesses(true);
  33483. this.renderList = null;
  33484. // Remove from custom render targets
  33485. var scene = this.getScene();
  33486. var index = scene.customRenderTargets.indexOf(this);
  33487. if (index >= 0) {
  33488. scene.customRenderTargets.splice(index, 1);
  33489. }
  33490. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  33491. var camera = _a[_i];
  33492. index = camera.customRenderTargets.indexOf(this);
  33493. if (index >= 0) {
  33494. camera.customRenderTargets.splice(index, 1);
  33495. }
  33496. }
  33497. _super.prototype.dispose.call(this);
  33498. };
  33499. RenderTargetTexture.prototype._rebuild = function () {
  33500. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  33501. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  33502. }
  33503. if (this._postProcessManager) {
  33504. this._postProcessManager._rebuild();
  33505. }
  33506. };
  33507. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  33508. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  33509. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  33510. return RenderTargetTexture;
  33511. }(BABYLON.Texture));
  33512. BABYLON.RenderTargetTexture = RenderTargetTexture;
  33513. })(BABYLON || (BABYLON = {}));
  33514. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  33515. var BABYLON;
  33516. (function (BABYLON) {
  33517. ;
  33518. var MultiRenderTarget = (function (_super) {
  33519. __extends(MultiRenderTarget, _super);
  33520. function MultiRenderTarget(name, size, count, scene, options) {
  33521. var _this = this;
  33522. options = options || {};
  33523. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  33524. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  33525. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  33526. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  33527. if (!_this.isSupported) {
  33528. _this.dispose();
  33529. return;
  33530. }
  33531. var types = [];
  33532. var samplingModes = [];
  33533. for (var i = 0; i < count; i++) {
  33534. if (options.types && options.types[i]) {
  33535. types.push(options.types[i]);
  33536. }
  33537. else {
  33538. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  33539. }
  33540. if (options.samplingModes && options.samplingModes[i]) {
  33541. samplingModes.push(options.samplingModes[i]);
  33542. }
  33543. else {
  33544. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33545. }
  33546. }
  33547. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  33548. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  33549. _this._count = count;
  33550. _this._size = size;
  33551. _this._multiRenderTargetOptions = {
  33552. samplingModes: samplingModes,
  33553. generateMipMaps: generateMipMaps,
  33554. generateDepthBuffer: generateDepthBuffer,
  33555. generateStencilBuffer: generateStencilBuffer,
  33556. generateDepthTexture: generateDepthTexture,
  33557. types: types,
  33558. textureCount: count
  33559. };
  33560. _this._createInternalTextures();
  33561. _this._createTextures();
  33562. return _this;
  33563. }
  33564. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  33565. get: function () {
  33566. var engine = this.getScene().getEngine();
  33567. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  33568. },
  33569. enumerable: true,
  33570. configurable: true
  33571. });
  33572. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  33573. get: function () {
  33574. return this._textures;
  33575. },
  33576. enumerable: true,
  33577. configurable: true
  33578. });
  33579. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  33580. get: function () {
  33581. return this._textures[this._textures.length - 1];
  33582. },
  33583. enumerable: true,
  33584. configurable: true
  33585. });
  33586. MultiRenderTarget.prototype._rebuild = function () {
  33587. this.releaseInternalTextures();
  33588. this._createInternalTextures();
  33589. for (var i = 0; i < this._internalTextures.length; i++) {
  33590. var texture = this._textures[i];
  33591. texture._texture = this._internalTextures[i];
  33592. }
  33593. // Keeps references to frame buffer and stencil/depth buffer
  33594. this._texture = this._internalTextures[0];
  33595. };
  33596. MultiRenderTarget.prototype._createInternalTextures = function () {
  33597. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  33598. };
  33599. MultiRenderTarget.prototype._createTextures = function () {
  33600. this._textures = [];
  33601. for (var i = 0; i < this._internalTextures.length; i++) {
  33602. var texture = new BABYLON.Texture(null, this.getScene());
  33603. texture._texture = this._internalTextures[i];
  33604. this._textures.push(texture);
  33605. }
  33606. // Keeps references to frame buffer and stencil/depth buffer
  33607. this._texture = this._internalTextures[0];
  33608. };
  33609. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  33610. get: function () {
  33611. return this._samples;
  33612. },
  33613. set: function (value) {
  33614. if (this._samples === value) {
  33615. return;
  33616. }
  33617. for (var i = 0; i < this._internalTextures.length; i++) {
  33618. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  33619. }
  33620. },
  33621. enumerable: true,
  33622. configurable: true
  33623. });
  33624. MultiRenderTarget.prototype.resize = function (size) {
  33625. this.releaseInternalTextures();
  33626. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  33627. this._createInternalTextures();
  33628. };
  33629. MultiRenderTarget.prototype.dispose = function () {
  33630. this.releaseInternalTextures();
  33631. _super.prototype.dispose.call(this);
  33632. };
  33633. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  33634. if (!this._internalTextures) {
  33635. return;
  33636. }
  33637. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  33638. if (this._internalTextures[i] !== undefined) {
  33639. this._internalTextures[i].dispose();
  33640. this._internalTextures.splice(i, 1);
  33641. }
  33642. }
  33643. };
  33644. return MultiRenderTarget;
  33645. }(BABYLON.RenderTargetTexture));
  33646. BABYLON.MultiRenderTarget = MultiRenderTarget;
  33647. })(BABYLON || (BABYLON = {}));
  33648. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  33649. /// <reference path="babylon.renderTargetTexture.ts" />
  33650. var BABYLON;
  33651. (function (BABYLON) {
  33652. var MirrorTexture = (function (_super) {
  33653. __extends(MirrorTexture, _super);
  33654. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  33655. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33656. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33657. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  33658. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  33659. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  33660. _this._transformMatrix = BABYLON.Matrix.Zero();
  33661. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  33662. _this._blurKernelX = 0;
  33663. _this._blurKernelY = 0;
  33664. _this._blurRatio = 1.0;
  33665. _this.onBeforeRenderObservable.add(function () {
  33666. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  33667. _this._savedViewMatrix = scene.getViewMatrix();
  33668. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  33669. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  33670. scene.clipPlane = _this.mirrorPlane;
  33671. scene.getEngine().cullBackFaces = false;
  33672. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  33673. });
  33674. _this.onAfterRenderObservable.add(function () {
  33675. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  33676. scene.getEngine().cullBackFaces = true;
  33677. scene._mirroredCameraPosition = null;
  33678. delete scene.clipPlane;
  33679. });
  33680. return _this;
  33681. }
  33682. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  33683. get: function () {
  33684. return this._blurRatio;
  33685. },
  33686. set: function (value) {
  33687. if (this._blurRatio === value) {
  33688. return;
  33689. }
  33690. this._blurRatio = value;
  33691. this._preparePostProcesses();
  33692. },
  33693. enumerable: true,
  33694. configurable: true
  33695. });
  33696. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  33697. set: function (value) {
  33698. this.blurKernelX = value;
  33699. this.blurKernelY = value;
  33700. },
  33701. enumerable: true,
  33702. configurable: true
  33703. });
  33704. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  33705. get: function () {
  33706. return this._blurKernelX;
  33707. },
  33708. set: function (value) {
  33709. if (this._blurKernelX === value) {
  33710. return;
  33711. }
  33712. this._blurKernelX = value;
  33713. this._preparePostProcesses();
  33714. },
  33715. enumerable: true,
  33716. configurable: true
  33717. });
  33718. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  33719. get: function () {
  33720. return this._blurKernelY;
  33721. },
  33722. set: function (value) {
  33723. if (this._blurKernelY === value) {
  33724. return;
  33725. }
  33726. this._blurKernelY = value;
  33727. this._preparePostProcesses();
  33728. },
  33729. enumerable: true,
  33730. configurable: true
  33731. });
  33732. MirrorTexture.prototype._preparePostProcesses = function () {
  33733. this.clearPostProcesses(true);
  33734. if (this._blurKernelX && this._blurKernelY) {
  33735. var engine = this.getScene().getEngine();
  33736. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33737. 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);
  33738. this._blurX.autoClear = false;
  33739. if (this._blurRatio === 1 && this.samples < 2) {
  33740. this._blurX.outputTexture = this._texture;
  33741. }
  33742. else {
  33743. this._blurX.alwaysForcePOT = true;
  33744. }
  33745. 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);
  33746. this._blurY.autoClear = false;
  33747. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  33748. this.addPostProcess(this._blurX);
  33749. this.addPostProcess(this._blurY);
  33750. }
  33751. };
  33752. MirrorTexture.prototype.clone = function () {
  33753. var textureSize = this.getSize();
  33754. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  33755. // Base texture
  33756. newTexture.hasAlpha = this.hasAlpha;
  33757. newTexture.level = this.level;
  33758. // Mirror Texture
  33759. newTexture.mirrorPlane = this.mirrorPlane.clone();
  33760. newTexture.renderList = this.renderList.slice(0);
  33761. return newTexture;
  33762. };
  33763. MirrorTexture.prototype.serialize = function () {
  33764. if (!this.name) {
  33765. return null;
  33766. }
  33767. var serializationObject = _super.prototype.serialize.call(this);
  33768. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  33769. return serializationObject;
  33770. };
  33771. return MirrorTexture;
  33772. }(BABYLON.RenderTargetTexture));
  33773. BABYLON.MirrorTexture = MirrorTexture;
  33774. })(BABYLON || (BABYLON = {}));
  33775. //# sourceMappingURL=babylon.mirrorTexture.js.map
  33776. /// <reference path="babylon.renderTargetTexture.ts" />
  33777. var BABYLON;
  33778. (function (BABYLON) {
  33779. /**
  33780. * Creates a refraction texture used by refraction channel of the standard material.
  33781. * @param name the texture name
  33782. * @param size size of the underlying texture
  33783. * @param scene root scene
  33784. */
  33785. var RefractionTexture = (function (_super) {
  33786. __extends(RefractionTexture, _super);
  33787. function RefractionTexture(name, size, scene, generateMipMaps) {
  33788. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  33789. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  33790. _this.depth = 2.0;
  33791. _this.onBeforeRenderObservable.add(function () {
  33792. scene.clipPlane = _this.refractionPlane;
  33793. });
  33794. _this.onAfterRenderObservable.add(function () {
  33795. delete scene.clipPlane;
  33796. });
  33797. return _this;
  33798. }
  33799. RefractionTexture.prototype.clone = function () {
  33800. var textureSize = this.getSize();
  33801. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  33802. // Base texture
  33803. newTexture.hasAlpha = this.hasAlpha;
  33804. newTexture.level = this.level;
  33805. // Refraction Texture
  33806. newTexture.refractionPlane = this.refractionPlane.clone();
  33807. newTexture.renderList = this.renderList.slice(0);
  33808. newTexture.depth = this.depth;
  33809. return newTexture;
  33810. };
  33811. RefractionTexture.prototype.serialize = function () {
  33812. if (!this.name) {
  33813. return null;
  33814. }
  33815. var serializationObject = _super.prototype.serialize.call(this);
  33816. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  33817. serializationObject.depth = this.depth;
  33818. return serializationObject;
  33819. };
  33820. return RefractionTexture;
  33821. }(BABYLON.RenderTargetTexture));
  33822. BABYLON.RefractionTexture = RefractionTexture;
  33823. })(BABYLON || (BABYLON = {}));
  33824. //# sourceMappingURL=babylon.refractionTexture.js.map
  33825. /// <reference path="babylon.texture.ts" />
  33826. var BABYLON;
  33827. (function (BABYLON) {
  33828. var DynamicTexture = (function (_super) {
  33829. __extends(DynamicTexture, _super);
  33830. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  33831. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33832. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  33833. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  33834. _this.name = name;
  33835. var engine = _this.getScene().getEngine();
  33836. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33837. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33838. _this._generateMipMaps = generateMipMaps;
  33839. if (options.getContext) {
  33840. _this._canvas = options;
  33841. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33842. }
  33843. else {
  33844. _this._canvas = document.createElement("canvas");
  33845. if (options.width) {
  33846. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33847. }
  33848. else {
  33849. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  33850. }
  33851. }
  33852. var textureSize = _this.getSize();
  33853. _this._canvas.width = textureSize.width;
  33854. _this._canvas.height = textureSize.height;
  33855. _this._context = _this._canvas.getContext("2d");
  33856. return _this;
  33857. }
  33858. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  33859. get: function () {
  33860. return true;
  33861. },
  33862. enumerable: true,
  33863. configurable: true
  33864. });
  33865. DynamicTexture.prototype._recreate = function (textureSize) {
  33866. this._canvas.width = textureSize.width;
  33867. this._canvas.height = textureSize.height;
  33868. this.releaseInternalTexture();
  33869. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  33870. };
  33871. DynamicTexture.prototype.scale = function (ratio) {
  33872. var textureSize = this.getSize();
  33873. textureSize.width *= ratio;
  33874. textureSize.height *= ratio;
  33875. this._recreate(textureSize);
  33876. };
  33877. DynamicTexture.prototype.scaleTo = function (width, height) {
  33878. var textureSize = this.getSize();
  33879. textureSize.width = width;
  33880. textureSize.height = height;
  33881. this._recreate(textureSize);
  33882. };
  33883. DynamicTexture.prototype.getContext = function () {
  33884. return this._context;
  33885. };
  33886. DynamicTexture.prototype.clear = function () {
  33887. var size = this.getSize();
  33888. this._context.fillRect(0, 0, size.width, size.height);
  33889. };
  33890. DynamicTexture.prototype.update = function (invertY) {
  33891. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  33892. };
  33893. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  33894. if (update === void 0) { update = true; }
  33895. var size = this.getSize();
  33896. if (clearColor) {
  33897. this._context.fillStyle = clearColor;
  33898. this._context.fillRect(0, 0, size.width, size.height);
  33899. }
  33900. this._context.font = font;
  33901. if (x === null || x === undefined) {
  33902. var textSize = this._context.measureText(text);
  33903. x = (size.width - textSize.width) / 2;
  33904. }
  33905. if (y === null || y === undefined) {
  33906. var fontSize = parseInt((font.replace(/\D/g, '')));
  33907. ;
  33908. y = (size.height / 2) + (fontSize / 3.65);
  33909. }
  33910. this._context.fillStyle = color;
  33911. this._context.fillText(text, x, y);
  33912. if (update) {
  33913. this.update(invertY);
  33914. }
  33915. };
  33916. DynamicTexture.prototype.clone = function () {
  33917. var textureSize = this.getSize();
  33918. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  33919. // Base texture
  33920. newTexture.hasAlpha = this.hasAlpha;
  33921. newTexture.level = this.level;
  33922. // Dynamic Texture
  33923. newTexture.wrapU = this.wrapU;
  33924. newTexture.wrapV = this.wrapV;
  33925. return newTexture;
  33926. };
  33927. DynamicTexture.prototype._rebuild = function () {
  33928. this.update();
  33929. };
  33930. return DynamicTexture;
  33931. }(BABYLON.Texture));
  33932. BABYLON.DynamicTexture = DynamicTexture;
  33933. })(BABYLON || (BABYLON = {}));
  33934. //# sourceMappingURL=babylon.dynamicTexture.js.map
  33935. var BABYLON;
  33936. (function (BABYLON) {
  33937. var VideoTexture = (function (_super) {
  33938. __extends(VideoTexture, _super);
  33939. /**
  33940. * Creates a video texture.
  33941. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  33942. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  33943. * @param {BABYLON.Scene} scene is obviously the current scene.
  33944. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  33945. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  33946. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  33947. */
  33948. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  33949. if (generateMipMaps === void 0) { generateMipMaps = false; }
  33950. if (invertY === void 0) { invertY = false; }
  33951. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33952. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33953. _this._autoLaunch = true;
  33954. var urls;
  33955. _this.name = name;
  33956. if (urlsOrVideo instanceof HTMLVideoElement) {
  33957. _this.video = urlsOrVideo;
  33958. }
  33959. else {
  33960. urls = urlsOrVideo;
  33961. _this.video = document.createElement("video");
  33962. _this.video.autoplay = false;
  33963. _this.video.loop = true;
  33964. }
  33965. _this._generateMipMaps = generateMipMaps;
  33966. _this._samplingMode = samplingMode;
  33967. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  33968. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33969. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33970. }
  33971. else {
  33972. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33973. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33974. _this._generateMipMaps = false;
  33975. }
  33976. if (urls) {
  33977. _this.video.addEventListener("canplay", function () {
  33978. _this._createTexture();
  33979. });
  33980. urls.forEach(function (url) {
  33981. var source = document.createElement("source");
  33982. source.src = url;
  33983. _this.video.appendChild(source);
  33984. });
  33985. }
  33986. else {
  33987. _this._createTexture();
  33988. }
  33989. _this._lastUpdate = BABYLON.Tools.Now;
  33990. return _this;
  33991. }
  33992. VideoTexture.prototype.__setTextureReady = function () {
  33993. this._texture.isReady = true;
  33994. };
  33995. VideoTexture.prototype._createTexture = function () {
  33996. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  33997. if (this._autoLaunch) {
  33998. this._autoLaunch = false;
  33999. this.video.play();
  34000. }
  34001. this._setTextureReady = this.__setTextureReady.bind(this);
  34002. this.video.addEventListener("playing", this._setTextureReady);
  34003. };
  34004. VideoTexture.prototype._rebuild = function () {
  34005. this.update();
  34006. };
  34007. VideoTexture.prototype.update = function () {
  34008. var now = BABYLON.Tools.Now;
  34009. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  34010. return false;
  34011. }
  34012. this._lastUpdate = now;
  34013. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  34014. return true;
  34015. };
  34016. VideoTexture.prototype.dispose = function () {
  34017. _super.prototype.dispose.call(this);
  34018. this.video.removeEventListener("playing", this._setTextureReady);
  34019. };
  34020. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  34021. var video = document.createElement("video");
  34022. var constraintsDeviceId;
  34023. if (constraints && constraints.deviceId) {
  34024. constraintsDeviceId = {
  34025. exact: constraints.deviceId
  34026. };
  34027. }
  34028. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  34029. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  34030. if (navigator.getUserMedia) {
  34031. navigator.getUserMedia({
  34032. video: {
  34033. deviceId: constraintsDeviceId,
  34034. width: {
  34035. min: (constraints && constraints.minWidth) || 256,
  34036. max: (constraints && constraints.maxWidth) || 640
  34037. },
  34038. height: {
  34039. min: (constraints && constraints.minHeight) || 256,
  34040. max: (constraints && constraints.maxHeight) || 480
  34041. }
  34042. }
  34043. }, function (stream) {
  34044. if (video.mozSrcObject !== undefined) {
  34045. video.mozSrcObject = stream;
  34046. }
  34047. else {
  34048. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  34049. }
  34050. video.play();
  34051. if (onReady) {
  34052. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  34053. }
  34054. }, function (e) {
  34055. BABYLON.Tools.Error(e.name);
  34056. });
  34057. }
  34058. };
  34059. return VideoTexture;
  34060. }(BABYLON.Texture));
  34061. BABYLON.VideoTexture = VideoTexture;
  34062. })(BABYLON || (BABYLON = {}));
  34063. //# sourceMappingURL=babylon.videoTexture.js.map
  34064. var BABYLON;
  34065. (function (BABYLON) {
  34066. var RawTexture = (function (_super) {
  34067. __extends(RawTexture, _super);
  34068. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  34069. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34070. if (invertY === void 0) { invertY = false; }
  34071. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34072. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  34073. _this.format = format;
  34074. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  34075. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34076. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34077. return _this;
  34078. }
  34079. RawTexture.prototype.update = function (data) {
  34080. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  34081. };
  34082. // Statics
  34083. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34084. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34085. if (invertY === void 0) { invertY = false; }
  34086. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34087. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  34088. };
  34089. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34090. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34091. if (invertY === void 0) { invertY = false; }
  34092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34093. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34094. };
  34095. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34096. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34097. if (invertY === void 0) { invertY = false; }
  34098. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34099. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34100. };
  34101. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34102. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34103. if (invertY === void 0) { invertY = false; }
  34104. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34105. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  34106. };
  34107. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34108. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34109. if (invertY === void 0) { invertY = false; }
  34110. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34111. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  34112. };
  34113. return RawTexture;
  34114. }(BABYLON.Texture));
  34115. BABYLON.RawTexture = RawTexture;
  34116. })(BABYLON || (BABYLON = {}));
  34117. //# sourceMappingURL=babylon.rawTexture.js.map
  34118. var BABYLON;
  34119. (function (BABYLON) {
  34120. var Internals;
  34121. (function (Internals) {
  34122. /*
  34123. * Based on jsTGALoader - Javascript loader for TGA file
  34124. * By Vincent Thibault
  34125. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  34126. */
  34127. var TGATools = (function () {
  34128. function TGATools() {
  34129. }
  34130. TGATools.GetTGAHeader = function (data) {
  34131. var offset = 0;
  34132. var header = {
  34133. id_length: data[offset++],
  34134. colormap_type: data[offset++],
  34135. image_type: data[offset++],
  34136. colormap_index: data[offset++] | data[offset++] << 8,
  34137. colormap_length: data[offset++] | data[offset++] << 8,
  34138. colormap_size: data[offset++],
  34139. origin: [
  34140. data[offset++] | data[offset++] << 8,
  34141. data[offset++] | data[offset++] << 8
  34142. ],
  34143. width: data[offset++] | data[offset++] << 8,
  34144. height: data[offset++] | data[offset++] << 8,
  34145. pixel_size: data[offset++],
  34146. flags: data[offset++]
  34147. };
  34148. return header;
  34149. };
  34150. TGATools.UploadContent = function (gl, data) {
  34151. // Not enough data to contain header ?
  34152. if (data.length < 19) {
  34153. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  34154. return;
  34155. }
  34156. // Read Header
  34157. var offset = 18;
  34158. var header = TGATools.GetTGAHeader(data);
  34159. // Assume it's a valid Targa file.
  34160. if (header.id_length + offset > data.length) {
  34161. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  34162. return;
  34163. }
  34164. // Skip not needed data
  34165. offset += header.id_length;
  34166. var use_rle = false;
  34167. var use_pal = false;
  34168. var use_rgb = false;
  34169. var use_grey = false;
  34170. // Get some informations.
  34171. switch (header.image_type) {
  34172. case TGATools._TYPE_RLE_INDEXED:
  34173. use_rle = true;
  34174. case TGATools._TYPE_INDEXED:
  34175. use_pal = true;
  34176. break;
  34177. case TGATools._TYPE_RLE_RGB:
  34178. use_rle = true;
  34179. case TGATools._TYPE_RGB:
  34180. use_rgb = true;
  34181. break;
  34182. case TGATools._TYPE_RLE_GREY:
  34183. use_rle = true;
  34184. case TGATools._TYPE_GREY:
  34185. use_grey = true;
  34186. break;
  34187. }
  34188. var pixel_data;
  34189. var numAlphaBits = header.flags & 0xf;
  34190. var pixel_size = header.pixel_size >> 3;
  34191. var pixel_total = header.width * header.height * pixel_size;
  34192. // Read palettes
  34193. var palettes;
  34194. if (use_pal) {
  34195. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  34196. }
  34197. // Read LRE
  34198. if (use_rle) {
  34199. pixel_data = new Uint8Array(pixel_total);
  34200. var c, count, i;
  34201. var localOffset = 0;
  34202. var pixels = new Uint8Array(pixel_size);
  34203. while (offset < pixel_total && localOffset < pixel_total) {
  34204. c = data[offset++];
  34205. count = (c & 0x7f) + 1;
  34206. // RLE pixels
  34207. if (c & 0x80) {
  34208. // Bind pixel tmp array
  34209. for (i = 0; i < pixel_size; ++i) {
  34210. pixels[i] = data[offset++];
  34211. }
  34212. // Copy pixel array
  34213. for (i = 0; i < count; ++i) {
  34214. pixel_data.set(pixels, localOffset + i * pixel_size);
  34215. }
  34216. localOffset += pixel_size * count;
  34217. }
  34218. else {
  34219. count *= pixel_size;
  34220. for (i = 0; i < count; ++i) {
  34221. pixel_data[localOffset + i] = data[offset++];
  34222. }
  34223. localOffset += count;
  34224. }
  34225. }
  34226. }
  34227. else {
  34228. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  34229. }
  34230. // Load to texture
  34231. var x_start, y_start, x_step, y_step, y_end, x_end;
  34232. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  34233. default:
  34234. case TGATools._ORIGIN_UL:
  34235. x_start = 0;
  34236. x_step = 1;
  34237. x_end = header.width;
  34238. y_start = 0;
  34239. y_step = 1;
  34240. y_end = header.height;
  34241. break;
  34242. case TGATools._ORIGIN_BL:
  34243. x_start = 0;
  34244. x_step = 1;
  34245. x_end = header.width;
  34246. y_start = header.height - 1;
  34247. y_step = -1;
  34248. y_end = -1;
  34249. break;
  34250. case TGATools._ORIGIN_UR:
  34251. x_start = header.width - 1;
  34252. x_step = -1;
  34253. x_end = -1;
  34254. y_start = 0;
  34255. y_step = 1;
  34256. y_end = header.height;
  34257. break;
  34258. case TGATools._ORIGIN_BR:
  34259. x_start = header.width - 1;
  34260. x_step = -1;
  34261. x_end = -1;
  34262. y_start = header.height - 1;
  34263. y_step = -1;
  34264. y_end = -1;
  34265. break;
  34266. }
  34267. // Load the specify method
  34268. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  34269. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  34270. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  34271. };
  34272. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34273. var image = pixel_data, colormap = palettes;
  34274. var width = header.width, height = header.height;
  34275. var color, i = 0, x, y;
  34276. var imageData = new Uint8Array(width * height * 4);
  34277. for (y = y_start; y !== y_end; y += y_step) {
  34278. for (x = x_start; x !== x_end; x += x_step, i++) {
  34279. color = image[i];
  34280. imageData[(x + width * y) * 4 + 3] = 255;
  34281. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  34282. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  34283. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  34284. }
  34285. }
  34286. return imageData;
  34287. };
  34288. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34289. var image = pixel_data;
  34290. var width = header.width, height = header.height;
  34291. var color, i = 0, x, y;
  34292. var imageData = new Uint8Array(width * height * 4);
  34293. for (y = y_start; y !== y_end; y += y_step) {
  34294. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  34295. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  34296. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  34297. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  34298. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  34299. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  34300. }
  34301. }
  34302. return imageData;
  34303. };
  34304. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34305. var image = pixel_data;
  34306. var width = header.width, height = header.height;
  34307. var i = 0, x, y;
  34308. var imageData = new Uint8Array(width * height * 4);
  34309. for (y = y_start; y !== y_end; y += y_step) {
  34310. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  34311. imageData[(x + width * y) * 4 + 3] = 255;
  34312. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34313. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  34314. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  34315. }
  34316. }
  34317. return imageData;
  34318. };
  34319. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34320. var image = pixel_data;
  34321. var width = header.width, height = header.height;
  34322. var i = 0, x, y;
  34323. var imageData = new Uint8Array(width * height * 4);
  34324. for (y = y_start; y !== y_end; y += y_step) {
  34325. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  34326. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34327. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  34328. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  34329. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  34330. }
  34331. }
  34332. return imageData;
  34333. };
  34334. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34335. var image = pixel_data;
  34336. var width = header.width, height = header.height;
  34337. var color, i = 0, x, y;
  34338. var imageData = new Uint8Array(width * height * 4);
  34339. for (y = y_start; y !== y_end; y += y_step) {
  34340. for (x = x_start; x !== x_end; x += x_step, i++) {
  34341. color = image[i];
  34342. imageData[(x + width * y) * 4 + 0] = color;
  34343. imageData[(x + width * y) * 4 + 1] = color;
  34344. imageData[(x + width * y) * 4 + 2] = color;
  34345. imageData[(x + width * y) * 4 + 3] = 255;
  34346. }
  34347. }
  34348. return imageData;
  34349. };
  34350. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34351. var image = pixel_data;
  34352. var width = header.width, height = header.height;
  34353. var i = 0, x, y;
  34354. var imageData = new Uint8Array(width * height * 4);
  34355. for (y = y_start; y !== y_end; y += y_step) {
  34356. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  34357. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  34358. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  34359. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34360. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  34361. }
  34362. }
  34363. return imageData;
  34364. };
  34365. TGATools._TYPE_NO_DATA = 0;
  34366. TGATools._TYPE_INDEXED = 1;
  34367. TGATools._TYPE_RGB = 2;
  34368. TGATools._TYPE_GREY = 3;
  34369. TGATools._TYPE_RLE_INDEXED = 9;
  34370. TGATools._TYPE_RLE_RGB = 10;
  34371. TGATools._TYPE_RLE_GREY = 11;
  34372. TGATools._ORIGIN_MASK = 0x30;
  34373. TGATools._ORIGIN_SHIFT = 0x04;
  34374. TGATools._ORIGIN_BL = 0x00;
  34375. TGATools._ORIGIN_BR = 0x01;
  34376. TGATools._ORIGIN_UL = 0x02;
  34377. TGATools._ORIGIN_UR = 0x03;
  34378. return TGATools;
  34379. }());
  34380. Internals.TGATools = TGATools;
  34381. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34382. })(BABYLON || (BABYLON = {}));
  34383. //# sourceMappingURL=babylon.tga.js.map
  34384. var BABYLON;
  34385. (function (BABYLON) {
  34386. var Internals;
  34387. (function (Internals) {
  34388. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  34389. // All values and structures referenced from:
  34390. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  34391. var DDS_MAGIC = 0x20534444;
  34392. 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;
  34393. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  34394. 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;
  34395. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  34396. function FourCCToInt32(value) {
  34397. return value.charCodeAt(0) +
  34398. (value.charCodeAt(1) << 8) +
  34399. (value.charCodeAt(2) << 16) +
  34400. (value.charCodeAt(3) << 24);
  34401. }
  34402. function Int32ToFourCC(value) {
  34403. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  34404. }
  34405. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  34406. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  34407. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  34408. var FOURCC_DX10 = FourCCToInt32("DX10");
  34409. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  34410. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  34411. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  34412. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  34413. var headerLengthInt = 31; // The header length in 32 bit ints
  34414. // Offsets into the header array
  34415. var off_magic = 0;
  34416. var off_size = 1;
  34417. var off_flags = 2;
  34418. var off_height = 3;
  34419. var off_width = 4;
  34420. var off_mipmapCount = 7;
  34421. var off_pfFlags = 20;
  34422. var off_pfFourCC = 21;
  34423. var off_RGBbpp = 22;
  34424. var off_RMask = 23;
  34425. var off_GMask = 24;
  34426. var off_BMask = 25;
  34427. var off_AMask = 26;
  34428. var off_caps1 = 27;
  34429. var off_caps2 = 28;
  34430. var off_caps3 = 29;
  34431. var off_caps4 = 30;
  34432. var off_dxgiFormat = 32;
  34433. ;
  34434. var DDSTools = (function () {
  34435. function DDSTools() {
  34436. }
  34437. DDSTools.GetDDSInfo = function (arrayBuffer) {
  34438. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  34439. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  34440. var mipmapCount = 1;
  34441. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  34442. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34443. }
  34444. var fourCC = header[off_pfFourCC];
  34445. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  34446. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34447. switch (fourCC) {
  34448. case FOURCC_D3DFMT_R16G16B16A16F:
  34449. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34450. break;
  34451. case FOURCC_D3DFMT_R32G32B32A32F:
  34452. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34453. break;
  34454. case FOURCC_DX10:
  34455. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  34456. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34457. break;
  34458. }
  34459. }
  34460. return {
  34461. width: header[off_width],
  34462. height: header[off_height],
  34463. mipmapCount: mipmapCount,
  34464. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  34465. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  34466. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  34467. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  34468. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  34469. dxgiFormat: dxgiFormat,
  34470. textureType: textureType
  34471. };
  34472. };
  34473. DDSTools._ToHalfFloat = function (value) {
  34474. if (!DDSTools._FloatView) {
  34475. DDSTools._FloatView = new Float32Array(1);
  34476. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  34477. }
  34478. DDSTools._FloatView[0] = value;
  34479. var x = DDSTools._Int32View[0];
  34480. var bits = (x >> 16) & 0x8000; /* Get the sign */
  34481. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  34482. var e = (x >> 23) & 0xff; /* Using int is faster here */
  34483. /* If zero, or denormal, or exponent underflows too much for a denormal
  34484. * half, return signed zero. */
  34485. if (e < 103) {
  34486. return bits;
  34487. }
  34488. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  34489. if (e > 142) {
  34490. bits |= 0x7c00;
  34491. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  34492. * not Inf, so make sure we set one mantissa bit too. */
  34493. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  34494. return bits;
  34495. }
  34496. /* If exponent underflows but not too much, return a denormal */
  34497. if (e < 113) {
  34498. m |= 0x0800;
  34499. /* Extra rounding may overflow and set mantissa to 0 and exponent
  34500. * to 1, which is OK. */
  34501. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  34502. return bits;
  34503. }
  34504. bits |= ((e - 112) << 10) | (m >> 1);
  34505. bits += m & 1;
  34506. return bits;
  34507. };
  34508. DDSTools._FromHalfFloat = function (value) {
  34509. var s = (value & 0x8000) >> 15;
  34510. var e = (value & 0x7C00) >> 10;
  34511. var f = value & 0x03FF;
  34512. if (e === 0) {
  34513. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  34514. }
  34515. else if (e == 0x1F) {
  34516. return f ? NaN : ((s ? -1 : 1) * Infinity);
  34517. }
  34518. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  34519. };
  34520. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34521. var destArray = new Float32Array(dataLength);
  34522. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34523. var index = 0;
  34524. for (var y = 0; y < height; y++) {
  34525. for (var x = 0; x < width; x++) {
  34526. var srcPos = (x + y * width) * 4;
  34527. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  34528. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  34529. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  34530. if (DDSTools.StoreLODInAlphaChannel) {
  34531. destArray[index + 3] = lod;
  34532. }
  34533. else {
  34534. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  34535. }
  34536. index += 4;
  34537. }
  34538. }
  34539. return destArray;
  34540. };
  34541. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34542. if (DDSTools.StoreLODInAlphaChannel) {
  34543. var destArray = new Uint16Array(dataLength);
  34544. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34545. var index = 0;
  34546. for (var y = 0; y < height; y++) {
  34547. for (var x = 0; x < width; x++) {
  34548. var srcPos = (x + y * width) * 4;
  34549. destArray[index] = srcData[srcPos];
  34550. destArray[index + 1] = srcData[srcPos + 1];
  34551. destArray[index + 2] = srcData[srcPos + 2];
  34552. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  34553. index += 4;
  34554. }
  34555. }
  34556. return destArray;
  34557. }
  34558. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  34559. };
  34560. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34561. if (DDSTools.StoreLODInAlphaChannel) {
  34562. var destArray = new Float32Array(dataLength);
  34563. var srcData = new Float32Array(arrayBuffer, dataOffset);
  34564. var index = 0;
  34565. for (var y = 0; y < height; y++) {
  34566. for (var x = 0; x < width; x++) {
  34567. var srcPos = (x + y * width) * 4;
  34568. destArray[index] = srcData[srcPos];
  34569. destArray[index + 1] = srcData[srcPos + 1];
  34570. destArray[index + 2] = srcData[srcPos + 2];
  34571. destArray[index + 3] = lod;
  34572. index += 4;
  34573. }
  34574. }
  34575. return destArray;
  34576. }
  34577. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  34578. };
  34579. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34580. var destArray = new Uint8Array(dataLength);
  34581. var srcData = new Float32Array(arrayBuffer, dataOffset);
  34582. var index = 0;
  34583. for (var y = 0; y < height; y++) {
  34584. for (var x = 0; x < width; x++) {
  34585. var srcPos = (x + y * width) * 4;
  34586. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  34587. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  34588. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  34589. if (DDSTools.StoreLODInAlphaChannel) {
  34590. destArray[index + 3] = lod;
  34591. }
  34592. else {
  34593. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  34594. }
  34595. index += 4;
  34596. }
  34597. }
  34598. return destArray;
  34599. };
  34600. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34601. var destArray = new Uint8Array(dataLength);
  34602. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34603. var index = 0;
  34604. for (var y = 0; y < height; y++) {
  34605. for (var x = 0; x < width; x++) {
  34606. var srcPos = (x + y * width) * 4;
  34607. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  34608. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  34609. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  34610. if (DDSTools.StoreLODInAlphaChannel) {
  34611. destArray[index + 3] = lod;
  34612. }
  34613. else {
  34614. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  34615. }
  34616. index += 4;
  34617. }
  34618. }
  34619. return destArray;
  34620. };
  34621. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34622. var byteArray = new Uint8Array(dataLength);
  34623. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34624. var index = 0;
  34625. for (var y = 0; y < height; y++) {
  34626. for (var x = 0; x < width; x++) {
  34627. var srcPos = (x + y * width) * 4;
  34628. byteArray[index] = srcData[srcPos + 2];
  34629. byteArray[index + 1] = srcData[srcPos + 1];
  34630. byteArray[index + 2] = srcData[srcPos];
  34631. byteArray[index + 3] = srcData[srcPos + 3];
  34632. index += 4;
  34633. }
  34634. }
  34635. return byteArray;
  34636. };
  34637. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34638. var byteArray = new Uint8Array(dataLength);
  34639. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34640. var index = 0;
  34641. for (var y = 0; y < height; y++) {
  34642. for (var x = 0; x < width; x++) {
  34643. var srcPos = (x + y * width) * 3;
  34644. byteArray[index] = srcData[srcPos + 2];
  34645. byteArray[index + 1] = srcData[srcPos + 1];
  34646. byteArray[index + 2] = srcData[srcPos];
  34647. index += 3;
  34648. }
  34649. }
  34650. return byteArray;
  34651. };
  34652. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34653. var byteArray = new Uint8Array(dataLength);
  34654. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34655. var index = 0;
  34656. for (var y = 0; y < height; y++) {
  34657. for (var x = 0; x < width; x++) {
  34658. var srcPos = (x + y * width);
  34659. byteArray[index] = srcData[srcPos];
  34660. index++;
  34661. }
  34662. }
  34663. return byteArray;
  34664. };
  34665. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  34666. if (lodIndex === void 0) { lodIndex = -1; }
  34667. var ext = engine.getCaps().s3tc;
  34668. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  34669. if (header[off_magic] != DDS_MAGIC) {
  34670. BABYLON.Tools.Error("Invalid magic number in DDS header");
  34671. return;
  34672. }
  34673. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  34674. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  34675. return;
  34676. }
  34677. if (info.isCompressed && !ext) {
  34678. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  34679. return;
  34680. }
  34681. var bpp = header[off_RGBbpp];
  34682. dataOffset = header[off_size] + 4;
  34683. var computeFormats = false;
  34684. if (info.isFourCC) {
  34685. fourCC = header[off_pfFourCC];
  34686. switch (fourCC) {
  34687. case FOURCC_DXT1:
  34688. blockBytes = 8;
  34689. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  34690. break;
  34691. case FOURCC_DXT3:
  34692. blockBytes = 16;
  34693. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  34694. break;
  34695. case FOURCC_DXT5:
  34696. blockBytes = 16;
  34697. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  34698. break;
  34699. case FOURCC_D3DFMT_R16G16B16A16F:
  34700. computeFormats = true;
  34701. break;
  34702. case FOURCC_D3DFMT_R32G32B32A32F:
  34703. computeFormats = true;
  34704. break;
  34705. case FOURCC_DX10:
  34706. // There is an additionnal header so dataOffset need to be changed
  34707. dataOffset += 5 * 4; // 5 uints
  34708. var supported = false;
  34709. switch (info.dxgiFormat) {
  34710. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  34711. computeFormats = true;
  34712. supported = true;
  34713. break;
  34714. case DXGI_FORMAT_B8G8R8X8_UNORM:
  34715. info.isRGB = true;
  34716. info.isFourCC = false;
  34717. bpp = 32;
  34718. supported = true;
  34719. break;
  34720. }
  34721. if (supported) {
  34722. break;
  34723. }
  34724. default:
  34725. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  34726. return;
  34727. }
  34728. }
  34729. if (computeFormats) {
  34730. format = engine._getWebGLTextureType(info.textureType);
  34731. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34732. }
  34733. mipmapCount = 1;
  34734. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  34735. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34736. }
  34737. for (var face = 0; face < faces; face++) {
  34738. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34739. width = header[off_width];
  34740. height = header[off_height];
  34741. for (mip = 0; mip < mipmapCount; ++mip) {
  34742. if (lodIndex === -1 || lodIndex === mip) {
  34743. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  34744. var i = (lodIndex === -1) ? mip : 0;
  34745. if (!info.isCompressed && info.isFourCC) {
  34746. dataLength = width * height * 4;
  34747. var floatArray;
  34748. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  34749. if (bpp === 128) {
  34750. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34751. }
  34752. else if (bpp === 64) {
  34753. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34754. }
  34755. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34756. format = engine._getWebGLTextureType(info.textureType);
  34757. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34758. }
  34759. else {
  34760. if (bpp === 128) {
  34761. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34762. }
  34763. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  34764. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34765. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34766. format = engine._getWebGLTextureType(info.textureType);
  34767. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34768. }
  34769. else {
  34770. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34771. }
  34772. }
  34773. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  34774. }
  34775. else if (info.isRGB) {
  34776. if (bpp === 24) {
  34777. dataLength = width * height * 3;
  34778. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34779. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  34780. }
  34781. else {
  34782. dataLength = width * height * 4;
  34783. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34784. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  34785. }
  34786. }
  34787. else if (info.isLuminance) {
  34788. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  34789. var unpaddedRowSize = width;
  34790. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  34791. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  34792. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34793. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  34794. }
  34795. else {
  34796. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  34797. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  34798. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  34799. }
  34800. }
  34801. dataOffset += width * height * (bpp / 8);
  34802. width *= 0.5;
  34803. height *= 0.5;
  34804. width = Math.max(1.0, width);
  34805. height = Math.max(1.0, height);
  34806. }
  34807. }
  34808. };
  34809. DDSTools.StoreLODInAlphaChannel = false;
  34810. return DDSTools;
  34811. }());
  34812. Internals.DDSTools = DDSTools;
  34813. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34814. })(BABYLON || (BABYLON = {}));
  34815. //# sourceMappingURL=babylon.dds.js.map
  34816. var BABYLON;
  34817. (function (BABYLON) {
  34818. var Internals;
  34819. (function (Internals) {
  34820. /**
  34821. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  34822. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  34823. */
  34824. var KhronosTextureContainer = (function () {
  34825. /**
  34826. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  34827. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  34828. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  34829. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  34830. */
  34831. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  34832. this.arrayBuffer = arrayBuffer;
  34833. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  34834. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  34835. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  34836. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  34837. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  34838. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  34839. BABYLON.Tools.Error("texture missing KTX identifier");
  34840. return;
  34841. }
  34842. // load the reset of the header in native 32 bit int
  34843. var header = new Int32Array(this.arrayBuffer, 12, 13);
  34844. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  34845. var oppositeEndianess = header[0] === 0x01020304;
  34846. // read all the header elements in order they exist in the file, without modification (sans endainness)
  34847. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  34848. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  34849. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  34850. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  34851. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  34852. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  34853. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  34854. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  34855. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  34856. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  34857. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  34858. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  34859. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  34860. if (this.glType !== 0) {
  34861. BABYLON.Tools.Error("only compressed formats currently supported");
  34862. return;
  34863. }
  34864. else {
  34865. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  34866. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  34867. }
  34868. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  34869. BABYLON.Tools.Error("only 2D textures currently supported");
  34870. return;
  34871. }
  34872. if (this.numberOfArrayElements !== 0) {
  34873. BABYLON.Tools.Error("texture arrays not currently supported");
  34874. return;
  34875. }
  34876. if (this.numberOfFaces !== facesExpected) {
  34877. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  34878. return;
  34879. }
  34880. // we now have a completely validated file, so could use existence of loadType as success
  34881. // would need to make this more elaborate & adjust checks above to support more than one load type
  34882. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  34883. }
  34884. // not as fast hardware based, but will probably never need to use
  34885. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  34886. return ((val & 0xFF) << 24)
  34887. | ((val & 0xFF00) << 8)
  34888. | ((val >> 8) & 0xFF00)
  34889. | ((val >> 24) & 0xFF);
  34890. };
  34891. /**
  34892. * It is assumed that the texture has already been created & is currently bound
  34893. */
  34894. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  34895. switch (this.loadType) {
  34896. case KhronosTextureContainer.COMPRESSED_2D:
  34897. this._upload2DCompressedLevels(gl, loadMipmaps);
  34898. break;
  34899. case KhronosTextureContainer.TEX_2D:
  34900. case KhronosTextureContainer.COMPRESSED_3D:
  34901. case KhronosTextureContainer.TEX_3D:
  34902. }
  34903. };
  34904. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  34905. // initialize width & height for level 1
  34906. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  34907. var width = this.pixelWidth;
  34908. var height = this.pixelHeight;
  34909. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  34910. for (var level = 0; level < mipmapCount; level++) {
  34911. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  34912. for (var face = 0; face < this.numberOfFaces; face++) {
  34913. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34914. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  34915. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  34916. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  34917. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  34918. }
  34919. width = Math.max(1.0, width * 0.5);
  34920. height = Math.max(1.0, height * 0.5);
  34921. }
  34922. };
  34923. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  34924. // load types
  34925. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  34926. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  34927. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  34928. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  34929. return KhronosTextureContainer;
  34930. }());
  34931. Internals.KhronosTextureContainer = KhronosTextureContainer;
  34932. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34933. })(BABYLON || (BABYLON = {}));
  34934. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  34935. var BABYLON;
  34936. (function (BABYLON) {
  34937. var PostProcess = (function () {
  34938. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  34939. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  34940. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34941. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  34942. if (blockCompilation === void 0) { blockCompilation = false; }
  34943. this.name = name;
  34944. this.width = -1;
  34945. this.height = -1;
  34946. this.autoClear = true;
  34947. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  34948. /*
  34949. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  34950. Can only be used on a single postprocess or on the last one of a chain.
  34951. */
  34952. this.enablePixelPerfectMode = false;
  34953. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  34954. this.alwaysForcePOT = false;
  34955. this.samples = 1;
  34956. this._reusable = false;
  34957. this._textures = new BABYLON.SmartArray(2);
  34958. this._currentRenderTextureInd = 0;
  34959. this._scaleRatio = new BABYLON.Vector2(1, 1);
  34960. this._texelSize = BABYLON.Vector2.Zero();
  34961. // Events
  34962. /**
  34963. * An event triggered when the postprocess is activated.
  34964. * @type {BABYLON.Observable}
  34965. */
  34966. this.onActivateObservable = new BABYLON.Observable();
  34967. /**
  34968. * An event triggered when the postprocess changes its size.
  34969. * @type {BABYLON.Observable}
  34970. */
  34971. this.onSizeChangedObservable = new BABYLON.Observable();
  34972. /**
  34973. * An event triggered when the postprocess applies its effect.
  34974. * @type {BABYLON.Observable}
  34975. */
  34976. this.onApplyObservable = new BABYLON.Observable();
  34977. /**
  34978. * An event triggered before rendering the postprocess
  34979. * @type {BABYLON.Observable}
  34980. */
  34981. this.onBeforeRenderObservable = new BABYLON.Observable();
  34982. /**
  34983. * An event triggered after rendering the postprocess
  34984. * @type {BABYLON.Observable}
  34985. */
  34986. this.onAfterRenderObservable = new BABYLON.Observable();
  34987. if (camera != null) {
  34988. this._camera = camera;
  34989. this._scene = camera.getScene();
  34990. camera.attachPostProcess(this);
  34991. this._engine = this._scene.getEngine();
  34992. this._scene.postProcesses.push(this);
  34993. }
  34994. else {
  34995. this._engine = engine;
  34996. this._engine.postProcesses.push(this);
  34997. }
  34998. this._options = options;
  34999. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  35000. this._reusable = reusable || false;
  35001. this._textureType = textureType;
  35002. this._samplers = samplers || [];
  35003. this._samplers.push("textureSampler");
  35004. this._fragmentUrl = fragmentUrl;
  35005. this._vertexUrl = vertexUrl;
  35006. this._parameters = parameters || [];
  35007. this._parameters.push("scale");
  35008. this._indexParameters = indexParameters;
  35009. if (!blockCompilation) {
  35010. this.updateEffect(defines);
  35011. }
  35012. }
  35013. Object.defineProperty(PostProcess.prototype, "onActivate", {
  35014. set: function (callback) {
  35015. if (this._onActivateObserver) {
  35016. this.onActivateObservable.remove(this._onActivateObserver);
  35017. }
  35018. this._onActivateObserver = this.onActivateObservable.add(callback);
  35019. },
  35020. enumerable: true,
  35021. configurable: true
  35022. });
  35023. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  35024. set: function (callback) {
  35025. if (this._onSizeChangedObserver) {
  35026. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  35027. }
  35028. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  35029. },
  35030. enumerable: true,
  35031. configurable: true
  35032. });
  35033. Object.defineProperty(PostProcess.prototype, "onApply", {
  35034. set: function (callback) {
  35035. if (this._onApplyObserver) {
  35036. this.onApplyObservable.remove(this._onApplyObserver);
  35037. }
  35038. this._onApplyObserver = this.onApplyObservable.add(callback);
  35039. },
  35040. enumerable: true,
  35041. configurable: true
  35042. });
  35043. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  35044. set: function (callback) {
  35045. if (this._onBeforeRenderObserver) {
  35046. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  35047. }
  35048. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  35049. },
  35050. enumerable: true,
  35051. configurable: true
  35052. });
  35053. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  35054. set: function (callback) {
  35055. if (this._onAfterRenderObserver) {
  35056. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  35057. }
  35058. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  35059. },
  35060. enumerable: true,
  35061. configurable: true
  35062. });
  35063. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  35064. get: function () {
  35065. return this._textures.data[this._currentRenderTextureInd];
  35066. },
  35067. set: function (value) {
  35068. this._forcedOutputTexture = value;
  35069. },
  35070. enumerable: true,
  35071. configurable: true
  35072. });
  35073. PostProcess.prototype.getCamera = function () {
  35074. return this._camera;
  35075. };
  35076. Object.defineProperty(PostProcess.prototype, "texelSize", {
  35077. get: function () {
  35078. if (this._shareOutputWithPostProcess) {
  35079. return this._shareOutputWithPostProcess.texelSize;
  35080. }
  35081. if (this._forcedOutputTexture) {
  35082. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  35083. }
  35084. return this._texelSize;
  35085. },
  35086. enumerable: true,
  35087. configurable: true
  35088. });
  35089. PostProcess.prototype.getEngine = function () {
  35090. return this._engine;
  35091. };
  35092. PostProcess.prototype.getEffect = function () {
  35093. return this._effect;
  35094. };
  35095. PostProcess.prototype.shareOutputWith = function (postProcess) {
  35096. this._disposeTextures();
  35097. this._shareOutputWithPostProcess = postProcess;
  35098. return this;
  35099. };
  35100. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  35101. 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);
  35102. };
  35103. PostProcess.prototype.isReusable = function () {
  35104. return this._reusable;
  35105. };
  35106. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  35107. PostProcess.prototype.markTextureDirty = function () {
  35108. this.width = -1;
  35109. };
  35110. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  35111. var _this = this;
  35112. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  35113. camera = camera || this._camera;
  35114. var scene = camera.getScene();
  35115. var engine = scene.getEngine();
  35116. var maxSize = engine.getCaps().maxTextureSize;
  35117. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  35118. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  35119. var desiredWidth = this._options.width || requiredWidth;
  35120. var desiredHeight = this._options.height || requiredHeight;
  35121. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  35122. if (!this._options.width) {
  35123. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  35124. }
  35125. if (!this._options.height) {
  35126. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  35127. }
  35128. }
  35129. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  35130. if (this._textures.length > 0) {
  35131. for (var i = 0; i < this._textures.length; i++) {
  35132. this._engine._releaseTexture(this._textures.data[i]);
  35133. }
  35134. this._textures.reset();
  35135. }
  35136. this.width = desiredWidth;
  35137. this.height = desiredHeight;
  35138. var textureSize = { width: this.width, height: this.height };
  35139. var textureOptions = {
  35140. generateMipMaps: false,
  35141. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  35142. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  35143. samplingMode: this.renderTargetSamplingMode,
  35144. type: this._textureType
  35145. };
  35146. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35147. if (this._reusable) {
  35148. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35149. }
  35150. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  35151. this.onSizeChangedObservable.notifyObservers(this);
  35152. }
  35153. this._textures.forEach(function (texture) {
  35154. if (texture.samples !== _this.samples) {
  35155. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  35156. }
  35157. });
  35158. }
  35159. var target;
  35160. if (this._shareOutputWithPostProcess) {
  35161. target = this._shareOutputWithPostProcess.outputTexture;
  35162. }
  35163. else if (this._forcedOutputTexture) {
  35164. target = this._forcedOutputTexture;
  35165. this.width = this._forcedOutputTexture.width;
  35166. this.height = this._forcedOutputTexture.height;
  35167. }
  35168. else {
  35169. target = this.outputTexture;
  35170. }
  35171. if (this.enablePixelPerfectMode) {
  35172. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  35173. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  35174. }
  35175. else {
  35176. this._scaleRatio.copyFromFloats(1, 1);
  35177. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  35178. }
  35179. this.onActivateObservable.notifyObservers(camera);
  35180. // Clear
  35181. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  35182. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  35183. }
  35184. if (this._reusable) {
  35185. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  35186. }
  35187. };
  35188. Object.defineProperty(PostProcess.prototype, "isSupported", {
  35189. get: function () {
  35190. return this._effect.isSupported;
  35191. },
  35192. enumerable: true,
  35193. configurable: true
  35194. });
  35195. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  35196. get: function () {
  35197. if (this._shareOutputWithPostProcess) {
  35198. return this._shareOutputWithPostProcess.aspectRatio;
  35199. }
  35200. if (this._forcedOutputTexture) {
  35201. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  35202. }
  35203. return this.width / this.height;
  35204. },
  35205. enumerable: true,
  35206. configurable: true
  35207. });
  35208. PostProcess.prototype.apply = function () {
  35209. // Check
  35210. if (!this._effect || !this._effect.isReady())
  35211. return null;
  35212. // States
  35213. this._engine.enableEffect(this._effect);
  35214. this._engine.setState(false);
  35215. this._engine.setDepthBuffer(false);
  35216. this._engine.setDepthWrite(false);
  35217. // Alpha
  35218. this._engine.setAlphaMode(this.alphaMode);
  35219. if (this.alphaConstants) {
  35220. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  35221. }
  35222. // Texture
  35223. var source;
  35224. if (this._shareOutputWithPostProcess) {
  35225. source = this._shareOutputWithPostProcess.outputTexture;
  35226. }
  35227. else if (this._forcedOutputTexture) {
  35228. source = this._forcedOutputTexture;
  35229. }
  35230. else {
  35231. source = this.outputTexture;
  35232. }
  35233. this._effect._bindTexture("textureSampler", source);
  35234. // Parameters
  35235. this._effect.setVector2("scale", this._scaleRatio);
  35236. this.onApplyObservable.notifyObservers(this._effect);
  35237. return this._effect;
  35238. };
  35239. PostProcess.prototype._disposeTextures = function () {
  35240. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  35241. return;
  35242. }
  35243. if (this._textures.length > 0) {
  35244. for (var i = 0; i < this._textures.length; i++) {
  35245. this._engine._releaseTexture(this._textures.data[i]);
  35246. }
  35247. }
  35248. this._textures.dispose();
  35249. };
  35250. PostProcess.prototype.dispose = function (camera) {
  35251. camera = camera || this._camera;
  35252. this._disposeTextures();
  35253. if (this._scene) {
  35254. var index_1 = this._scene.postProcesses.indexOf(this);
  35255. if (index_1 !== -1) {
  35256. this._scene.postProcesses.splice(index_1, 1);
  35257. }
  35258. }
  35259. else {
  35260. var index_2 = this._engine.postProcesses.indexOf(this);
  35261. if (index_2 !== -1) {
  35262. this._engine.postProcesses.splice(index_2, 1);
  35263. }
  35264. }
  35265. if (!camera) {
  35266. return;
  35267. }
  35268. camera.detachPostProcess(this);
  35269. var index = camera._postProcesses.indexOf(this);
  35270. if (index === 0 && camera._postProcesses.length > 0) {
  35271. this._camera._postProcesses[0].markTextureDirty();
  35272. }
  35273. this.onActivateObservable.clear();
  35274. this.onAfterRenderObservable.clear();
  35275. this.onApplyObservable.clear();
  35276. this.onBeforeRenderObservable.clear();
  35277. this.onSizeChangedObservable.clear();
  35278. };
  35279. return PostProcess;
  35280. }());
  35281. BABYLON.PostProcess = PostProcess;
  35282. })(BABYLON || (BABYLON = {}));
  35283. //# sourceMappingURL=babylon.postProcess.js.map
  35284. var BABYLON;
  35285. (function (BABYLON) {
  35286. var PassPostProcess = (function (_super) {
  35287. __extends(PassPostProcess, _super);
  35288. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  35289. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35290. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  35291. }
  35292. return PassPostProcess;
  35293. }(BABYLON.PostProcess));
  35294. BABYLON.PassPostProcess = PassPostProcess;
  35295. })(BABYLON || (BABYLON = {}));
  35296. //# sourceMappingURL=babylon.passPostProcess.js.map
  35297. var BABYLON;
  35298. (function (BABYLON) {
  35299. var ShadowGenerator = (function () {
  35300. /**
  35301. * Creates a ShadowGenerator object.
  35302. * A ShadowGenerator is the required tool to use the shadows.
  35303. * Each light casting shadows needs to use its own ShadowGenerator.
  35304. * Required parameters :
  35305. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  35306. * - `light`: the light object generating the shadows.
  35307. * - `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.
  35308. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  35309. */
  35310. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  35311. // Members
  35312. this._bias = 0.00005;
  35313. this._blurBoxOffset = 1;
  35314. this._blurScale = 2;
  35315. this._blurKernel = 1;
  35316. this._useKernelBlur = false;
  35317. this._filter = ShadowGenerator.FILTER_NONE;
  35318. this._darkness = 0;
  35319. this._transparencyShadow = false;
  35320. /**
  35321. * Controls the extent to which the shadows fade out at the edge of the frustum
  35322. * Used only by directionals and spots
  35323. */
  35324. this.frustumEdgeFalloff = 0;
  35325. this.forceBackFacesOnly = false;
  35326. this._lightDirection = BABYLON.Vector3.Zero();
  35327. this._viewMatrix = BABYLON.Matrix.Zero();
  35328. this._projectionMatrix = BABYLON.Matrix.Zero();
  35329. this._transformMatrix = BABYLON.Matrix.Zero();
  35330. this._worldViewProjection = BABYLON.Matrix.Zero();
  35331. this._currentFaceIndex = 0;
  35332. this._currentFaceIndexCache = 0;
  35333. this._isCube = false;
  35334. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  35335. this._mapSize = mapSize;
  35336. this._light = light;
  35337. this._scene = light.getScene();
  35338. light._shadowGenerator = this;
  35339. // Texture type fallback from float to int if not supported.
  35340. var caps = this._scene.getEngine().getCaps();
  35341. if (!useFullFloatFirst) {
  35342. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  35343. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  35344. }
  35345. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  35346. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  35347. }
  35348. else {
  35349. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  35350. }
  35351. }
  35352. else {
  35353. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  35354. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  35355. }
  35356. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  35357. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  35358. }
  35359. else {
  35360. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  35361. }
  35362. }
  35363. this._initializeGenerator();
  35364. }
  35365. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  35366. // Static
  35367. get: function () {
  35368. return ShadowGenerator._FILTER_NONE;
  35369. },
  35370. enumerable: true,
  35371. configurable: true
  35372. });
  35373. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  35374. get: function () {
  35375. return ShadowGenerator._FILTER_POISSONSAMPLING;
  35376. },
  35377. enumerable: true,
  35378. configurable: true
  35379. });
  35380. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  35381. get: function () {
  35382. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  35383. },
  35384. enumerable: true,
  35385. configurable: true
  35386. });
  35387. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  35388. get: function () {
  35389. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  35390. },
  35391. enumerable: true,
  35392. configurable: true
  35393. });
  35394. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  35395. get: function () {
  35396. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  35397. },
  35398. enumerable: true,
  35399. configurable: true
  35400. });
  35401. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  35402. get: function () {
  35403. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  35404. },
  35405. enumerable: true,
  35406. configurable: true
  35407. });
  35408. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  35409. get: function () {
  35410. return this._bias;
  35411. },
  35412. set: function (bias) {
  35413. this._bias = bias;
  35414. },
  35415. enumerable: true,
  35416. configurable: true
  35417. });
  35418. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  35419. get: function () {
  35420. return this._blurBoxOffset;
  35421. },
  35422. set: function (value) {
  35423. if (this._blurBoxOffset === value) {
  35424. return;
  35425. }
  35426. this._blurBoxOffset = value;
  35427. this._disposeBlurPostProcesses();
  35428. },
  35429. enumerable: true,
  35430. configurable: true
  35431. });
  35432. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  35433. get: function () {
  35434. return this._blurScale;
  35435. },
  35436. set: function (value) {
  35437. if (this._blurScale === value) {
  35438. return;
  35439. }
  35440. this._blurScale = value;
  35441. this._disposeBlurPostProcesses();
  35442. },
  35443. enumerable: true,
  35444. configurable: true
  35445. });
  35446. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  35447. get: function () {
  35448. return this._blurKernel;
  35449. },
  35450. set: function (value) {
  35451. if (this._blurKernel === value) {
  35452. return;
  35453. }
  35454. this._blurKernel = value;
  35455. this._disposeBlurPostProcesses();
  35456. },
  35457. enumerable: true,
  35458. configurable: true
  35459. });
  35460. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  35461. get: function () {
  35462. return this._useKernelBlur;
  35463. },
  35464. set: function (value) {
  35465. if (this._useKernelBlur === value) {
  35466. return;
  35467. }
  35468. this._useKernelBlur = value;
  35469. this._disposeBlurPostProcesses();
  35470. },
  35471. enumerable: true,
  35472. configurable: true
  35473. });
  35474. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  35475. get: function () {
  35476. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  35477. },
  35478. set: function (value) {
  35479. this._depthScale = value;
  35480. },
  35481. enumerable: true,
  35482. configurable: true
  35483. });
  35484. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  35485. get: function () {
  35486. return this._filter;
  35487. },
  35488. set: function (value) {
  35489. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  35490. if (this._light.needCube()) {
  35491. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  35492. this.useExponentialShadowMap = true;
  35493. return;
  35494. }
  35495. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  35496. this.useCloseExponentialShadowMap = true;
  35497. return;
  35498. }
  35499. }
  35500. if (this._filter === value) {
  35501. return;
  35502. }
  35503. this._filter = value;
  35504. this._disposeBlurPostProcesses();
  35505. this._applyFilterValues();
  35506. this._light._markMeshesAsLightDirty();
  35507. },
  35508. enumerable: true,
  35509. configurable: true
  35510. });
  35511. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  35512. get: function () {
  35513. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  35514. },
  35515. set: function (value) {
  35516. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  35517. return;
  35518. }
  35519. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  35520. },
  35521. enumerable: true,
  35522. configurable: true
  35523. });
  35524. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  35525. get: function () {
  35526. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  35527. return this.useExponentialShadowMap;
  35528. },
  35529. set: function (value) {
  35530. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  35531. this.useExponentialShadowMap = value;
  35532. },
  35533. enumerable: true,
  35534. configurable: true
  35535. });
  35536. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  35537. get: function () {
  35538. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  35539. return this.useBlurExponentialShadowMap;
  35540. },
  35541. set: function (value) {
  35542. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  35543. this.useBlurExponentialShadowMap = value;
  35544. },
  35545. enumerable: true,
  35546. configurable: true
  35547. });
  35548. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  35549. get: function () {
  35550. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  35551. },
  35552. set: function (value) {
  35553. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  35554. return;
  35555. }
  35556. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35557. },
  35558. enumerable: true,
  35559. configurable: true
  35560. });
  35561. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  35562. get: function () {
  35563. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  35564. },
  35565. set: function (value) {
  35566. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  35567. return;
  35568. }
  35569. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35570. },
  35571. enumerable: true,
  35572. configurable: true
  35573. });
  35574. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  35575. get: function () {
  35576. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  35577. },
  35578. set: function (value) {
  35579. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  35580. return;
  35581. }
  35582. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35583. },
  35584. enumerable: true,
  35585. configurable: true
  35586. });
  35587. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  35588. get: function () {
  35589. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  35590. },
  35591. set: function (value) {
  35592. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  35593. return;
  35594. }
  35595. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35596. },
  35597. enumerable: true,
  35598. configurable: true
  35599. });
  35600. /**
  35601. * Returns the darkness value (float).
  35602. */
  35603. ShadowGenerator.prototype.getDarkness = function () {
  35604. return this._darkness;
  35605. };
  35606. /**
  35607. * Sets the ShadowGenerator darkness value (float <= 1.0).
  35608. * Returns the ShadowGenerator.
  35609. */
  35610. ShadowGenerator.prototype.setDarkness = function (darkness) {
  35611. if (darkness >= 1.0)
  35612. this._darkness = 1.0;
  35613. else if (darkness <= 0.0)
  35614. this._darkness = 0.0;
  35615. else
  35616. this._darkness = darkness;
  35617. return this;
  35618. };
  35619. /**
  35620. * Sets the ability to have transparent shadow (boolean).
  35621. * Returns the ShadowGenerator.
  35622. */
  35623. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  35624. this._transparencyShadow = hasShadow;
  35625. return this;
  35626. };
  35627. /**
  35628. * Returns a RenderTargetTexture object : the shadow map texture.
  35629. */
  35630. ShadowGenerator.prototype.getShadowMap = function () {
  35631. return this._shadowMap;
  35632. };
  35633. /**
  35634. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  35635. */
  35636. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  35637. if (this._shadowMap2) {
  35638. return this._shadowMap2;
  35639. }
  35640. return this._shadowMap;
  35641. };
  35642. /**
  35643. * Returns the associated light object.
  35644. */
  35645. ShadowGenerator.prototype.getLight = function () {
  35646. return this._light;
  35647. };
  35648. ShadowGenerator.prototype._initializeGenerator = function () {
  35649. this._light._markMeshesAsLightDirty();
  35650. this._initializeShadowMap();
  35651. };
  35652. ShadowGenerator.prototype._initializeShadowMap = function () {
  35653. var _this = this;
  35654. // Render target
  35655. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  35656. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35657. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35658. this._shadowMap.anisotropicFilteringLevel = 1;
  35659. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35660. this._shadowMap.renderParticles = false;
  35661. // Record Face Index before render.
  35662. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  35663. _this._currentFaceIndex = faceIndex;
  35664. });
  35665. // Custom render function.
  35666. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  35667. // Blur if required afer render.
  35668. this._shadowMap.onAfterUnbindObservable.add(function () {
  35669. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  35670. return;
  35671. }
  35672. if (!_this._blurPostProcesses) {
  35673. _this._initializeBlurRTTAndPostProcesses();
  35674. }
  35675. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  35676. });
  35677. // Clear according to the chosen filter.
  35678. this._shadowMap.onClearObservable.add(function (engine) {
  35679. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  35680. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  35681. }
  35682. else {
  35683. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  35684. }
  35685. });
  35686. };
  35687. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  35688. var _this = this;
  35689. var engine = this._scene.getEngine();
  35690. var targetSize = this._mapSize / this.blurScale;
  35691. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  35692. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  35693. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35694. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35695. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35696. }
  35697. if (this.useKernelBlur) {
  35698. 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);
  35699. this._kernelBlurXPostprocess.width = targetSize;
  35700. this._kernelBlurXPostprocess.height = targetSize;
  35701. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  35702. effect.setTexture("textureSampler", _this._shadowMap);
  35703. });
  35704. 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);
  35705. this._kernelBlurXPostprocess.autoClear = false;
  35706. this._kernelBlurYPostprocess.autoClear = false;
  35707. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35708. this._kernelBlurXPostprocess.packedFloat = true;
  35709. this._kernelBlurYPostprocess.packedFloat = true;
  35710. }
  35711. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  35712. }
  35713. else {
  35714. 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);
  35715. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  35716. effect.setFloat2("screenSize", targetSize, targetSize);
  35717. effect.setTexture("textureSampler", _this._shadowMap);
  35718. });
  35719. this._boxBlurPostprocess.autoClear = false;
  35720. this._blurPostProcesses = [this._boxBlurPostprocess];
  35721. }
  35722. };
  35723. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35724. var index;
  35725. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35726. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  35727. }
  35728. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35729. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  35730. }
  35731. if (this._transparencyShadow) {
  35732. for (index = 0; index < transparentSubMeshes.length; index++) {
  35733. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  35734. }
  35735. }
  35736. };
  35737. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  35738. var _this = this;
  35739. var mesh = subMesh.getRenderingMesh();
  35740. var scene = this._scene;
  35741. var engine = scene.getEngine();
  35742. // Culling
  35743. engine.setState(subMesh.getMaterial().backFaceCulling);
  35744. // Managing instances
  35745. var batch = mesh._getInstancesRenderList(subMesh._id);
  35746. if (batch.mustReturn) {
  35747. return;
  35748. }
  35749. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  35750. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  35751. engine.enableEffect(this._effect);
  35752. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  35753. var material = subMesh.getMaterial();
  35754. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  35755. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  35756. this._effect.setVector3("lightPosition", this.getLight().position);
  35757. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  35758. // Alpha test
  35759. if (material && material.needAlphaTesting()) {
  35760. var alphaTexture = material.getAlphaTestTexture();
  35761. if (alphaTexture) {
  35762. this._effect.setTexture("diffuseSampler", alphaTexture);
  35763. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  35764. }
  35765. }
  35766. // Bones
  35767. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35768. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35769. }
  35770. if (this.forceBackFacesOnly) {
  35771. engine.setState(true, 0, false, true);
  35772. }
  35773. // Draw
  35774. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35775. if (this.forceBackFacesOnly) {
  35776. engine.setState(true, 0, false, false);
  35777. }
  35778. }
  35779. else {
  35780. // Need to reset refresh rate of the shadowMap
  35781. this._shadowMap.resetRefreshCounter();
  35782. }
  35783. };
  35784. ShadowGenerator.prototype._applyFilterValues = function () {
  35785. if (this.filter === ShadowGenerator.FILTER_NONE) {
  35786. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  35787. }
  35788. else {
  35789. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35790. }
  35791. };
  35792. /**
  35793. * Force shader compilation including textures ready check
  35794. */
  35795. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  35796. var _this = this;
  35797. var scene = this._scene;
  35798. var engine = scene.getEngine();
  35799. var subMeshes = new Array();
  35800. var currentIndex = 0;
  35801. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  35802. var mesh = _a[_i];
  35803. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  35804. }
  35805. var checkReady = function () {
  35806. if (!_this._scene || !_this._scene.getEngine()) {
  35807. return;
  35808. }
  35809. var subMesh = subMeshes[currentIndex];
  35810. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  35811. currentIndex++;
  35812. if (currentIndex >= subMeshes.length) {
  35813. if (onCompiled) {
  35814. onCompiled(_this);
  35815. }
  35816. return;
  35817. }
  35818. }
  35819. setTimeout(checkReady, 16);
  35820. };
  35821. if (subMeshes.length > 0) {
  35822. checkReady();
  35823. }
  35824. };
  35825. /**
  35826. * Boolean : true when the ShadowGenerator is finally computed.
  35827. */
  35828. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  35829. var defines = [];
  35830. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35831. defines.push("#define FLOAT");
  35832. }
  35833. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  35834. defines.push("#define ESM");
  35835. }
  35836. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35837. var mesh = subMesh.getMesh();
  35838. var material = subMesh.getMaterial();
  35839. // Alpha test
  35840. if (material && material.needAlphaTesting()) {
  35841. var alphaTexture = material.getAlphaTestTexture();
  35842. if (alphaTexture) {
  35843. defines.push("#define ALPHATEST");
  35844. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35845. attribs.push(BABYLON.VertexBuffer.UVKind);
  35846. defines.push("#define UV1");
  35847. }
  35848. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35849. if (alphaTexture.coordinatesIndex === 1) {
  35850. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35851. defines.push("#define UV2");
  35852. }
  35853. }
  35854. }
  35855. }
  35856. // Bones
  35857. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35858. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35859. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35860. if (mesh.numBoneInfluencers > 4) {
  35861. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35862. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35863. }
  35864. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35865. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35866. }
  35867. else {
  35868. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35869. }
  35870. // Instances
  35871. if (useInstances) {
  35872. defines.push("#define INSTANCES");
  35873. attribs.push("world0");
  35874. attribs.push("world1");
  35875. attribs.push("world2");
  35876. attribs.push("world3");
  35877. }
  35878. // Get correct effect
  35879. var join = defines.join("\n");
  35880. if (this._cachedDefines !== join) {
  35881. this._cachedDefines = join;
  35882. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  35883. }
  35884. return this._effect.isReady();
  35885. };
  35886. /**
  35887. * This creates the defines related to the standard BJS materials.
  35888. */
  35889. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  35890. var scene = this._scene;
  35891. var light = this._light;
  35892. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  35893. return;
  35894. }
  35895. defines["SHADOW" + lightIndex] = true;
  35896. if (this.usePoissonSampling) {
  35897. defines["SHADOWPCF" + lightIndex] = true;
  35898. }
  35899. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  35900. defines["SHADOWESM" + lightIndex] = true;
  35901. }
  35902. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  35903. defines["SHADOWCLOSEESM" + lightIndex] = true;
  35904. }
  35905. if (light.needCube()) {
  35906. defines["SHADOWCUBE" + lightIndex] = true;
  35907. }
  35908. };
  35909. /**
  35910. * This binds shadow lights related to the standard BJS materials.
  35911. * It implies the unifroms available on the materials are the standard BJS ones.
  35912. */
  35913. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  35914. var light = this._light;
  35915. var scene = this._scene;
  35916. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  35917. return;
  35918. }
  35919. if (!light.needCube()) {
  35920. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  35921. }
  35922. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  35923. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  35924. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  35925. };
  35926. // Methods
  35927. /**
  35928. * Returns a Matrix object : the updated transformation matrix.
  35929. */
  35930. ShadowGenerator.prototype.getTransformMatrix = function () {
  35931. var scene = this._scene;
  35932. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  35933. return this._transformMatrix;
  35934. }
  35935. this._currentRenderID = scene.getRenderId();
  35936. this._currentFaceIndexCache = this._currentFaceIndex;
  35937. var lightPosition = this._light.position;
  35938. if (this._light.computeTransformedInformation()) {
  35939. lightPosition = this._light.transformedPosition;
  35940. }
  35941. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  35942. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  35943. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  35944. }
  35945. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  35946. this._cachedPosition = lightPosition.clone();
  35947. this._cachedDirection = this._lightDirection.clone();
  35948. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  35949. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  35950. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  35951. }
  35952. return this._transformMatrix;
  35953. };
  35954. ShadowGenerator.prototype.recreateShadowMap = function () {
  35955. // Track render list.
  35956. var renderList = this._shadowMap.renderList;
  35957. // Clean up existing data.
  35958. this._disposeRTTandPostProcesses();
  35959. // Reinitializes.
  35960. this._initializeGenerator();
  35961. // Reaffect the filter to ensure a correct fallback if necessary.
  35962. this.filter = this.filter;
  35963. // Reaffect the filter.
  35964. this._applyFilterValues();
  35965. // Reaffect Render List.
  35966. this._shadowMap.renderList = renderList;
  35967. };
  35968. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  35969. if (this._shadowMap2) {
  35970. this._shadowMap2.dispose();
  35971. this._shadowMap2 = null;
  35972. }
  35973. if (this._downSamplePostprocess) {
  35974. this._downSamplePostprocess.dispose();
  35975. this._downSamplePostprocess = null;
  35976. }
  35977. if (this._boxBlurPostprocess) {
  35978. this._boxBlurPostprocess.dispose();
  35979. this._boxBlurPostprocess = null;
  35980. }
  35981. if (this._kernelBlurXPostprocess) {
  35982. this._kernelBlurXPostprocess.dispose();
  35983. this._kernelBlurXPostprocess = null;
  35984. }
  35985. if (this._kernelBlurYPostprocess) {
  35986. this._kernelBlurYPostprocess.dispose();
  35987. this._kernelBlurYPostprocess = null;
  35988. }
  35989. this._blurPostProcesses = null;
  35990. };
  35991. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  35992. if (this._shadowMap) {
  35993. this._shadowMap.dispose();
  35994. this._shadowMap = null;
  35995. }
  35996. this._disposeBlurPostProcesses();
  35997. };
  35998. /**
  35999. * Disposes the ShadowGenerator.
  36000. * Returns nothing.
  36001. */
  36002. ShadowGenerator.prototype.dispose = function () {
  36003. this._disposeRTTandPostProcesses();
  36004. this._light._shadowGenerator = null;
  36005. this._light._markMeshesAsLightDirty();
  36006. };
  36007. /**
  36008. * Serializes the ShadowGenerator and returns a serializationObject.
  36009. */
  36010. ShadowGenerator.prototype.serialize = function () {
  36011. var serializationObject = {};
  36012. var shadowMap = this.getShadowMap();
  36013. serializationObject.lightId = this._light.id;
  36014. serializationObject.mapSize = shadowMap.getRenderSize();
  36015. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  36016. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  36017. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  36018. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  36019. serializationObject.usePoissonSampling = this.usePoissonSampling;
  36020. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  36021. serializationObject.depthScale = this.depthScale;
  36022. serializationObject.darkness = this.getDarkness();
  36023. serializationObject.blurBoxOffset = this.blurBoxOffset;
  36024. serializationObject.blurKernel = this.blurKernel;
  36025. serializationObject.blurScale = this.blurScale;
  36026. serializationObject.useKernelBlur = this.useKernelBlur;
  36027. serializationObject.transparencyShadow = this._transparencyShadow;
  36028. serializationObject.renderList = [];
  36029. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  36030. var mesh = shadowMap.renderList[meshIndex];
  36031. serializationObject.renderList.push(mesh.id);
  36032. }
  36033. return serializationObject;
  36034. };
  36035. /**
  36036. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  36037. */
  36038. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  36039. //casting to point light, as light is missing the position attr and typescript complains.
  36040. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  36041. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  36042. var shadowMap = shadowGenerator.getShadowMap();
  36043. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  36044. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  36045. meshes.forEach(function (mesh) {
  36046. shadowMap.renderList.push(mesh);
  36047. });
  36048. }
  36049. if (parsedShadowGenerator.usePoissonSampling) {
  36050. shadowGenerator.usePoissonSampling = true;
  36051. }
  36052. else if (parsedShadowGenerator.useExponentialShadowMap) {
  36053. shadowGenerator.useExponentialShadowMap = true;
  36054. }
  36055. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  36056. shadowGenerator.useBlurExponentialShadowMap = true;
  36057. }
  36058. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  36059. shadowGenerator.useCloseExponentialShadowMap = true;
  36060. }
  36061. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  36062. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  36063. }
  36064. else if (parsedShadowGenerator.useVarianceShadowMap) {
  36065. shadowGenerator.useExponentialShadowMap = true;
  36066. }
  36067. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  36068. shadowGenerator.useBlurExponentialShadowMap = true;
  36069. }
  36070. if (parsedShadowGenerator.depthScale) {
  36071. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  36072. }
  36073. if (parsedShadowGenerator.blurScale) {
  36074. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  36075. }
  36076. if (parsedShadowGenerator.blurBoxOffset) {
  36077. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  36078. }
  36079. if (parsedShadowGenerator.useKernelBlur) {
  36080. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  36081. }
  36082. if (parsedShadowGenerator.blurKernel) {
  36083. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  36084. }
  36085. if (parsedShadowGenerator.bias !== undefined) {
  36086. shadowGenerator.bias = parsedShadowGenerator.bias;
  36087. }
  36088. if (parsedShadowGenerator.darkness) {
  36089. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  36090. }
  36091. if (parsedShadowGenerator.transparencyShadow) {
  36092. shadowGenerator.setTransparencyShadow(true);
  36093. }
  36094. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  36095. return shadowGenerator;
  36096. };
  36097. ShadowGenerator._FILTER_NONE = 0;
  36098. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  36099. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  36100. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  36101. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  36102. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  36103. return ShadowGenerator;
  36104. }());
  36105. BABYLON.ShadowGenerator = ShadowGenerator;
  36106. })(BABYLON || (BABYLON = {}));
  36107. //# sourceMappingURL=babylon.shadowGenerator.js.map
  36108. var BABYLON;
  36109. (function (BABYLON) {
  36110. var ShadowLight = (function (_super) {
  36111. __extends(ShadowLight, _super);
  36112. function ShadowLight() {
  36113. var _this = _super !== null && _super.apply(this, arguments) || this;
  36114. _this._needProjectionMatrixCompute = true;
  36115. return _this;
  36116. }
  36117. Object.defineProperty(ShadowLight.prototype, "direction", {
  36118. get: function () {
  36119. return this._direction;
  36120. },
  36121. set: function (value) {
  36122. this._direction = value;
  36123. },
  36124. enumerable: true,
  36125. configurable: true
  36126. });
  36127. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  36128. get: function () {
  36129. return this._shadowMinZ;
  36130. },
  36131. set: function (value) {
  36132. this._shadowMinZ = value;
  36133. this.forceProjectionMatrixCompute();
  36134. },
  36135. enumerable: true,
  36136. configurable: true
  36137. });
  36138. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  36139. get: function () {
  36140. return this._shadowMaxZ;
  36141. },
  36142. set: function (value) {
  36143. this._shadowMaxZ = value;
  36144. this.forceProjectionMatrixCompute();
  36145. },
  36146. enumerable: true,
  36147. configurable: true
  36148. });
  36149. /**
  36150. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  36151. */
  36152. ShadowLight.prototype.computeTransformedInformation = function () {
  36153. if (this.parent && this.parent.getWorldMatrix) {
  36154. if (!this.transformedPosition) {
  36155. this.transformedPosition = BABYLON.Vector3.Zero();
  36156. }
  36157. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  36158. // In case the direction is present.
  36159. if (this.direction) {
  36160. if (!this.transformedDirection) {
  36161. this.transformedDirection = BABYLON.Vector3.Zero();
  36162. }
  36163. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  36164. }
  36165. return true;
  36166. }
  36167. return false;
  36168. };
  36169. /**
  36170. * Return the depth scale used for the shadow map.
  36171. */
  36172. ShadowLight.prototype.getDepthScale = function () {
  36173. return 50.0;
  36174. };
  36175. /**
  36176. * Returns the light direction (Vector3) for any passed face index.
  36177. */
  36178. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  36179. return this.transformedDirection ? this.transformedDirection : this.direction;
  36180. };
  36181. /**
  36182. * Returns the DirectionalLight absolute position in the World.
  36183. */
  36184. ShadowLight.prototype.getAbsolutePosition = function () {
  36185. return this.transformedPosition ? this.transformedPosition : this.position;
  36186. };
  36187. /**
  36188. * Sets the DirectionalLight direction toward the passed target (Vector3).
  36189. * Returns the updated DirectionalLight direction (Vector3).
  36190. */
  36191. ShadowLight.prototype.setDirectionToTarget = function (target) {
  36192. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  36193. return this.direction;
  36194. };
  36195. /**
  36196. * Returns the light rotation (Vector3).
  36197. */
  36198. ShadowLight.prototype.getRotation = function () {
  36199. this.direction.normalize();
  36200. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  36201. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  36202. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  36203. };
  36204. /**
  36205. * Boolean : false by default.
  36206. */
  36207. ShadowLight.prototype.needCube = function () {
  36208. return false;
  36209. };
  36210. /**
  36211. * Specifies wether or not the projection matrix should be recomputed this frame.
  36212. */
  36213. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  36214. return this._needProjectionMatrixCompute;
  36215. };
  36216. /**
  36217. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  36218. */
  36219. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  36220. this._needProjectionMatrixCompute = true;
  36221. };
  36222. /**
  36223. * Get the world matrix of the sahdow lights.
  36224. */
  36225. ShadowLight.prototype._getWorldMatrix = function () {
  36226. if (!this._worldMatrix) {
  36227. this._worldMatrix = BABYLON.Matrix.Identity();
  36228. }
  36229. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  36230. return this._worldMatrix;
  36231. };
  36232. /**
  36233. * Gets the minZ used for shadow according to both the scene and the light.
  36234. * @param activeCamera
  36235. */
  36236. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  36237. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  36238. };
  36239. /**
  36240. * Gets the maxZ used for shadow according to both the scene and the light.
  36241. * @param activeCamera
  36242. */
  36243. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  36244. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  36245. };
  36246. /**
  36247. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  36248. * Returns the light.
  36249. */
  36250. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36251. if (this.customProjectionMatrixBuilder) {
  36252. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  36253. }
  36254. else {
  36255. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36256. }
  36257. return this;
  36258. };
  36259. __decorate([
  36260. BABYLON.serializeAsVector3()
  36261. ], ShadowLight.prototype, "position", void 0);
  36262. __decorate([
  36263. BABYLON.serializeAsVector3()
  36264. ], ShadowLight.prototype, "direction", null);
  36265. __decorate([
  36266. BABYLON.serialize()
  36267. ], ShadowLight.prototype, "shadowMinZ", null);
  36268. __decorate([
  36269. BABYLON.serialize()
  36270. ], ShadowLight.prototype, "shadowMaxZ", null);
  36271. return ShadowLight;
  36272. }(BABYLON.Light));
  36273. BABYLON.ShadowLight = ShadowLight;
  36274. })(BABYLON || (BABYLON = {}));
  36275. //# sourceMappingURL=babylon.shadowLight.js.map
  36276. var BABYLON;
  36277. (function (BABYLON) {
  36278. var PointLight = (function (_super) {
  36279. __extends(PointLight, _super);
  36280. /**
  36281. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  36282. * A PointLight emits the light in every direction.
  36283. * It can cast shadows.
  36284. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  36285. * ```javascript
  36286. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  36287. * ```
  36288. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36289. */
  36290. function PointLight(name, position, scene) {
  36291. var _this = _super.call(this, name, scene) || this;
  36292. _this._shadowAngle = Math.PI / 2;
  36293. _this.position = position;
  36294. return _this;
  36295. }
  36296. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  36297. /**
  36298. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36299. * This specifies what angle the shadow will use to be created.
  36300. *
  36301. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36302. */
  36303. get: function () {
  36304. return this._shadowAngle;
  36305. },
  36306. /**
  36307. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36308. * This specifies what angle the shadow will use to be created.
  36309. *
  36310. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36311. */
  36312. set: function (value) {
  36313. this._shadowAngle = value;
  36314. this.forceProjectionMatrixCompute();
  36315. },
  36316. enumerable: true,
  36317. configurable: true
  36318. });
  36319. Object.defineProperty(PointLight.prototype, "direction", {
  36320. get: function () {
  36321. return this._direction;
  36322. },
  36323. /**
  36324. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36325. */
  36326. set: function (value) {
  36327. var previousNeedCube = this.needCube();
  36328. this._direction = value;
  36329. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  36330. this._shadowGenerator.recreateShadowMap();
  36331. }
  36332. },
  36333. enumerable: true,
  36334. configurable: true
  36335. });
  36336. /**
  36337. * Returns the string "PointLight"
  36338. */
  36339. PointLight.prototype.getClassName = function () {
  36340. return "PointLight";
  36341. };
  36342. /**
  36343. * Returns the integer 0.
  36344. */
  36345. PointLight.prototype.getTypeID = function () {
  36346. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  36347. };
  36348. /**
  36349. * Specifies wether or not the shadowmap should be a cube texture.
  36350. */
  36351. PointLight.prototype.needCube = function () {
  36352. return !this.direction;
  36353. };
  36354. /**
  36355. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  36356. */
  36357. PointLight.prototype.getShadowDirection = function (faceIndex) {
  36358. if (this.direction) {
  36359. return _super.prototype.getShadowDirection.call(this, faceIndex);
  36360. }
  36361. else {
  36362. switch (faceIndex) {
  36363. case 0:
  36364. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  36365. case 1:
  36366. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  36367. case 2:
  36368. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  36369. case 3:
  36370. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  36371. case 4:
  36372. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  36373. case 5:
  36374. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  36375. }
  36376. }
  36377. return BABYLON.Vector3.Zero();
  36378. };
  36379. /**
  36380. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  36381. * - fov = PI / 2
  36382. * - aspect ratio : 1.0
  36383. * - z-near and far equal to the active camera minZ and maxZ.
  36384. * Returns the PointLight.
  36385. */
  36386. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36387. var activeCamera = this.getScene().activeCamera;
  36388. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36389. };
  36390. PointLight.prototype._buildUniformLayout = function () {
  36391. this._uniformBuffer.addUniform("vLightData", 4);
  36392. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36393. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36394. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36395. this._uniformBuffer.addUniform("depthValues", 2);
  36396. this._uniformBuffer.create();
  36397. };
  36398. /**
  36399. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  36400. * Returns the PointLight.
  36401. */
  36402. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  36403. if (this.computeTransformedInformation()) {
  36404. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  36405. return this;
  36406. }
  36407. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36408. return this;
  36409. };
  36410. __decorate([
  36411. BABYLON.serialize()
  36412. ], PointLight.prototype, "shadowAngle", null);
  36413. return PointLight;
  36414. }(BABYLON.ShadowLight));
  36415. BABYLON.PointLight = PointLight;
  36416. })(BABYLON || (BABYLON = {}));
  36417. //# sourceMappingURL=babylon.pointLight.js.map
  36418. /// <reference path="babylon.light.ts" />
  36419. var BABYLON;
  36420. (function (BABYLON) {
  36421. var DirectionalLight = (function (_super) {
  36422. __extends(DirectionalLight, _super);
  36423. /**
  36424. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36425. * The directional light is emitted from everywhere in the given direction.
  36426. * It can cast shawdows.
  36427. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36428. */
  36429. function DirectionalLight(name, direction, scene) {
  36430. var _this = _super.call(this, name, scene) || this;
  36431. _this._shadowFrustumSize = 0;
  36432. _this._shadowOrthoScale = 0.5;
  36433. _this.autoUpdateExtends = true;
  36434. // Cache
  36435. _this._orthoLeft = Number.MAX_VALUE;
  36436. _this._orthoRight = Number.MIN_VALUE;
  36437. _this._orthoTop = Number.MIN_VALUE;
  36438. _this._orthoBottom = Number.MAX_VALUE;
  36439. _this.position = direction.scale(-1.0);
  36440. _this.direction = direction;
  36441. return _this;
  36442. }
  36443. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36444. /**
  36445. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36446. */
  36447. get: function () {
  36448. return this._shadowFrustumSize;
  36449. },
  36450. /**
  36451. * Specifies a fix frustum size for the shadow generation.
  36452. */
  36453. set: function (value) {
  36454. this._shadowFrustumSize = value;
  36455. this.forceProjectionMatrixCompute();
  36456. },
  36457. enumerable: true,
  36458. configurable: true
  36459. });
  36460. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36461. get: function () {
  36462. return this._shadowOrthoScale;
  36463. },
  36464. set: function (value) {
  36465. this._shadowOrthoScale = value;
  36466. this.forceProjectionMatrixCompute();
  36467. },
  36468. enumerable: true,
  36469. configurable: true
  36470. });
  36471. /**
  36472. * Returns the string "DirectionalLight".
  36473. */
  36474. DirectionalLight.prototype.getClassName = function () {
  36475. return "DirectionalLight";
  36476. };
  36477. /**
  36478. * Returns the integer 1.
  36479. */
  36480. DirectionalLight.prototype.getTypeID = function () {
  36481. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36482. };
  36483. /**
  36484. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36485. * Returns the DirectionalLight Shadow projection matrix.
  36486. */
  36487. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36488. if (this.shadowFrustumSize > 0) {
  36489. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36490. }
  36491. else {
  36492. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36493. }
  36494. };
  36495. /**
  36496. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36497. * Returns the DirectionalLight Shadow projection matrix.
  36498. */
  36499. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36500. var activeCamera = this.getScene().activeCamera;
  36501. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36502. };
  36503. /**
  36504. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36505. * Returns the DirectionalLight Shadow projection matrix.
  36506. */
  36507. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36508. var activeCamera = this.getScene().activeCamera;
  36509. // Check extends
  36510. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36511. var tempVector3 = BABYLON.Vector3.Zero();
  36512. this._orthoLeft = Number.MAX_VALUE;
  36513. this._orthoRight = Number.MIN_VALUE;
  36514. this._orthoTop = Number.MIN_VALUE;
  36515. this._orthoBottom = Number.MAX_VALUE;
  36516. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36517. var mesh = renderList[meshIndex];
  36518. if (!mesh) {
  36519. continue;
  36520. }
  36521. var boundingInfo = mesh.getBoundingInfo();
  36522. if (!boundingInfo) {
  36523. continue;
  36524. }
  36525. var boundingBox = boundingInfo.boundingBox;
  36526. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36527. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36528. if (tempVector3.x < this._orthoLeft)
  36529. this._orthoLeft = tempVector3.x;
  36530. if (tempVector3.y < this._orthoBottom)
  36531. this._orthoBottom = tempVector3.y;
  36532. if (tempVector3.x > this._orthoRight)
  36533. this._orthoRight = tempVector3.x;
  36534. if (tempVector3.y > this._orthoTop)
  36535. this._orthoTop = tempVector3.y;
  36536. }
  36537. }
  36538. }
  36539. var xOffset = this._orthoRight - this._orthoLeft;
  36540. var yOffset = this._orthoTop - this._orthoBottom;
  36541. 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);
  36542. };
  36543. DirectionalLight.prototype._buildUniformLayout = function () {
  36544. this._uniformBuffer.addUniform("vLightData", 4);
  36545. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36546. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36547. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36548. this._uniformBuffer.addUniform("depthValues", 2);
  36549. this._uniformBuffer.create();
  36550. };
  36551. /**
  36552. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36553. * Returns the DirectionalLight.
  36554. */
  36555. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36556. if (this.computeTransformedInformation()) {
  36557. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36558. return this;
  36559. }
  36560. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36561. return this;
  36562. };
  36563. /**
  36564. * Gets the minZ used for shadow according to both the scene and the light.
  36565. *
  36566. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36567. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36568. * @param activeCamera
  36569. */
  36570. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36571. return 1;
  36572. };
  36573. /**
  36574. * Gets the maxZ used for shadow according to both the scene and the light.
  36575. *
  36576. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36577. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36578. * @param activeCamera
  36579. */
  36580. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36581. return 1;
  36582. };
  36583. __decorate([
  36584. BABYLON.serialize()
  36585. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36586. __decorate([
  36587. BABYLON.serialize()
  36588. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36589. __decorate([
  36590. BABYLON.serialize()
  36591. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36592. return DirectionalLight;
  36593. }(BABYLON.ShadowLight));
  36594. BABYLON.DirectionalLight = DirectionalLight;
  36595. })(BABYLON || (BABYLON = {}));
  36596. //# sourceMappingURL=babylon.directionalLight.js.map
  36597. var BABYLON;
  36598. (function (BABYLON) {
  36599. var SpotLight = (function (_super) {
  36600. __extends(SpotLight, _super);
  36601. /**
  36602. * Creates a SpotLight object in the scene with the passed parameters :
  36603. * - `position` (Vector3) is the initial SpotLight position,
  36604. * - `direction` (Vector3) is the initial SpotLight direction,
  36605. * - `angle` (float, in radians) is the spot light cone angle,
  36606. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36607. * A spot light is a simply light oriented cone.
  36608. * It can cast shadows.
  36609. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36610. */
  36611. function SpotLight(name, position, direction, angle, exponent, scene) {
  36612. var _this = _super.call(this, name, scene) || this;
  36613. _this.position = position;
  36614. _this.direction = direction;
  36615. _this.angle = angle;
  36616. _this.exponent = exponent;
  36617. return _this;
  36618. }
  36619. Object.defineProperty(SpotLight.prototype, "angle", {
  36620. get: function () {
  36621. return this._angle;
  36622. },
  36623. set: function (value) {
  36624. this._angle = value;
  36625. this.forceProjectionMatrixCompute();
  36626. },
  36627. enumerable: true,
  36628. configurable: true
  36629. });
  36630. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  36631. get: function () {
  36632. return this._shadowAngleScale;
  36633. },
  36634. /**
  36635. * Allows scaling the angle of the light for shadow generation only.
  36636. */
  36637. set: function (value) {
  36638. this._shadowAngleScale = value;
  36639. this.forceProjectionMatrixCompute();
  36640. },
  36641. enumerable: true,
  36642. configurable: true
  36643. });
  36644. /**
  36645. * Returns the string "SpotLight".
  36646. */
  36647. SpotLight.prototype.getClassName = function () {
  36648. return "SpotLight";
  36649. };
  36650. /**
  36651. * Returns the integer 2.
  36652. */
  36653. SpotLight.prototype.getTypeID = function () {
  36654. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36655. };
  36656. /**
  36657. * 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.
  36658. * Returns the SpotLight.
  36659. */
  36660. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36661. var activeCamera = this.getScene().activeCamera;
  36662. this._shadowAngleScale = this._shadowAngleScale || 1;
  36663. var angle = this._shadowAngleScale * this._angle;
  36664. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36665. };
  36666. SpotLight.prototype._buildUniformLayout = function () {
  36667. this._uniformBuffer.addUniform("vLightData", 4);
  36668. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36669. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36670. this._uniformBuffer.addUniform("vLightDirection", 3);
  36671. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36672. this._uniformBuffer.addUniform("depthValues", 2);
  36673. this._uniformBuffer.create();
  36674. };
  36675. /**
  36676. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36677. * Return the SpotLight.
  36678. */
  36679. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36680. var normalizeDirection;
  36681. if (this.computeTransformedInformation()) {
  36682. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36683. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36684. }
  36685. else {
  36686. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36687. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36688. }
  36689. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36690. return this;
  36691. };
  36692. __decorate([
  36693. BABYLON.serialize()
  36694. ], SpotLight.prototype, "angle", null);
  36695. __decorate([
  36696. BABYLON.serialize()
  36697. /**
  36698. * Allows scaling the angle of the light for shadow generation only.
  36699. */
  36700. ], SpotLight.prototype, "shadowAngleScale", null);
  36701. __decorate([
  36702. BABYLON.serialize()
  36703. ], SpotLight.prototype, "exponent", void 0);
  36704. return SpotLight;
  36705. }(BABYLON.ShadowLight));
  36706. BABYLON.SpotLight = SpotLight;
  36707. })(BABYLON || (BABYLON = {}));
  36708. //# sourceMappingURL=babylon.spotLight.js.map
  36709. var BABYLON;
  36710. (function (BABYLON) {
  36711. var MultiMaterial = (function (_super) {
  36712. __extends(MultiMaterial, _super);
  36713. function MultiMaterial(name, scene) {
  36714. var _this = _super.call(this, name, scene, true) || this;
  36715. scene.multiMaterials.push(_this);
  36716. _this.subMaterials = new Array();
  36717. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  36718. return _this;
  36719. }
  36720. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  36721. get: function () {
  36722. return this._subMaterials;
  36723. },
  36724. set: function (value) {
  36725. this._subMaterials = value;
  36726. this._hookArray(value);
  36727. },
  36728. enumerable: true,
  36729. configurable: true
  36730. });
  36731. MultiMaterial.prototype._hookArray = function (array) {
  36732. var _this = this;
  36733. var oldPush = array.push;
  36734. array.push = function () {
  36735. var items = [];
  36736. for (var _i = 0; _i < arguments.length; _i++) {
  36737. items[_i] = arguments[_i];
  36738. }
  36739. var result = oldPush.apply(array, items);
  36740. _this._markAllSubMeshesAsTexturesDirty();
  36741. return result;
  36742. };
  36743. var oldSplice = array.splice;
  36744. array.splice = function (index, deleteCount) {
  36745. var deleted = oldSplice.apply(array, [index, deleteCount]);
  36746. _this._markAllSubMeshesAsTexturesDirty();
  36747. return deleted;
  36748. };
  36749. };
  36750. // Properties
  36751. MultiMaterial.prototype.getSubMaterial = function (index) {
  36752. if (index < 0 || index >= this.subMaterials.length) {
  36753. return this.getScene().defaultMaterial;
  36754. }
  36755. return this.subMaterials[index];
  36756. };
  36757. MultiMaterial.prototype.getActiveTextures = function () {
  36758. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  36759. var _a;
  36760. };
  36761. // Methods
  36762. MultiMaterial.prototype.getClassName = function () {
  36763. return "MultiMaterial";
  36764. };
  36765. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36766. for (var index = 0; index < this.subMaterials.length; index++) {
  36767. var subMaterial = this.subMaterials[index];
  36768. if (subMaterial) {
  36769. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  36770. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  36771. return false;
  36772. }
  36773. continue;
  36774. }
  36775. if (!this.subMaterials[index].isReady(mesh)) {
  36776. return false;
  36777. }
  36778. }
  36779. }
  36780. return true;
  36781. };
  36782. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  36783. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  36784. for (var index = 0; index < this.subMaterials.length; index++) {
  36785. var subMaterial = null;
  36786. if (cloneChildren) {
  36787. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  36788. }
  36789. else {
  36790. subMaterial = this.subMaterials[index];
  36791. }
  36792. newMultiMaterial.subMaterials.push(subMaterial);
  36793. }
  36794. return newMultiMaterial;
  36795. };
  36796. MultiMaterial.prototype.serialize = function () {
  36797. var serializationObject = {};
  36798. serializationObject.name = this.name;
  36799. serializationObject.id = this.id;
  36800. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36801. serializationObject.materials = [];
  36802. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  36803. var subMat = this.subMaterials[matIndex];
  36804. if (subMat) {
  36805. serializationObject.materials.push(subMat.id);
  36806. }
  36807. else {
  36808. serializationObject.materials.push(null);
  36809. }
  36810. }
  36811. return serializationObject;
  36812. };
  36813. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36814. var scene = this.getScene();
  36815. if (!scene) {
  36816. return;
  36817. }
  36818. var index = scene.multiMaterials.indexOf(this);
  36819. if (index >= 0) {
  36820. scene.multiMaterials.splice(index, 1);
  36821. }
  36822. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36823. };
  36824. return MultiMaterial;
  36825. }(BABYLON.Material));
  36826. BABYLON.MultiMaterial = MultiMaterial;
  36827. })(BABYLON || (BABYLON = {}));
  36828. //# sourceMappingURL=babylon.multiMaterial.js.map
  36829. var BABYLON;
  36830. (function (BABYLON) {
  36831. var PBRMaterialDefines = (function (_super) {
  36832. __extends(PBRMaterialDefines, _super);
  36833. function PBRMaterialDefines() {
  36834. var _this = _super.call(this) || this;
  36835. _this.PBR = true;
  36836. _this.MAINUV1 = false;
  36837. _this.MAINUV2 = false;
  36838. _this.UV1 = false;
  36839. _this.UV2 = false;
  36840. _this.ALBEDO = false;
  36841. _this.ALBEDODIRECTUV = 0;
  36842. _this.VERTEXCOLOR = false;
  36843. _this.AMBIENT = false;
  36844. _this.AMBIENTDIRECTUV = 0;
  36845. _this.AMBIENTINGRAYSCALE = false;
  36846. _this.OPACITY = false;
  36847. _this.VERTEXALPHA = false;
  36848. _this.OPACITYDIRECTUV = 0;
  36849. _this.OPACITYRGB = false;
  36850. _this.ALPHATEST = false;
  36851. _this.ALPHABLEND = false;
  36852. _this.ALPHAFROMALBEDO = false;
  36853. _this.ALPHATESTVALUE = 0.5;
  36854. _this.SPECULAROVERALPHA = false;
  36855. _this.RADIANCEOVERALPHA = false;
  36856. _this.ALPHAFRESNEL = false;
  36857. _this.PREMULTIPLYALPHA = false;
  36858. _this.EMISSIVE = false;
  36859. _this.EMISSIVEDIRECTUV = 0;
  36860. _this.REFLECTIVITY = false;
  36861. _this.REFLECTIVITYDIRECTUV = 0;
  36862. _this.SPECULARTERM = false;
  36863. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36864. _this.MICROSURFACEAUTOMATIC = false;
  36865. _this.LODBASEDMICROSFURACE = false;
  36866. _this.MICROSURFACEMAP = false;
  36867. _this.MICROSURFACEMAPDIRECTUV = 0;
  36868. _this.METALLICWORKFLOW = false;
  36869. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36870. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36871. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36872. _this.AOSTOREINMETALMAPRED = false;
  36873. _this.ENVIRONMENTBRDF = false;
  36874. _this.NORMAL = false;
  36875. _this.TANGENT = false;
  36876. _this.BUMP = false;
  36877. _this.BUMPDIRECTUV = 0;
  36878. _this.PARALLAX = false;
  36879. _this.PARALLAXOCCLUSION = false;
  36880. _this.NORMALXYSCALE = true;
  36881. _this.LIGHTMAP = false;
  36882. _this.LIGHTMAPDIRECTUV = 0;
  36883. _this.USELIGHTMAPASSHADOWMAP = false;
  36884. _this.REFLECTION = false;
  36885. _this.REFLECTIONMAP_3D = false;
  36886. _this.REFLECTIONMAP_SPHERICAL = false;
  36887. _this.REFLECTIONMAP_PLANAR = false;
  36888. _this.REFLECTIONMAP_CUBIC = false;
  36889. _this.REFLECTIONMAP_PROJECTION = false;
  36890. _this.REFLECTIONMAP_SKYBOX = false;
  36891. _this.REFLECTIONMAP_EXPLICIT = false;
  36892. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36893. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36894. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36895. _this.INVERTCUBICMAP = false;
  36896. _this.USESPHERICALFROMREFLECTIONMAP = false;
  36897. _this.USESPHERICALINFRAGMENT = false;
  36898. _this.REFLECTIONMAP_OPPOSITEZ = false;
  36899. _this.LODINREFLECTIONALPHA = false;
  36900. _this.GAMMAREFLECTION = false;
  36901. _this.REFRACTION = false;
  36902. _this.REFRACTIONMAP_3D = false;
  36903. _this.REFRACTIONMAP_OPPOSITEZ = false;
  36904. _this.LODINREFRACTIONALPHA = false;
  36905. _this.GAMMAREFRACTION = false;
  36906. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  36907. _this.INSTANCES = false;
  36908. _this.NUM_BONE_INFLUENCERS = 0;
  36909. _this.BonesPerMesh = 0;
  36910. _this.MORPHTARGETS = false;
  36911. _this.MORPHTARGETS_NORMAL = false;
  36912. _this.MORPHTARGETS_TANGENT = false;
  36913. _this.NUM_MORPH_INFLUENCERS = 0;
  36914. _this.IMAGEPROCESSING = false;
  36915. _this.VIGNETTE = false;
  36916. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36917. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36918. _this.TONEMAPPING = false;
  36919. _this.CONTRAST = false;
  36920. _this.COLORCURVES = false;
  36921. _this.COLORGRADING = false;
  36922. _this.SAMPLER3DGREENDEPTH = false;
  36923. _this.SAMPLER3DBGRMAP = false;
  36924. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36925. _this.EXPOSURE = false;
  36926. _this.USEPHYSICALLIGHTFALLOFF = false;
  36927. _this.TWOSIDEDLIGHTING = false;
  36928. _this.SHADOWFLOAT = false;
  36929. _this.USERIGHTHANDEDSYSTEM = false;
  36930. _this.CLIPPLANE = false;
  36931. _this.POINTSIZE = false;
  36932. _this.FOG = false;
  36933. _this.LOGARITHMICDEPTH = false;
  36934. _this.FORCENORMALFORWARD = false;
  36935. _this.rebuild();
  36936. return _this;
  36937. }
  36938. PBRMaterialDefines.prototype.reset = function () {
  36939. _super.prototype.reset.call(this);
  36940. this.ALPHATESTVALUE = 0.5;
  36941. this.PBR = true;
  36942. };
  36943. return PBRMaterialDefines;
  36944. }(BABYLON.MaterialDefines));
  36945. /**
  36946. * The Physically based material base class of BJS.
  36947. *
  36948. * This offers the main features of a standard PBR material.
  36949. * For more information, please refer to the documentation :
  36950. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36951. */
  36952. var PBRBaseMaterial = (function (_super) {
  36953. __extends(PBRBaseMaterial, _super);
  36954. /**
  36955. * Instantiates a new PBRMaterial instance.
  36956. *
  36957. * @param name The material name
  36958. * @param scene The scene the material will be use in.
  36959. */
  36960. function PBRBaseMaterial(name, scene) {
  36961. var _this = _super.call(this, name, scene) || this;
  36962. /**
  36963. * Intensity of the direct lights e.g. the four lights available in your scene.
  36964. * This impacts both the direct diffuse and specular highlights.
  36965. */
  36966. _this._directIntensity = 1.0;
  36967. /**
  36968. * Intensity of the emissive part of the material.
  36969. * This helps controlling the emissive effect without modifying the emissive color.
  36970. */
  36971. _this._emissiveIntensity = 1.0;
  36972. /**
  36973. * Intensity of the environment e.g. how much the environment will light the object
  36974. * either through harmonics for rough material or through the refelction for shiny ones.
  36975. */
  36976. _this._environmentIntensity = 1.0;
  36977. /**
  36978. * This is a special control allowing the reduction of the specular highlights coming from the
  36979. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36980. */
  36981. _this._specularIntensity = 1.0;
  36982. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  36983. /**
  36984. * Debug Control allowing disabling the bump map on this material.
  36985. */
  36986. _this._disableBumpMap = false;
  36987. /**
  36988. * AKA Occlusion Texture Intensity in other nomenclature.
  36989. */
  36990. _this._ambientTextureStrength = 1.0;
  36991. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  36992. /**
  36993. * AKA Diffuse Color in other nomenclature.
  36994. */
  36995. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  36996. /**
  36997. * AKA Specular Color in other nomenclature.
  36998. */
  36999. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37000. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  37001. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  37002. /**
  37003. * AKA Glossiness in other nomenclature.
  37004. */
  37005. _this._microSurface = 0.9;
  37006. /**
  37007. * source material index of refraction (IOR)' / 'destination material IOR.
  37008. */
  37009. _this._indexOfRefraction = 0.66;
  37010. /**
  37011. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37012. */
  37013. _this._invertRefractionY = false;
  37014. /**
  37015. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37016. * Materials half opaque for instance using refraction could benefit from this control.
  37017. */
  37018. _this._linkRefractionWithTransparency = false;
  37019. _this._useLightmapAsShadowmap = false;
  37020. /**
  37021. * Specifies that the alpha is coming form the albedo channel alpha channel.
  37022. */
  37023. _this._useAlphaFromAlbedoTexture = false;
  37024. /**
  37025. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37026. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37027. */
  37028. _this._useSpecularOverAlpha = true;
  37029. /**
  37030. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37031. */
  37032. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  37033. /**
  37034. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37035. */
  37036. _this._useRoughnessFromMetallicTextureAlpha = true;
  37037. /**
  37038. * Specifies if the metallic texture contains the roughness information in its green channel.
  37039. */
  37040. _this._useRoughnessFromMetallicTextureGreen = false;
  37041. /**
  37042. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37043. */
  37044. _this._useMetallnessFromMetallicTextureBlue = false;
  37045. /**
  37046. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37047. */
  37048. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  37049. /**
  37050. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37051. */
  37052. _this._useAmbientInGrayScale = false;
  37053. /**
  37054. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37055. * The material will try to infer what glossiness each pixel should be.
  37056. */
  37057. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  37058. /**
  37059. * BJS is using an harcoded light falloff based on a manually sets up range.
  37060. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37061. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37062. */
  37063. _this._usePhysicalLightFalloff = true;
  37064. /**
  37065. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37066. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37067. */
  37068. _this._useRadianceOverAlpha = true;
  37069. /**
  37070. * Allows using the bump map in parallax mode.
  37071. */
  37072. _this._useParallax = false;
  37073. /**
  37074. * Allows using the bump map in parallax occlusion mode.
  37075. */
  37076. _this._useParallaxOcclusion = false;
  37077. /**
  37078. * Controls the scale bias of the parallax mode.
  37079. */
  37080. _this._parallaxScaleBias = 0.05;
  37081. /**
  37082. * If sets to true, disables all the lights affecting the material.
  37083. */
  37084. _this._disableLighting = false;
  37085. /**
  37086. * Number of Simultaneous lights allowed on the material.
  37087. */
  37088. _this._maxSimultaneousLights = 4;
  37089. /**
  37090. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  37091. */
  37092. _this._invertNormalMapX = false;
  37093. /**
  37094. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  37095. */
  37096. _this._invertNormalMapY = false;
  37097. /**
  37098. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37099. */
  37100. _this._twoSidedLighting = false;
  37101. /**
  37102. * Defines the alpha limits in alpha test mode.
  37103. */
  37104. _this._alphaCutOff = 0.4;
  37105. /**
  37106. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37107. */
  37108. _this._forceAlphaTest = false;
  37109. /**
  37110. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  37111. * in your scene composition.
  37112. */
  37113. _this._preMultiplyAlpha = false;
  37114. /**
  37115. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37116. * And/Or occlude the blended part.
  37117. */
  37118. _this._useAlphaFresnel = false;
  37119. /**
  37120. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  37121. * from cos thetav and roughness:
  37122. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  37123. */
  37124. _this._environmentBRDFTexture = null;
  37125. /**
  37126. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37127. */
  37128. _this._forceIrradianceInFragment = false;
  37129. /**
  37130. * Force normal to face away from face.
  37131. * (Temporary internal fix to remove before 3.1)
  37132. */
  37133. _this._forceNormalForward = false;
  37134. _this._renderTargets = new BABYLON.SmartArray(16);
  37135. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  37136. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  37137. _this._tempColor = new BABYLON.Color3();
  37138. // Setup the default processing configuration to the scene.
  37139. _this._attachImageProcessingConfiguration(null);
  37140. _this.getRenderTargetTextures = function () {
  37141. _this._renderTargets.reset();
  37142. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  37143. _this._renderTargets.push(_this._reflectionTexture);
  37144. }
  37145. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  37146. _this._renderTargets.push(_this._refractionTexture);
  37147. }
  37148. return _this._renderTargets;
  37149. };
  37150. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37151. return _this;
  37152. }
  37153. /**
  37154. * Attaches a new image processing configuration to the PBR Material.
  37155. * @param configuration
  37156. */
  37157. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  37158. var _this = this;
  37159. if (configuration === this._imageProcessingConfiguration) {
  37160. return;
  37161. }
  37162. // Detaches observer.
  37163. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37164. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37165. }
  37166. // Pick the scene configuration if needed.
  37167. if (!configuration) {
  37168. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  37169. }
  37170. else {
  37171. this._imageProcessingConfiguration = configuration;
  37172. }
  37173. // Attaches observer.
  37174. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  37175. _this._markAllSubMeshesAsImageProcessingDirty();
  37176. });
  37177. };
  37178. PBRBaseMaterial.prototype.getClassName = function () {
  37179. return "PBRBaseMaterial";
  37180. };
  37181. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  37182. get: function () {
  37183. return this._useLogarithmicDepth;
  37184. },
  37185. set: function (value) {
  37186. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37187. },
  37188. enumerable: true,
  37189. configurable: true
  37190. });
  37191. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  37192. if (this._linkRefractionWithTransparency) {
  37193. return false;
  37194. }
  37195. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  37196. };
  37197. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  37198. if (this._forceAlphaTest) {
  37199. return true;
  37200. }
  37201. if (this._linkRefractionWithTransparency) {
  37202. return false;
  37203. }
  37204. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  37205. };
  37206. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  37207. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  37208. };
  37209. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  37210. return this._albedoTexture;
  37211. };
  37212. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37213. if (this.isFrozen) {
  37214. if (this._wasPreviouslyReady) {
  37215. return true;
  37216. }
  37217. }
  37218. if (!subMesh._materialDefines) {
  37219. subMesh._materialDefines = new PBRMaterialDefines();
  37220. }
  37221. var scene = this.getScene();
  37222. var defines = subMesh._materialDefines;
  37223. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37224. if (defines._renderId === scene.getRenderId()) {
  37225. return true;
  37226. }
  37227. }
  37228. var engine = scene.getEngine();
  37229. // Lights
  37230. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37231. defines._needNormals = true;
  37232. // Textures
  37233. if (defines._areTexturesDirty) {
  37234. defines._needUVs = false;
  37235. if (scene.texturesEnabled) {
  37236. if (scene.getEngine().getCaps().textureLOD) {
  37237. defines.LODBASEDMICROSFURACE = true;
  37238. }
  37239. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37240. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  37241. return false;
  37242. }
  37243. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  37244. }
  37245. else {
  37246. defines.ALBEDO = false;
  37247. }
  37248. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37249. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37250. return false;
  37251. }
  37252. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37253. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  37254. }
  37255. else {
  37256. defines.AMBIENT = false;
  37257. }
  37258. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37259. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37260. return false;
  37261. }
  37262. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37263. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37264. }
  37265. else {
  37266. defines.OPACITY = false;
  37267. }
  37268. var reflectionTexture = this._getReflectionTexture();
  37269. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37270. if (!reflectionTexture.isReadyOrNotBlocking()) {
  37271. return false;
  37272. }
  37273. defines.REFLECTION = true;
  37274. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  37275. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  37276. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37277. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  37278. defines.INVERTCUBICMAP = true;
  37279. }
  37280. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  37281. switch (reflectionTexture.coordinatesMode) {
  37282. case BABYLON.Texture.CUBIC_MODE:
  37283. case BABYLON.Texture.INVCUBIC_MODE:
  37284. defines.REFLECTIONMAP_CUBIC = true;
  37285. break;
  37286. case BABYLON.Texture.EXPLICIT_MODE:
  37287. defines.REFLECTIONMAP_EXPLICIT = true;
  37288. break;
  37289. case BABYLON.Texture.PLANAR_MODE:
  37290. defines.REFLECTIONMAP_PLANAR = true;
  37291. break;
  37292. case BABYLON.Texture.PROJECTION_MODE:
  37293. defines.REFLECTIONMAP_PROJECTION = true;
  37294. break;
  37295. case BABYLON.Texture.SKYBOX_MODE:
  37296. defines.REFLECTIONMAP_SKYBOX = true;
  37297. break;
  37298. case BABYLON.Texture.SPHERICAL_MODE:
  37299. defines.REFLECTIONMAP_SPHERICAL = true;
  37300. break;
  37301. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37302. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  37303. break;
  37304. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37305. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  37306. break;
  37307. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37308. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  37309. break;
  37310. }
  37311. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37312. if (reflectionTexture.sphericalPolynomial) {
  37313. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37314. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37315. defines.USESPHERICALINFRAGMENT = true;
  37316. }
  37317. }
  37318. }
  37319. }
  37320. else {
  37321. defines.REFLECTION = false;
  37322. defines.REFLECTIONMAP_3D = false;
  37323. defines.REFLECTIONMAP_SPHERICAL = false;
  37324. defines.REFLECTIONMAP_PLANAR = false;
  37325. defines.REFLECTIONMAP_CUBIC = false;
  37326. defines.REFLECTIONMAP_PROJECTION = false;
  37327. defines.REFLECTIONMAP_SKYBOX = false;
  37328. defines.REFLECTIONMAP_EXPLICIT = false;
  37329. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37330. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37331. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37332. defines.INVERTCUBICMAP = false;
  37333. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37334. defines.USESPHERICALINFRAGMENT = false;
  37335. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37336. defines.LODINREFLECTIONALPHA = false;
  37337. defines.GAMMAREFLECTION = false;
  37338. }
  37339. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37340. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37341. return false;
  37342. }
  37343. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37344. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37345. }
  37346. else {
  37347. defines.LIGHTMAP = false;
  37348. }
  37349. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37350. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37351. return false;
  37352. }
  37353. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37354. }
  37355. else {
  37356. defines.EMISSIVE = false;
  37357. }
  37358. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37359. if (this._metallicTexture) {
  37360. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37361. return false;
  37362. }
  37363. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37364. defines.METALLICWORKFLOW = true;
  37365. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37366. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37367. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37368. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37369. }
  37370. else if (this._reflectivityTexture) {
  37371. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37372. return false;
  37373. }
  37374. defines.METALLICWORKFLOW = false;
  37375. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37376. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37377. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37378. }
  37379. else {
  37380. defines.METALLICWORKFLOW = false;
  37381. defines.REFLECTIVITY = false;
  37382. }
  37383. if (this._microSurfaceTexture) {
  37384. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37385. return false;
  37386. }
  37387. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37388. }
  37389. else {
  37390. defines.MICROSURFACEMAP = false;
  37391. }
  37392. }
  37393. else {
  37394. defines.REFLECTIVITY = false;
  37395. defines.MICROSURFACEMAP = false;
  37396. }
  37397. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37398. // Bump texure can not be none blocking.
  37399. if (!this._bumpTexture.isReady()) {
  37400. return false;
  37401. }
  37402. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37403. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37404. defines.PARALLAX = true;
  37405. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  37406. }
  37407. else {
  37408. defines.PARALLAX = false;
  37409. }
  37410. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  37411. }
  37412. else {
  37413. defines.BUMP = false;
  37414. }
  37415. var refractionTexture = this._getRefractionTexture();
  37416. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37417. if (!refractionTexture.isReadyOrNotBlocking()) {
  37418. return false;
  37419. }
  37420. defines.REFRACTION = true;
  37421. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  37422. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  37423. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  37424. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37425. if (this._linkRefractionWithTransparency) {
  37426. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  37427. }
  37428. }
  37429. else {
  37430. defines.REFRACTION = false;
  37431. }
  37432. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37433. // This is blocking.
  37434. if (!this._environmentBRDFTexture.isReady()) {
  37435. return false;
  37436. }
  37437. defines.ENVIRONMENTBRDF = true;
  37438. }
  37439. if (this._shouldUseAlphaFromAlbedoTexture()) {
  37440. defines.ALPHAFROMALBEDO = true;
  37441. }
  37442. }
  37443. if (this._useSpecularOverAlpha) {
  37444. defines.SPECULAROVERALPHA = true;
  37445. }
  37446. if (this._usePhysicalLightFalloff) {
  37447. defines.USEPHYSICALLIGHTFALLOFF = true;
  37448. }
  37449. if (this._useRadianceOverAlpha) {
  37450. defines.RADIANCEOVERALPHA = true;
  37451. }
  37452. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  37453. defines.METALLICWORKFLOW = true;
  37454. }
  37455. if (!this.backFaceCulling && this._twoSidedLighting) {
  37456. defines.TWOSIDEDLIGHTING = true;
  37457. }
  37458. defines.ALPHATESTVALUE = this._alphaCutOff;
  37459. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  37460. defines.ALPHABLEND = this.needAlphaBlending();
  37461. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  37462. }
  37463. if (defines._areImageProcessingDirty) {
  37464. if (!this._imageProcessingConfiguration.isReady()) {
  37465. return false;
  37466. }
  37467. this._imageProcessingConfiguration.prepareDefines(defines);
  37468. }
  37469. defines.FORCENORMALFORWARD = this._forceNormalForward;
  37470. // Misc.
  37471. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  37472. // Values that need to be evaluated on every frame
  37473. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  37474. // Attribs
  37475. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  37476. if (mesh) {
  37477. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37478. mesh.createNormals(true);
  37479. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  37480. }
  37481. }
  37482. }
  37483. // Get correct effect
  37484. if (defines.isDirty) {
  37485. defines.markAsProcessed();
  37486. scene.resetCachedMaterial();
  37487. // Fallbacks
  37488. var fallbacks = new BABYLON.EffectFallbacks();
  37489. if (defines.ENVIRONMENTBRDF) {
  37490. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  37491. }
  37492. if (defines.REFLECTION) {
  37493. fallbacks.addFallback(0, "REFLECTION");
  37494. }
  37495. if (defines.REFRACTION) {
  37496. fallbacks.addFallback(0, "REFRACTION");
  37497. }
  37498. if (defines.REFLECTIVITY) {
  37499. fallbacks.addFallback(0, "REFLECTIVITY");
  37500. }
  37501. if (defines.BUMP) {
  37502. fallbacks.addFallback(0, "BUMP");
  37503. }
  37504. if (defines.PARALLAX) {
  37505. fallbacks.addFallback(1, "PARALLAX");
  37506. }
  37507. if (defines.PARALLAXOCCLUSION) {
  37508. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37509. }
  37510. if (defines.SPECULAROVERALPHA) {
  37511. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37512. }
  37513. if (defines.FOG) {
  37514. fallbacks.addFallback(1, "FOG");
  37515. }
  37516. if (defines.POINTSIZE) {
  37517. fallbacks.addFallback(0, "POINTSIZE");
  37518. }
  37519. if (defines.LOGARITHMICDEPTH) {
  37520. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37521. }
  37522. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37523. if (defines.SPECULARTERM) {
  37524. fallbacks.addFallback(0, "SPECULARTERM");
  37525. }
  37526. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37527. fallbacks.addCPUSkinningFallback(0, mesh);
  37528. }
  37529. //Attributes
  37530. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37531. if (defines.NORMAL) {
  37532. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37533. }
  37534. if (defines.TANGENT) {
  37535. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37536. }
  37537. if (defines.UV1) {
  37538. attribs.push(BABYLON.VertexBuffer.UVKind);
  37539. }
  37540. if (defines.UV2) {
  37541. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37542. }
  37543. if (defines.VERTEXCOLOR) {
  37544. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37545. }
  37546. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37547. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37548. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37549. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  37550. "vFogInfos", "vFogColor", "pointSize",
  37551. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37552. "mBones",
  37553. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37554. "vLightingIntensity",
  37555. "logarithmicDepthConstant",
  37556. "vSphericalX", "vSphericalY", "vSphericalZ",
  37557. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  37558. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  37559. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  37560. "vNormalReoderParams"
  37561. ];
  37562. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  37563. "bumpSampler", "lightmapSampler", "opacitySampler",
  37564. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  37565. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  37566. "microSurfaceSampler", "environmentBrdfSampler"];
  37567. var uniformBuffers = ["Material", "Scene"];
  37568. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37569. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37570. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37571. uniformsNames: uniforms,
  37572. uniformBuffersNames: uniformBuffers,
  37573. samplers: samplers,
  37574. defines: defines,
  37575. maxSimultaneousLights: this._maxSimultaneousLights
  37576. });
  37577. var onCompiled = function (effect) {
  37578. if (this.onCompiled) {
  37579. this.onCompiled(effect);
  37580. }
  37581. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  37582. }.bind(this);
  37583. var join = defines.toString();
  37584. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  37585. attributes: attribs,
  37586. uniformsNames: uniforms,
  37587. uniformBuffersNames: uniformBuffers,
  37588. samplers: samplers,
  37589. defines: join,
  37590. fallbacks: fallbacks,
  37591. onCompiled: onCompiled,
  37592. onError: this.onError,
  37593. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37594. }, engine), defines);
  37595. this.buildUniformLayout();
  37596. }
  37597. if (!subMesh.effect.isReady()) {
  37598. return false;
  37599. }
  37600. defines._renderId = scene.getRenderId();
  37601. this._wasPreviouslyReady = true;
  37602. return true;
  37603. };
  37604. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37605. // Order is important !
  37606. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37607. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37608. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37609. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37610. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37611. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37612. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37613. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37614. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37615. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37616. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37617. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37618. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37619. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37620. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37621. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37622. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37623. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37624. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  37625. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37626. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37627. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37628. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37629. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37630. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37631. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37632. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37633. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37634. this._uniformBuffer.addUniform("pointSize", 1);
  37635. this._uniformBuffer.create();
  37636. };
  37637. PBRBaseMaterial.prototype.unbind = function () {
  37638. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37639. this._uniformBuffer.setTexture("reflectionSampler", null);
  37640. }
  37641. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37642. this._uniformBuffer.setTexture("refractionSampler", null);
  37643. }
  37644. _super.prototype.unbind.call(this);
  37645. };
  37646. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37647. this._activeEffect.setMatrix("world", world);
  37648. };
  37649. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37650. var scene = this.getScene();
  37651. var defines = subMesh._materialDefines;
  37652. if (!defines) {
  37653. return;
  37654. }
  37655. var effect = subMesh.effect;
  37656. this._activeEffect = effect;
  37657. // Matrices
  37658. this.bindOnlyWorldMatrix(world);
  37659. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37660. // Bones
  37661. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37662. if (mustRebind) {
  37663. this._uniformBuffer.bindToEffect(effect, "Material");
  37664. this.bindViewProjection(effect);
  37665. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37666. // Texture uniforms
  37667. if (scene.texturesEnabled) {
  37668. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37669. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37670. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37671. }
  37672. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37673. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37674. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37675. }
  37676. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37677. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37678. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37679. }
  37680. var reflectionTexture = this._getReflectionTexture();
  37681. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37682. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37683. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37684. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37685. var polynomials = reflectionTexture.sphericalPolynomial;
  37686. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37687. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37688. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37689. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37690. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37691. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37692. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37693. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37694. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37695. }
  37696. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37697. }
  37698. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37699. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37700. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37701. }
  37702. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37703. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37704. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37705. }
  37706. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37707. if (this._metallicTexture) {
  37708. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37709. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37710. }
  37711. else if (this._reflectivityTexture) {
  37712. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37713. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37714. }
  37715. if (this._microSurfaceTexture) {
  37716. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37717. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37718. }
  37719. }
  37720. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37721. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37722. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37723. if (scene._mirroredCameraPosition) {
  37724. 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);
  37725. }
  37726. else {
  37727. 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);
  37728. }
  37729. }
  37730. var refractionTexture = this._getRefractionTexture();
  37731. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37732. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37733. var depth = 1.0;
  37734. if (!refractionTexture.isCube) {
  37735. if (refractionTexture.depth) {
  37736. depth = refractionTexture.depth;
  37737. }
  37738. }
  37739. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37740. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37741. }
  37742. }
  37743. // Point size
  37744. if (this.pointsCloud) {
  37745. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37746. }
  37747. // Colors
  37748. if (defines.METALLICWORKFLOW) {
  37749. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37750. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37751. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37752. }
  37753. else {
  37754. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37755. }
  37756. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37757. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37758. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37759. // Misc
  37760. this._lightingInfos.x = this._directIntensity;
  37761. this._lightingInfos.y = this._emissiveIntensity;
  37762. this._lightingInfos.z = this._environmentIntensity;
  37763. this._lightingInfos.w = this._specularIntensity;
  37764. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37765. }
  37766. // Textures
  37767. if (scene.texturesEnabled) {
  37768. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37769. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37770. }
  37771. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37772. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37773. }
  37774. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37775. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37776. }
  37777. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37778. if (defines.LODBASEDMICROSFURACE) {
  37779. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37780. }
  37781. else {
  37782. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37783. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37784. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37785. }
  37786. }
  37787. if (defines.ENVIRONMENTBRDF) {
  37788. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37789. }
  37790. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37791. if (defines.LODBASEDMICROSFURACE) {
  37792. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37793. }
  37794. else {
  37795. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37796. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37797. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37798. }
  37799. }
  37800. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37801. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37802. }
  37803. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37804. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37805. }
  37806. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37807. if (this._metallicTexture) {
  37808. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37809. }
  37810. else if (this._reflectivityTexture) {
  37811. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37812. }
  37813. if (this._microSurfaceTexture) {
  37814. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37815. }
  37816. }
  37817. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37818. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37819. }
  37820. }
  37821. // Clip plane
  37822. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37823. // Colors
  37824. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37825. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  37826. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  37827. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37828. }
  37829. if (mustRebind || !this.isFrozen) {
  37830. // Lights
  37831. if (scene.lightsEnabled && !this._disableLighting) {
  37832. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37833. }
  37834. // View
  37835. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37836. this.bindView(effect);
  37837. }
  37838. // Fog
  37839. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37840. // Morph targets
  37841. if (defines.NUM_MORPH_INFLUENCERS) {
  37842. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37843. }
  37844. // image processing
  37845. this._imageProcessingConfiguration.bind(this._activeEffect);
  37846. // Log. depth
  37847. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37848. }
  37849. this._uniformBuffer.update();
  37850. this._afterBind(mesh);
  37851. scene = null;
  37852. };
  37853. PBRBaseMaterial.prototype.getAnimatables = function () {
  37854. var results = [];
  37855. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37856. results.push(this._albedoTexture);
  37857. }
  37858. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37859. results.push(this._ambientTexture);
  37860. }
  37861. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37862. results.push(this._opacityTexture);
  37863. }
  37864. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37865. results.push(this._reflectionTexture);
  37866. }
  37867. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37868. results.push(this._emissiveTexture);
  37869. }
  37870. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37871. results.push(this._metallicTexture);
  37872. }
  37873. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37874. results.push(this._reflectivityTexture);
  37875. }
  37876. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37877. results.push(this._bumpTexture);
  37878. }
  37879. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37880. results.push(this._lightmapTexture);
  37881. }
  37882. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37883. results.push(this._refractionTexture);
  37884. }
  37885. return results;
  37886. };
  37887. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  37888. if (this._reflectionTexture) {
  37889. return this._reflectionTexture;
  37890. }
  37891. return this.getScene().environmentTexture;
  37892. };
  37893. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  37894. if (this._refractionTexture) {
  37895. return this._refractionTexture;
  37896. }
  37897. if (this._linkRefractionWithTransparency) {
  37898. return this.getScene().environmentTexture;
  37899. }
  37900. return null;
  37901. };
  37902. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37903. if (forceDisposeTextures) {
  37904. if (this._albedoTexture) {
  37905. this._albedoTexture.dispose();
  37906. }
  37907. if (this._ambientTexture) {
  37908. this._ambientTexture.dispose();
  37909. }
  37910. if (this._opacityTexture) {
  37911. this._opacityTexture.dispose();
  37912. }
  37913. if (this._reflectionTexture) {
  37914. this._reflectionTexture.dispose();
  37915. }
  37916. if (this._environmentBRDFTexture) {
  37917. this._environmentBRDFTexture.dispose();
  37918. }
  37919. if (this._emissiveTexture) {
  37920. this._emissiveTexture.dispose();
  37921. }
  37922. if (this._metallicTexture) {
  37923. this._metallicTexture.dispose();
  37924. }
  37925. if (this._reflectivityTexture) {
  37926. this._reflectivityTexture.dispose();
  37927. }
  37928. if (this._bumpTexture) {
  37929. this._bumpTexture.dispose();
  37930. }
  37931. if (this._lightmapTexture) {
  37932. this._lightmapTexture.dispose();
  37933. }
  37934. if (this._refractionTexture) {
  37935. this._refractionTexture.dispose();
  37936. }
  37937. }
  37938. this._renderTargets.dispose();
  37939. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37940. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37941. }
  37942. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37943. };
  37944. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37945. __decorate([
  37946. BABYLON.serializeAsImageProcessingConfiguration()
  37947. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37948. __decorate([
  37949. BABYLON.serialize()
  37950. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37951. return PBRBaseMaterial;
  37952. }(BABYLON.PushMaterial));
  37953. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37954. })(BABYLON || (BABYLON = {}));
  37955. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37956. var BABYLON;
  37957. (function (BABYLON) {
  37958. var Internals;
  37959. (function (Internals) {
  37960. /**
  37961. * The Physically based simple base material of BJS.
  37962. *
  37963. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37964. * It is used as the base class for both the specGloss and metalRough conventions.
  37965. */
  37966. var PBRBaseSimpleMaterial = (function (_super) {
  37967. __extends(PBRBaseSimpleMaterial, _super);
  37968. /**
  37969. * Instantiates a new PBRMaterial instance.
  37970. *
  37971. * @param name The material name
  37972. * @param scene The scene the material will be use in.
  37973. */
  37974. function PBRBaseSimpleMaterial(name, scene) {
  37975. var _this = _super.call(this, name, scene) || this;
  37976. /**
  37977. * Number of Simultaneous lights allowed on the material.
  37978. */
  37979. _this.maxSimultaneousLights = 4;
  37980. /**
  37981. * If sets to true, disables all the lights affecting the material.
  37982. */
  37983. _this.disableLighting = false;
  37984. /**
  37985. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37986. */
  37987. _this.invertNormalMapX = false;
  37988. /**
  37989. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37990. */
  37991. _this.invertNormalMapY = false;
  37992. /**
  37993. * Emissivie color used to self-illuminate the model.
  37994. */
  37995. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37996. /**
  37997. * Occlusion Channel Strenght.
  37998. */
  37999. _this.occlusionStrength = 1.0;
  38000. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38001. _this._useAmbientInGrayScale = true;
  38002. return _this;
  38003. }
  38004. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  38005. /**
  38006. * Gets the current transparency mode.
  38007. */
  38008. get: function () {
  38009. return this._transparencyMode;
  38010. },
  38011. /**
  38012. * Sets the transparency mode of the material.
  38013. */
  38014. set: function (value) {
  38015. if (this._transparencyMode === value) {
  38016. return;
  38017. }
  38018. this._transparencyMode = value;
  38019. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  38020. this._forceAlphaTest = true;
  38021. }
  38022. else {
  38023. this._forceAlphaTest = false;
  38024. }
  38025. this._markAllSubMeshesAsTexturesDirty();
  38026. },
  38027. enumerable: true,
  38028. configurable: true
  38029. });
  38030. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  38031. /**
  38032. * Gets the current double sided mode.
  38033. */
  38034. get: function () {
  38035. return this._twoSidedLighting;
  38036. },
  38037. /**
  38038. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38039. */
  38040. set: function (value) {
  38041. if (this._twoSidedLighting === value) {
  38042. return;
  38043. }
  38044. this._twoSidedLighting = value;
  38045. this.backFaceCulling = !value;
  38046. this._markAllSubMeshesAsTexturesDirty();
  38047. },
  38048. enumerable: true,
  38049. configurable: true
  38050. });
  38051. /**
  38052. * Specifies wether or not the alpha value of the albedo texture should be used.
  38053. */
  38054. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38055. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38056. };
  38057. /**
  38058. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  38059. */
  38060. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  38061. if (this._linkRefractionWithTransparency) {
  38062. return false;
  38063. }
  38064. return (this.alpha < 1.0) ||
  38065. (this._shouldUseAlphaFromAlbedoTexture() &&
  38066. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  38067. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  38068. };
  38069. /**
  38070. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  38071. */
  38072. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  38073. if (this._linkRefractionWithTransparency) {
  38074. return false;
  38075. }
  38076. return this._shouldUseAlphaFromAlbedoTexture() &&
  38077. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  38078. };
  38079. /**
  38080. * Return the active textures of the material.
  38081. */
  38082. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  38083. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38084. if (this.environmentTexture) {
  38085. activeTextures.push(this.environmentTexture);
  38086. }
  38087. if (this.normalTexture) {
  38088. activeTextures.push(this.normalTexture);
  38089. }
  38090. if (this.emissiveTexture) {
  38091. activeTextures.push(this.emissiveTexture);
  38092. }
  38093. if (this.occlusionTexture) {
  38094. activeTextures.push(this.occlusionTexture);
  38095. }
  38096. return activeTextures;
  38097. };
  38098. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  38099. return "PBRBaseSimpleMaterial";
  38100. };
  38101. __decorate([
  38102. BABYLON.serialize(),
  38103. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38104. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  38105. __decorate([
  38106. BABYLON.serialize(),
  38107. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38108. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  38109. __decorate([
  38110. BABYLON.serializeAsTexture(),
  38111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  38112. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  38113. __decorate([
  38114. BABYLON.serialize(),
  38115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38116. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  38117. __decorate([
  38118. BABYLON.serialize(),
  38119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38120. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  38121. __decorate([
  38122. BABYLON.serializeAsTexture(),
  38123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  38124. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  38125. __decorate([
  38126. BABYLON.serializeAsColor3("emissive"),
  38127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38128. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  38129. __decorate([
  38130. BABYLON.serializeAsTexture(),
  38131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38132. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  38133. __decorate([
  38134. BABYLON.serialize(),
  38135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  38136. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  38137. __decorate([
  38138. BABYLON.serializeAsTexture(),
  38139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  38140. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  38141. __decorate([
  38142. BABYLON.serialize(),
  38143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  38144. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  38145. __decorate([
  38146. BABYLON.serialize()
  38147. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  38148. __decorate([
  38149. BABYLON.serialize()
  38150. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  38151. return PBRBaseSimpleMaterial;
  38152. }(BABYLON.PBRBaseMaterial));
  38153. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  38154. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38155. })(BABYLON || (BABYLON = {}));
  38156. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  38157. var BABYLON;
  38158. (function (BABYLON) {
  38159. /**
  38160. * The Physically based material of BJS.
  38161. *
  38162. * This offers the main features of a standard PBR material.
  38163. * For more information, please refer to the documentation :
  38164. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38165. */
  38166. var PBRMaterial = (function (_super) {
  38167. __extends(PBRMaterial, _super);
  38168. /**
  38169. * Instantiates a new PBRMaterial instance.
  38170. *
  38171. * @param name The material name
  38172. * @param scene The scene the material will be use in.
  38173. */
  38174. function PBRMaterial(name, scene) {
  38175. var _this = _super.call(this, name, scene) || this;
  38176. /**
  38177. * Intensity of the direct lights e.g. the four lights available in your scene.
  38178. * This impacts both the direct diffuse and specular highlights.
  38179. */
  38180. _this.directIntensity = 1.0;
  38181. /**
  38182. * Intensity of the emissive part of the material.
  38183. * This helps controlling the emissive effect without modifying the emissive color.
  38184. */
  38185. _this.emissiveIntensity = 1.0;
  38186. /**
  38187. * Intensity of the environment e.g. how much the environment will light the object
  38188. * either through harmonics for rough material or through the refelction for shiny ones.
  38189. */
  38190. _this.environmentIntensity = 1.0;
  38191. /**
  38192. * This is a special control allowing the reduction of the specular highlights coming from the
  38193. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38194. */
  38195. _this.specularIntensity = 1.0;
  38196. /**
  38197. * Debug Control allowing disabling the bump map on this material.
  38198. */
  38199. _this.disableBumpMap = false;
  38200. /**
  38201. * AKA Occlusion Texture Intensity in other nomenclature.
  38202. */
  38203. _this.ambientTextureStrength = 1.0;
  38204. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38205. /**
  38206. * AKA Diffuse Color in other nomenclature.
  38207. */
  38208. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  38209. /**
  38210. * AKA Specular Color in other nomenclature.
  38211. */
  38212. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38213. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  38214. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38215. /**
  38216. * AKA Glossiness in other nomenclature.
  38217. */
  38218. _this.microSurface = 1.0;
  38219. /**
  38220. * source material index of refraction (IOR)' / 'destination material IOR.
  38221. */
  38222. _this.indexOfRefraction = 0.66;
  38223. /**
  38224. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38225. */
  38226. _this.invertRefractionY = false;
  38227. /**
  38228. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38229. * Materials half opaque for instance using refraction could benefit from this control.
  38230. */
  38231. _this.linkRefractionWithTransparency = false;
  38232. _this.useLightmapAsShadowmap = false;
  38233. /**
  38234. * Specifies that the alpha is coming form the albedo channel alpha channel.
  38235. */
  38236. _this.useAlphaFromAlbedoTexture = false;
  38237. /**
  38238. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38239. */
  38240. _this.forceAlphaTest = false;
  38241. /**
  38242. * Defines the alpha limits in alpha test mode.
  38243. */
  38244. _this.alphaCutOff = 0.4;
  38245. /**
  38246. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38247. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38248. */
  38249. _this.useSpecularOverAlpha = true;
  38250. /**
  38251. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38252. */
  38253. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  38254. /**
  38255. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38256. */
  38257. _this.useRoughnessFromMetallicTextureAlpha = true;
  38258. /**
  38259. * Specifies if the metallic texture contains the roughness information in its green channel.
  38260. */
  38261. _this.useRoughnessFromMetallicTextureGreen = false;
  38262. /**
  38263. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38264. */
  38265. _this.useMetallnessFromMetallicTextureBlue = false;
  38266. /**
  38267. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38268. */
  38269. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  38270. /**
  38271. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38272. */
  38273. _this.useAmbientInGrayScale = false;
  38274. /**
  38275. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38276. * The material will try to infer what glossiness each pixel should be.
  38277. */
  38278. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  38279. /**
  38280. * BJS is using an harcoded light falloff based on a manually sets up range.
  38281. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38282. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38283. */
  38284. _this.usePhysicalLightFalloff = true;
  38285. /**
  38286. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38287. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38288. */
  38289. _this.useRadianceOverAlpha = true;
  38290. /**
  38291. * Allows using the bump map in parallax mode.
  38292. */
  38293. _this.useParallax = false;
  38294. /**
  38295. * Allows using the bump map in parallax occlusion mode.
  38296. */
  38297. _this.useParallaxOcclusion = false;
  38298. /**
  38299. * Controls the scale bias of the parallax mode.
  38300. */
  38301. _this.parallaxScaleBias = 0.05;
  38302. /**
  38303. * If sets to true, disables all the lights affecting the material.
  38304. */
  38305. _this.disableLighting = false;
  38306. /**
  38307. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38308. */
  38309. _this.forceIrradianceInFragment = false;
  38310. /**
  38311. * Number of Simultaneous lights allowed on the material.
  38312. */
  38313. _this.maxSimultaneousLights = 4;
  38314. /**
  38315. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38316. */
  38317. _this.invertNormalMapX = false;
  38318. /**
  38319. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38320. */
  38321. _this.invertNormalMapY = false;
  38322. /**
  38323. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38324. */
  38325. _this.twoSidedLighting = false;
  38326. /**
  38327. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  38328. * in your scene composition.
  38329. */
  38330. _this.preMultiplyAlpha = false;
  38331. /**
  38332. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38333. * And/Or occlude the blended part.
  38334. */
  38335. _this.useAlphaFresnel = false;
  38336. /**
  38337. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38338. * And/Or occlude the blended part.
  38339. */
  38340. _this.environmentBRDFTexture = null;
  38341. /**
  38342. * Force normal to face away from face.
  38343. * (Temporary internal fix to remove before 3.1)
  38344. */
  38345. _this.forceNormalForward = false;
  38346. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38347. return _this;
  38348. }
  38349. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38350. /**
  38351. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38352. */
  38353. get: function () {
  38354. return this._PBRMATERIAL_OPAQUE;
  38355. },
  38356. enumerable: true,
  38357. configurable: true
  38358. });
  38359. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38360. /**
  38361. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  38362. */
  38363. get: function () {
  38364. return this._PBRMATERIAL_ALPHATEST;
  38365. },
  38366. enumerable: true,
  38367. configurable: true
  38368. });
  38369. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  38370. /**
  38371. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38372. */
  38373. get: function () {
  38374. return this._PBRMATERIAL_ALPHABLEND;
  38375. },
  38376. enumerable: true,
  38377. configurable: true
  38378. });
  38379. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  38380. /**
  38381. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38382. * They are also discarded below the alpha cutoff threshold to improve performances.
  38383. */
  38384. get: function () {
  38385. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  38386. },
  38387. enumerable: true,
  38388. configurable: true
  38389. });
  38390. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  38391. /**
  38392. * Gets the image processing configuration used either in this material.
  38393. */
  38394. get: function () {
  38395. return this._imageProcessingConfiguration;
  38396. },
  38397. /**
  38398. * Sets the Default image processing configuration used either in the this material.
  38399. *
  38400. * If sets to null, the scene one is in use.
  38401. */
  38402. set: function (value) {
  38403. this._attachImageProcessingConfiguration(value);
  38404. // Ensure the effect will be rebuilt.
  38405. this._markAllSubMeshesAsTexturesDirty();
  38406. },
  38407. enumerable: true,
  38408. configurable: true
  38409. });
  38410. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  38411. /**
  38412. * Gets wether the color curves effect is enabled.
  38413. */
  38414. get: function () {
  38415. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38416. },
  38417. /**
  38418. * Sets wether the color curves effect is enabled.
  38419. */
  38420. set: function (value) {
  38421. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38422. },
  38423. enumerable: true,
  38424. configurable: true
  38425. });
  38426. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  38427. /**
  38428. * Gets wether the color grading effect is enabled.
  38429. */
  38430. get: function () {
  38431. return this.imageProcessingConfiguration.colorGradingEnabled;
  38432. },
  38433. /**
  38434. * Gets wether the color grading effect is enabled.
  38435. */
  38436. set: function (value) {
  38437. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38438. },
  38439. enumerable: true,
  38440. configurable: true
  38441. });
  38442. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  38443. /**
  38444. * Gets wether tonemapping is enabled or not.
  38445. */
  38446. get: function () {
  38447. return this._imageProcessingConfiguration.toneMappingEnabled;
  38448. },
  38449. /**
  38450. * Sets wether tonemapping is enabled or not
  38451. */
  38452. set: function (value) {
  38453. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38454. },
  38455. enumerable: true,
  38456. configurable: true
  38457. });
  38458. ;
  38459. ;
  38460. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  38461. /**
  38462. * The camera exposure used on this material.
  38463. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38464. * This corresponds to a photographic exposure.
  38465. */
  38466. get: function () {
  38467. return this._imageProcessingConfiguration.exposure;
  38468. },
  38469. /**
  38470. * The camera exposure used on this material.
  38471. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38472. * This corresponds to a photographic exposure.
  38473. */
  38474. set: function (value) {
  38475. this._imageProcessingConfiguration.exposure = value;
  38476. },
  38477. enumerable: true,
  38478. configurable: true
  38479. });
  38480. ;
  38481. ;
  38482. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  38483. /**
  38484. * Gets The camera contrast used on this material.
  38485. */
  38486. get: function () {
  38487. return this._imageProcessingConfiguration.contrast;
  38488. },
  38489. /**
  38490. * Sets The camera contrast used on this material.
  38491. */
  38492. set: function (value) {
  38493. this._imageProcessingConfiguration.contrast = value;
  38494. },
  38495. enumerable: true,
  38496. configurable: true
  38497. });
  38498. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  38499. /**
  38500. * Gets the Color Grading 2D Lookup Texture.
  38501. */
  38502. get: function () {
  38503. return this._imageProcessingConfiguration.colorGradingTexture;
  38504. },
  38505. /**
  38506. * Sets the Color Grading 2D Lookup Texture.
  38507. */
  38508. set: function (value) {
  38509. this._imageProcessingConfiguration.colorGradingTexture = value;
  38510. },
  38511. enumerable: true,
  38512. configurable: true
  38513. });
  38514. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  38515. /**
  38516. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38517. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38518. * 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;
  38519. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38520. */
  38521. get: function () {
  38522. return this._imageProcessingConfiguration.colorCurves;
  38523. },
  38524. /**
  38525. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38526. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38527. * 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;
  38528. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38529. */
  38530. set: function (value) {
  38531. this._imageProcessingConfiguration.colorCurves = value;
  38532. },
  38533. enumerable: true,
  38534. configurable: true
  38535. });
  38536. PBRMaterial.prototype.getClassName = function () {
  38537. return "PBRMaterial";
  38538. };
  38539. PBRMaterial.prototype.getActiveTextures = function () {
  38540. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38541. if (this._albedoTexture) {
  38542. activeTextures.push(this._albedoTexture);
  38543. }
  38544. if (this._ambientTexture) {
  38545. activeTextures.push(this._ambientTexture);
  38546. }
  38547. if (this._opacityTexture) {
  38548. activeTextures.push(this._opacityTexture);
  38549. }
  38550. if (this._reflectionTexture) {
  38551. activeTextures.push(this._reflectionTexture);
  38552. }
  38553. if (this._emissiveTexture) {
  38554. activeTextures.push(this._emissiveTexture);
  38555. }
  38556. if (this._reflectivityTexture) {
  38557. activeTextures.push(this._reflectivityTexture);
  38558. }
  38559. if (this._metallicTexture) {
  38560. activeTextures.push(this._metallicTexture);
  38561. }
  38562. if (this._microSurfaceTexture) {
  38563. activeTextures.push(this._microSurfaceTexture);
  38564. }
  38565. if (this._bumpTexture) {
  38566. activeTextures.push(this._bumpTexture);
  38567. }
  38568. if (this._lightmapTexture) {
  38569. activeTextures.push(this._lightmapTexture);
  38570. }
  38571. if (this._refractionTexture) {
  38572. activeTextures.push(this._refractionTexture);
  38573. }
  38574. return activeTextures;
  38575. };
  38576. PBRMaterial.prototype.hasTexture = function (texture) {
  38577. if (_super.prototype.hasTexture.call(this, texture)) {
  38578. return true;
  38579. }
  38580. if (this._albedoTexture === texture) {
  38581. return true;
  38582. }
  38583. if (this._ambientTexture === texture) {
  38584. return true;
  38585. }
  38586. if (this._opacityTexture === texture) {
  38587. return true;
  38588. }
  38589. if (this._reflectionTexture === texture) {
  38590. return true;
  38591. }
  38592. if (this._reflectivityTexture === texture) {
  38593. return true;
  38594. }
  38595. if (this._metallicTexture === texture) {
  38596. return true;
  38597. }
  38598. if (this._microSurfaceTexture === texture) {
  38599. return true;
  38600. }
  38601. if (this._bumpTexture === texture) {
  38602. return true;
  38603. }
  38604. if (this._lightmapTexture === texture) {
  38605. return true;
  38606. }
  38607. if (this._refractionTexture === texture) {
  38608. return true;
  38609. }
  38610. return false;
  38611. };
  38612. PBRMaterial.prototype.clone = function (name) {
  38613. var _this = this;
  38614. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38615. };
  38616. PBRMaterial.prototype.serialize = function () {
  38617. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38618. serializationObject.customType = "BABYLON.PBRMaterial";
  38619. return serializationObject;
  38620. };
  38621. // Statics
  38622. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38623. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38624. };
  38625. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38626. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38627. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38628. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38629. __decorate([
  38630. BABYLON.serialize(),
  38631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38632. ], PBRMaterial.prototype, "directIntensity", void 0);
  38633. __decorate([
  38634. BABYLON.serialize(),
  38635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38636. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38637. __decorate([
  38638. BABYLON.serialize(),
  38639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38640. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38641. __decorate([
  38642. BABYLON.serialize(),
  38643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38644. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38645. __decorate([
  38646. BABYLON.serialize(),
  38647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38648. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38649. __decorate([
  38650. BABYLON.serializeAsTexture(),
  38651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38652. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38653. __decorate([
  38654. BABYLON.serializeAsTexture(),
  38655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38656. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38657. __decorate([
  38658. BABYLON.serialize(),
  38659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38660. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38661. __decorate([
  38662. BABYLON.serializeAsTexture(),
  38663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38664. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38665. __decorate([
  38666. BABYLON.serializeAsTexture(),
  38667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38668. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38669. __decorate([
  38670. BABYLON.serializeAsTexture(),
  38671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38672. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38673. __decorate([
  38674. BABYLON.serializeAsTexture(),
  38675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38676. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38677. __decorate([
  38678. BABYLON.serializeAsTexture(),
  38679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38680. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38681. __decorate([
  38682. BABYLON.serialize(),
  38683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38684. ], PBRMaterial.prototype, "metallic", void 0);
  38685. __decorate([
  38686. BABYLON.serialize(),
  38687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38688. ], PBRMaterial.prototype, "roughness", void 0);
  38689. __decorate([
  38690. BABYLON.serializeAsTexture(),
  38691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38692. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38693. __decorate([
  38694. BABYLON.serializeAsTexture(),
  38695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38696. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38697. __decorate([
  38698. BABYLON.serializeAsTexture(),
  38699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38700. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38701. __decorate([
  38702. BABYLON.serializeAsTexture(),
  38703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38704. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38705. __decorate([
  38706. BABYLON.serializeAsColor3("ambient"),
  38707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38708. ], PBRMaterial.prototype, "ambientColor", void 0);
  38709. __decorate([
  38710. BABYLON.serializeAsColor3("albedo"),
  38711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38712. ], PBRMaterial.prototype, "albedoColor", void 0);
  38713. __decorate([
  38714. BABYLON.serializeAsColor3("reflectivity"),
  38715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38716. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38717. __decorate([
  38718. BABYLON.serializeAsColor3("reflection"),
  38719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38720. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38721. __decorate([
  38722. BABYLON.serializeAsColor3("emissive"),
  38723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38724. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38725. __decorate([
  38726. BABYLON.serialize(),
  38727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38728. ], PBRMaterial.prototype, "microSurface", void 0);
  38729. __decorate([
  38730. BABYLON.serialize(),
  38731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38732. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38733. __decorate([
  38734. BABYLON.serialize(),
  38735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38736. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38737. __decorate([
  38738. BABYLON.serialize(),
  38739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38740. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38741. __decorate([
  38742. BABYLON.serialize(),
  38743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38744. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38745. __decorate([
  38746. BABYLON.serialize(),
  38747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38748. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38749. __decorate([
  38750. BABYLON.serialize(),
  38751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38752. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38753. __decorate([
  38754. BABYLON.serialize(),
  38755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38756. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38757. __decorate([
  38758. BABYLON.serialize(),
  38759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38760. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38761. __decorate([
  38762. BABYLON.serialize(),
  38763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38764. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38765. __decorate([
  38766. BABYLON.serialize(),
  38767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38768. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38769. __decorate([
  38770. BABYLON.serialize(),
  38771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38772. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38773. __decorate([
  38774. BABYLON.serialize(),
  38775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38776. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38777. __decorate([
  38778. BABYLON.serialize(),
  38779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38780. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38781. __decorate([
  38782. BABYLON.serialize(),
  38783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38784. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38785. __decorate([
  38786. BABYLON.serialize(),
  38787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38788. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38789. __decorate([
  38790. BABYLON.serialize(),
  38791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38792. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38793. __decorate([
  38794. BABYLON.serialize(),
  38795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38796. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38797. __decorate([
  38798. BABYLON.serialize(),
  38799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38800. ], PBRMaterial.prototype, "useParallax", void 0);
  38801. __decorate([
  38802. BABYLON.serialize(),
  38803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38804. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38805. __decorate([
  38806. BABYLON.serialize(),
  38807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38808. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38809. __decorate([
  38810. BABYLON.serialize(),
  38811. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38812. ], PBRMaterial.prototype, "disableLighting", void 0);
  38813. __decorate([
  38814. BABYLON.serialize(),
  38815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38816. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38817. __decorate([
  38818. BABYLON.serialize(),
  38819. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38820. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38821. __decorate([
  38822. BABYLON.serialize(),
  38823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38824. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38825. __decorate([
  38826. BABYLON.serialize(),
  38827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38828. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38829. __decorate([
  38830. BABYLON.serialize(),
  38831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38832. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38833. __decorate([
  38834. BABYLON.serialize(),
  38835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38836. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  38837. __decorate([
  38838. BABYLON.serialize(),
  38839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38840. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38841. __decorate([
  38842. BABYLON.serializeAsTexture(),
  38843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38844. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38845. __decorate([
  38846. BABYLON.serialize(),
  38847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38848. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38849. return PBRMaterial;
  38850. }(BABYLON.PBRBaseMaterial));
  38851. BABYLON.PBRMaterial = PBRMaterial;
  38852. })(BABYLON || (BABYLON = {}));
  38853. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38854. var BABYLON;
  38855. (function (BABYLON) {
  38856. /**
  38857. * The PBR material of BJS following the metal roughness convention.
  38858. *
  38859. * This fits to the PBR convention in the GLTF definition:
  38860. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38861. */
  38862. var PBRMetallicRoughnessMaterial = (function (_super) {
  38863. __extends(PBRMetallicRoughnessMaterial, _super);
  38864. /**
  38865. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38866. *
  38867. * @param name The material name
  38868. * @param scene The scene the material will be use in.
  38869. */
  38870. function PBRMetallicRoughnessMaterial(name, scene) {
  38871. var _this = _super.call(this, name, scene) || this;
  38872. _this._useRoughnessFromMetallicTextureAlpha = false;
  38873. _this._useRoughnessFromMetallicTextureGreen = true;
  38874. _this._useMetallnessFromMetallicTextureBlue = true;
  38875. return _this;
  38876. }
  38877. /**
  38878. * Return the currrent class name of the material.
  38879. */
  38880. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38881. return "PBRMetallicRoughnessMaterial";
  38882. };
  38883. /**
  38884. * Return the active textures of the material.
  38885. */
  38886. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  38887. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38888. if (this.baseTexture) {
  38889. activeTextures.push(this.baseTexture);
  38890. }
  38891. if (this.metallicRoughnessTexture) {
  38892. activeTextures.push(this.metallicRoughnessTexture);
  38893. }
  38894. return activeTextures;
  38895. };
  38896. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  38897. if (_super.prototype.hasTexture.call(this, texture)) {
  38898. return true;
  38899. }
  38900. if (this.baseTexture === texture) {
  38901. return true;
  38902. }
  38903. if (this.metallicRoughnessTexture === texture) {
  38904. return true;
  38905. }
  38906. return false;
  38907. };
  38908. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  38909. var _this = this;
  38910. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  38911. };
  38912. /**
  38913. * Serialize the material to a parsable JSON object.
  38914. */
  38915. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  38916. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38917. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  38918. return serializationObject;
  38919. };
  38920. /**
  38921. * Parses a JSON object correponding to the serialize function.
  38922. */
  38923. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38924. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38925. };
  38926. __decorate([
  38927. BABYLON.serializeAsColor3(),
  38928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38929. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38930. __decorate([
  38931. BABYLON.serializeAsTexture(),
  38932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38933. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38934. __decorate([
  38935. BABYLON.serialize(),
  38936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38937. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38938. __decorate([
  38939. BABYLON.serialize(),
  38940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38941. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38942. __decorate([
  38943. BABYLON.serializeAsTexture(),
  38944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38945. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38946. return PBRMetallicRoughnessMaterial;
  38947. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38948. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38949. })(BABYLON || (BABYLON = {}));
  38950. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38951. var BABYLON;
  38952. (function (BABYLON) {
  38953. /**
  38954. * The PBR material of BJS following the specular glossiness convention.
  38955. *
  38956. * This fits to the PBR convention in the GLTF definition:
  38957. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38958. */
  38959. var PBRSpecularGlossinessMaterial = (function (_super) {
  38960. __extends(PBRSpecularGlossinessMaterial, _super);
  38961. /**
  38962. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38963. *
  38964. * @param name The material name
  38965. * @param scene The scene the material will be use in.
  38966. */
  38967. function PBRSpecularGlossinessMaterial(name, scene) {
  38968. var _this = _super.call(this, name, scene) || this;
  38969. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38970. return _this;
  38971. }
  38972. /**
  38973. * Return the currrent class name of the material.
  38974. */
  38975. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38976. return "PBRSpecularGlossinessMaterial";
  38977. };
  38978. /**
  38979. * Return the active textures of the material.
  38980. */
  38981. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38982. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38983. if (this.diffuseTexture) {
  38984. activeTextures.push(this.diffuseTexture);
  38985. }
  38986. if (this.specularGlossinessTexture) {
  38987. activeTextures.push(this.specularGlossinessTexture);
  38988. }
  38989. return activeTextures;
  38990. };
  38991. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38992. if (_super.prototype.hasTexture.call(this, texture)) {
  38993. return true;
  38994. }
  38995. if (this.diffuseTexture === texture) {
  38996. return true;
  38997. }
  38998. if (this.specularGlossinessTexture === texture) {
  38999. return true;
  39000. }
  39001. return false;
  39002. };
  39003. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  39004. var _this = this;
  39005. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  39006. };
  39007. /**
  39008. * Serialize the material to a parsable JSON object.
  39009. */
  39010. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  39011. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39012. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  39013. return serializationObject;
  39014. };
  39015. /**
  39016. * Parses a JSON object correponding to the serialize function.
  39017. */
  39018. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  39019. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  39020. };
  39021. __decorate([
  39022. BABYLON.serializeAsColor3("diffuse"),
  39023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39024. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  39025. __decorate([
  39026. BABYLON.serializeAsTexture(),
  39027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39028. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  39029. __decorate([
  39030. BABYLON.serializeAsColor3("specular"),
  39031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  39032. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  39033. __decorate([
  39034. BABYLON.serialize(),
  39035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  39036. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  39037. __decorate([
  39038. BABYLON.serializeAsTexture(),
  39039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  39040. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  39041. return PBRSpecularGlossinessMaterial;
  39042. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  39043. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  39044. })(BABYLON || (BABYLON = {}));
  39045. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  39046. var BABYLON;
  39047. (function (BABYLON) {
  39048. var ShaderMaterial = (function (_super) {
  39049. __extends(ShaderMaterial, _super);
  39050. function ShaderMaterial(name, scene, shaderPath, options) {
  39051. var _this = _super.call(this, name, scene) || this;
  39052. _this._textures = {};
  39053. _this._textureArrays = {};
  39054. _this._floats = {};
  39055. _this._floatsArrays = {};
  39056. _this._colors3 = {};
  39057. _this._colors3Arrays = {};
  39058. _this._colors4 = {};
  39059. _this._vectors2 = {};
  39060. _this._vectors3 = {};
  39061. _this._vectors4 = {};
  39062. _this._matrices = {};
  39063. _this._matrices3x3 = {};
  39064. _this._matrices2x2 = {};
  39065. _this._vectors3Arrays = {};
  39066. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  39067. _this._shaderPath = shaderPath;
  39068. options.needAlphaBlending = options.needAlphaBlending || false;
  39069. options.needAlphaTesting = options.needAlphaTesting || false;
  39070. options.attributes = options.attributes || ["position", "normal", "uv"];
  39071. options.uniforms = options.uniforms || ["worldViewProjection"];
  39072. options.uniformBuffers = options.uniformBuffers || [];
  39073. options.samplers = options.samplers || [];
  39074. options.defines = options.defines || [];
  39075. _this._options = options;
  39076. return _this;
  39077. }
  39078. ShaderMaterial.prototype.getClassName = function () {
  39079. return "ShaderMaterial";
  39080. };
  39081. ShaderMaterial.prototype.needAlphaBlending = function () {
  39082. return this._options.needAlphaBlending;
  39083. };
  39084. ShaderMaterial.prototype.needAlphaTesting = function () {
  39085. return this._options.needAlphaTesting;
  39086. };
  39087. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  39088. if (this._options.uniforms.indexOf(uniformName) === -1) {
  39089. this._options.uniforms.push(uniformName);
  39090. }
  39091. };
  39092. ShaderMaterial.prototype.setTexture = function (name, texture) {
  39093. if (this._options.samplers.indexOf(name) === -1) {
  39094. this._options.samplers.push(name);
  39095. }
  39096. this._textures[name] = texture;
  39097. return this;
  39098. };
  39099. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  39100. if (this._options.samplers.indexOf(name) === -1) {
  39101. this._options.samplers.push(name);
  39102. }
  39103. this._checkUniform(name);
  39104. this._textureArrays[name] = textures;
  39105. return this;
  39106. };
  39107. ShaderMaterial.prototype.setFloat = function (name, value) {
  39108. this._checkUniform(name);
  39109. this._floats[name] = value;
  39110. return this;
  39111. };
  39112. ShaderMaterial.prototype.setFloats = function (name, value) {
  39113. this._checkUniform(name);
  39114. this._floatsArrays[name] = value;
  39115. return this;
  39116. };
  39117. ShaderMaterial.prototype.setColor3 = function (name, value) {
  39118. this._checkUniform(name);
  39119. this._colors3[name] = value;
  39120. return this;
  39121. };
  39122. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  39123. this._checkUniform(name);
  39124. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  39125. color.toArray(arr, arr.length);
  39126. return arr;
  39127. }, []);
  39128. return this;
  39129. };
  39130. ShaderMaterial.prototype.setColor4 = function (name, value) {
  39131. this._checkUniform(name);
  39132. this._colors4[name] = value;
  39133. return this;
  39134. };
  39135. ShaderMaterial.prototype.setVector2 = function (name, value) {
  39136. this._checkUniform(name);
  39137. this._vectors2[name] = value;
  39138. return this;
  39139. };
  39140. ShaderMaterial.prototype.setVector3 = function (name, value) {
  39141. this._checkUniform(name);
  39142. this._vectors3[name] = value;
  39143. return this;
  39144. };
  39145. ShaderMaterial.prototype.setVector4 = function (name, value) {
  39146. this._checkUniform(name);
  39147. this._vectors4[name] = value;
  39148. return this;
  39149. };
  39150. ShaderMaterial.prototype.setMatrix = function (name, value) {
  39151. this._checkUniform(name);
  39152. this._matrices[name] = value;
  39153. return this;
  39154. };
  39155. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  39156. this._checkUniform(name);
  39157. this._matrices3x3[name] = value;
  39158. return this;
  39159. };
  39160. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  39161. this._checkUniform(name);
  39162. this._matrices2x2[name] = value;
  39163. return this;
  39164. };
  39165. ShaderMaterial.prototype.setArray3 = function (name, value) {
  39166. this._checkUniform(name);
  39167. this._vectors3Arrays[name] = value;
  39168. return this;
  39169. };
  39170. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  39171. if (!mesh) {
  39172. return true;
  39173. }
  39174. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  39175. return false;
  39176. }
  39177. return false;
  39178. };
  39179. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  39180. var scene = this.getScene();
  39181. var engine = scene.getEngine();
  39182. if (!this.checkReadyOnEveryCall) {
  39183. if (this._renderId === scene.getRenderId()) {
  39184. if (this._checkCache(scene, mesh, useInstances)) {
  39185. return true;
  39186. }
  39187. }
  39188. }
  39189. // Instances
  39190. var defines = [];
  39191. var attribs = [];
  39192. var fallbacks = new BABYLON.EffectFallbacks();
  39193. if (useInstances) {
  39194. defines.push("#define INSTANCES");
  39195. }
  39196. for (var index = 0; index < this._options.defines.length; index++) {
  39197. defines.push(this._options.defines[index]);
  39198. }
  39199. for (var index = 0; index < this._options.attributes.length; index++) {
  39200. attribs.push(this._options.attributes[index]);
  39201. }
  39202. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39203. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39204. defines.push("#define VERTEXCOLOR");
  39205. }
  39206. // Bones
  39207. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  39208. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39209. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39210. if (mesh.numBoneInfluencers > 4) {
  39211. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39212. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39213. }
  39214. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39215. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39216. fallbacks.addCPUSkinningFallback(0, mesh);
  39217. if (this._options.uniforms.indexOf("mBones") === -1) {
  39218. this._options.uniforms.push("mBones");
  39219. }
  39220. }
  39221. else {
  39222. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39223. }
  39224. // Textures
  39225. for (var name in this._textures) {
  39226. if (!this._textures[name].isReady()) {
  39227. return false;
  39228. }
  39229. }
  39230. // Alpha test
  39231. if (engine.getAlphaTesting()) {
  39232. defines.push("#define ALPHATEST");
  39233. }
  39234. var previousEffect = this._effect;
  39235. var join = defines.join("\n");
  39236. this._effect = engine.createEffect(this._shaderPath, {
  39237. attributes: attribs,
  39238. uniformsNames: this._options.uniforms,
  39239. uniformBuffersNames: this._options.uniformBuffers,
  39240. samplers: this._options.samplers,
  39241. defines: join,
  39242. fallbacks: fallbacks,
  39243. onCompiled: this.onCompiled,
  39244. onError: this.onError
  39245. }, engine);
  39246. if (!this._effect.isReady()) {
  39247. return false;
  39248. }
  39249. if (previousEffect !== this._effect) {
  39250. scene.resetCachedMaterial();
  39251. }
  39252. this._renderId = scene.getRenderId();
  39253. return true;
  39254. };
  39255. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39256. var scene = this.getScene();
  39257. if (this._options.uniforms.indexOf("world") !== -1) {
  39258. this._effect.setMatrix("world", world);
  39259. }
  39260. if (this._options.uniforms.indexOf("worldView") !== -1) {
  39261. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  39262. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  39263. }
  39264. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  39265. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  39266. }
  39267. };
  39268. ShaderMaterial.prototype.bind = function (world, mesh) {
  39269. // Std values
  39270. this.bindOnlyWorldMatrix(world);
  39271. if (this.getScene().getCachedMaterial() !== this) {
  39272. if (this._options.uniforms.indexOf("view") !== -1) {
  39273. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  39274. }
  39275. if (this._options.uniforms.indexOf("projection") !== -1) {
  39276. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  39277. }
  39278. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  39279. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  39280. }
  39281. // Bones
  39282. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  39283. var name;
  39284. // Texture
  39285. for (name in this._textures) {
  39286. this._effect.setTexture(name, this._textures[name]);
  39287. }
  39288. // Texture arrays
  39289. for (name in this._textureArrays) {
  39290. this._effect.setTextureArray(name, this._textureArrays[name]);
  39291. }
  39292. // Float
  39293. for (name in this._floats) {
  39294. this._effect.setFloat(name, this._floats[name]);
  39295. }
  39296. // Float s
  39297. for (name in this._floatsArrays) {
  39298. this._effect.setArray(name, this._floatsArrays[name]);
  39299. }
  39300. // Color3
  39301. for (name in this._colors3) {
  39302. this._effect.setColor3(name, this._colors3[name]);
  39303. }
  39304. for (name in this._colors3Arrays) {
  39305. this._effect.setArray3(name, this._colors3Arrays[name]);
  39306. }
  39307. // Color4
  39308. for (name in this._colors4) {
  39309. var color = this._colors4[name];
  39310. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  39311. }
  39312. // Vector2
  39313. for (name in this._vectors2) {
  39314. this._effect.setVector2(name, this._vectors2[name]);
  39315. }
  39316. // Vector3
  39317. for (name in this._vectors3) {
  39318. this._effect.setVector3(name, this._vectors3[name]);
  39319. }
  39320. // Vector4
  39321. for (name in this._vectors4) {
  39322. this._effect.setVector4(name, this._vectors4[name]);
  39323. }
  39324. // Matrix
  39325. for (name in this._matrices) {
  39326. this._effect.setMatrix(name, this._matrices[name]);
  39327. }
  39328. // Matrix 3x3
  39329. for (name in this._matrices3x3) {
  39330. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  39331. }
  39332. // Matrix 2x2
  39333. for (name in this._matrices2x2) {
  39334. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  39335. }
  39336. // Vector3Array
  39337. for (name in this._vectors3Arrays) {
  39338. this._effect.setArray3(name, this._vectors3Arrays[name]);
  39339. }
  39340. }
  39341. this._afterBind(mesh);
  39342. };
  39343. ShaderMaterial.prototype.getActiveTextures = function () {
  39344. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39345. for (var name in this._textures) {
  39346. activeTextures.push(this._textures[name]);
  39347. }
  39348. for (var name in this._textureArrays) {
  39349. var array = this._textureArrays[name];
  39350. for (var index = 0; index < array.length; index++) {
  39351. activeTextures.push(array[index]);
  39352. }
  39353. }
  39354. return activeTextures;
  39355. };
  39356. ShaderMaterial.prototype.hasTexture = function (texture) {
  39357. if (_super.prototype.hasTexture.call(this, texture)) {
  39358. return true;
  39359. }
  39360. for (var name in this._textures) {
  39361. if (this._textures[name] === texture) {
  39362. return true;
  39363. }
  39364. }
  39365. for (var name in this._textureArrays) {
  39366. var array = this._textureArrays[name];
  39367. for (var index = 0; index < array.length; index++) {
  39368. if (array[index] === texture) {
  39369. return true;
  39370. }
  39371. }
  39372. }
  39373. return false;
  39374. };
  39375. ShaderMaterial.prototype.clone = function (name) {
  39376. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  39377. return newShaderMaterial;
  39378. };
  39379. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39380. if (forceDisposeTextures) {
  39381. var name;
  39382. for (name in this._textures) {
  39383. this._textures[name].dispose();
  39384. }
  39385. for (name in this._textureArrays) {
  39386. var array = this._textureArrays[name];
  39387. for (var index = 0; index < array.length; index++) {
  39388. array[index].dispose();
  39389. }
  39390. }
  39391. }
  39392. this._textures = {};
  39393. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39394. };
  39395. ShaderMaterial.prototype.serialize = function () {
  39396. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39397. serializationObject.customType = "BABYLON.ShaderMaterial";
  39398. serializationObject.options = this._options;
  39399. serializationObject.shaderPath = this._shaderPath;
  39400. var name;
  39401. // Texture
  39402. serializationObject.textures = {};
  39403. for (name in this._textures) {
  39404. serializationObject.textures[name] = this._textures[name].serialize();
  39405. }
  39406. // Texture arrays
  39407. serializationObject.textureArrays = {};
  39408. for (name in this._textureArrays) {
  39409. serializationObject.textureArrays[name] = [];
  39410. var array = this._textureArrays[name];
  39411. for (var index = 0; index < array.length; index++) {
  39412. serializationObject.textureArrays[name].push(array[index].serialize());
  39413. }
  39414. }
  39415. // Float
  39416. serializationObject.floats = {};
  39417. for (name in this._floats) {
  39418. serializationObject.floats[name] = this._floats[name];
  39419. }
  39420. // Float s
  39421. serializationObject.floatArrays = {};
  39422. for (name in this._floatsArrays) {
  39423. serializationObject.floatArrays[name] = this._floatsArrays[name];
  39424. }
  39425. // Color3
  39426. serializationObject.colors3 = {};
  39427. for (name in this._colors3) {
  39428. serializationObject.colors3[name] = this._colors3[name].asArray();
  39429. }
  39430. // Color3 array
  39431. serializationObject.colors3Arrays = {};
  39432. for (name in this._colors3Arrays) {
  39433. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  39434. }
  39435. // Color4
  39436. serializationObject.colors4 = {};
  39437. for (name in this._colors4) {
  39438. serializationObject.colors4[name] = this._colors4[name].asArray();
  39439. }
  39440. // Vector2
  39441. serializationObject.vectors2 = {};
  39442. for (name in this._vectors2) {
  39443. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  39444. }
  39445. // Vector3
  39446. serializationObject.vectors3 = {};
  39447. for (name in this._vectors3) {
  39448. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  39449. }
  39450. // Vector4
  39451. serializationObject.vectors4 = {};
  39452. for (name in this._vectors4) {
  39453. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  39454. }
  39455. // Matrix
  39456. serializationObject.matrices = {};
  39457. for (name in this._matrices) {
  39458. serializationObject.matrices[name] = this._matrices[name].asArray();
  39459. }
  39460. // Matrix 3x3
  39461. serializationObject.matrices3x3 = {};
  39462. for (name in this._matrices3x3) {
  39463. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  39464. }
  39465. // Matrix 2x2
  39466. serializationObject.matrices2x2 = {};
  39467. for (name in this._matrices2x2) {
  39468. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  39469. }
  39470. // Vector3Array
  39471. serializationObject.vectors3Arrays = {};
  39472. for (name in this._vectors3Arrays) {
  39473. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  39474. }
  39475. return serializationObject;
  39476. };
  39477. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  39478. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  39479. var name;
  39480. // Texture
  39481. for (name in source.textures) {
  39482. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  39483. }
  39484. // Texture arrays
  39485. for (name in source.textureArrays) {
  39486. var array = source.textureArrays[name];
  39487. var textureArray = new Array();
  39488. for (var index = 0; index < array.length; index++) {
  39489. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  39490. }
  39491. material.setTextureArray(name, textureArray);
  39492. }
  39493. // Float
  39494. for (name in source.floats) {
  39495. material.setFloat(name, source.floats[name]);
  39496. }
  39497. // Float s
  39498. for (name in source.floatsArrays) {
  39499. material.setFloats(name, source.floatsArrays[name]);
  39500. }
  39501. // Color3
  39502. for (name in source.colors3) {
  39503. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  39504. }
  39505. // Color3 arrays
  39506. for (name in source.colors3Arrays) {
  39507. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  39508. if (i % 3 === 0) {
  39509. arr.push([num]);
  39510. }
  39511. else {
  39512. arr[arr.length - 1].push(num);
  39513. }
  39514. return arr;
  39515. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  39516. material.setColor3Array(name, colors);
  39517. }
  39518. // Color4
  39519. for (name in source.colors4) {
  39520. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  39521. }
  39522. // Vector2
  39523. for (name in source.vectors2) {
  39524. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  39525. }
  39526. // Vector3
  39527. for (name in source.vectors3) {
  39528. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  39529. }
  39530. // Vector4
  39531. for (name in source.vectors4) {
  39532. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  39533. }
  39534. // Matrix
  39535. for (name in source.matrices) {
  39536. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  39537. }
  39538. // Matrix 3x3
  39539. for (name in source.matrices3x3) {
  39540. material.setMatrix3x3(name, source.matrices3x3[name]);
  39541. }
  39542. // Matrix 2x2
  39543. for (name in source.matrices2x2) {
  39544. material.setMatrix2x2(name, source.matrices2x2[name]);
  39545. }
  39546. // Vector3Array
  39547. for (name in source.vectors3Arrays) {
  39548. material.setArray3(name, source.vectors3Arrays[name]);
  39549. }
  39550. return material;
  39551. };
  39552. return ShaderMaterial;
  39553. }(BABYLON.Material));
  39554. BABYLON.ShaderMaterial = ShaderMaterial;
  39555. })(BABYLON || (BABYLON = {}));
  39556. //# sourceMappingURL=babylon.shaderMaterial.js.map
  39557. var BABYLON;
  39558. (function (BABYLON) {
  39559. var MeshBuilder = (function () {
  39560. function MeshBuilder() {
  39561. }
  39562. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  39563. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  39564. return BABYLON.Mesh.DOUBLESIDE;
  39565. }
  39566. if (orientation === undefined || orientation === null) {
  39567. return BABYLON.Mesh.FRONTSIDE;
  39568. }
  39569. return orientation;
  39570. };
  39571. /**
  39572. * Creates a box mesh.
  39573. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  39574. * The parameter `size` sets the size (float) of each box side (default 1).
  39575. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  39576. * 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).
  39577. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  39578. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39579. * 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).
  39580. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39581. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39582. */
  39583. MeshBuilder.CreateBox = function (name, options, scene) {
  39584. var box = new BABYLON.Mesh(name, scene);
  39585. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39586. box.sideOrientation = options.sideOrientation;
  39587. var vertexData = BABYLON.VertexData.CreateBox(options);
  39588. vertexData.applyToMesh(box, options.updatable);
  39589. return box;
  39590. };
  39591. /**
  39592. * Creates a sphere mesh.
  39593. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  39594. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  39595. * 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`).
  39596. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  39597. * 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
  39598. * 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).
  39599. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39600. * 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).
  39601. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39602. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39603. */
  39604. MeshBuilder.CreateSphere = function (name, options, scene) {
  39605. var sphere = new BABYLON.Mesh(name, scene);
  39606. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39607. sphere.sideOrientation = options.sideOrientation;
  39608. var vertexData = BABYLON.VertexData.CreateSphere(options);
  39609. vertexData.applyToMesh(sphere, options.updatable);
  39610. return sphere;
  39611. };
  39612. /**
  39613. * Creates a plane polygonal mesh. By default, this is a disc.
  39614. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  39615. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  39616. * 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.
  39617. * 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
  39618. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39619. * 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).
  39620. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39621. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39622. */
  39623. MeshBuilder.CreateDisc = function (name, options, scene) {
  39624. var disc = new BABYLON.Mesh(name, scene);
  39625. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39626. disc.sideOrientation = options.sideOrientation;
  39627. var vertexData = BABYLON.VertexData.CreateDisc(options);
  39628. vertexData.applyToMesh(disc, options.updatable);
  39629. return disc;
  39630. };
  39631. /**
  39632. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  39633. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  39634. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  39635. * 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`).
  39636. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  39637. * 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.
  39638. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39639. * 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).
  39640. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39641. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39642. */
  39643. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  39644. var sphere = new BABYLON.Mesh(name, scene);
  39645. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39646. sphere.sideOrientation = options.sideOrientation;
  39647. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  39648. vertexData.applyToMesh(sphere, options.updatable);
  39649. return sphere;
  39650. };
  39651. ;
  39652. /**
  39653. * Creates a ribbon mesh.
  39654. * 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.
  39655. *
  39656. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  39657. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  39658. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  39659. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  39660. * 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.
  39661. * 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.
  39662. * 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
  39663. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39664. * 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).
  39665. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39666. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39667. * 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.
  39668. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  39669. * 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
  39670. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  39671. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  39672. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39673. */
  39674. MeshBuilder.CreateRibbon = function (name, options, scene) {
  39675. var pathArray = options.pathArray;
  39676. var closeArray = options.closeArray;
  39677. var closePath = options.closePath;
  39678. var offset = options.offset;
  39679. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39680. var instance = options.instance;
  39681. var updatable = options.updatable;
  39682. if (instance) {
  39683. // positionFunction : ribbon case
  39684. // only pathArray and sideOrientation parameters are taken into account for positions update
  39685. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  39686. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  39687. var positionFunction = function (positions) {
  39688. var minlg = pathArray[0].length;
  39689. var i = 0;
  39690. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  39691. for (var si = 1; si <= ns; si++) {
  39692. for (var p = 0; p < pathArray.length; p++) {
  39693. var path = pathArray[p];
  39694. var l = path.length;
  39695. minlg = (minlg < l) ? minlg : l;
  39696. var j = 0;
  39697. while (j < minlg) {
  39698. positions[i] = path[j].x;
  39699. positions[i + 1] = path[j].y;
  39700. positions[i + 2] = path[j].z;
  39701. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  39702. BABYLON.Tmp.Vector3[0].x = path[j].x;
  39703. }
  39704. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  39705. BABYLON.Tmp.Vector3[1].x = path[j].x;
  39706. }
  39707. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  39708. BABYLON.Tmp.Vector3[0].y = path[j].y;
  39709. }
  39710. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  39711. BABYLON.Tmp.Vector3[1].y = path[j].y;
  39712. }
  39713. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  39714. BABYLON.Tmp.Vector3[0].z = path[j].z;
  39715. }
  39716. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  39717. BABYLON.Tmp.Vector3[1].z = path[j].z;
  39718. }
  39719. j++;
  39720. i += 3;
  39721. }
  39722. if (instance._closePath) {
  39723. positions[i] = path[0].x;
  39724. positions[i + 1] = path[0].y;
  39725. positions[i + 2] = path[0].z;
  39726. i += 3;
  39727. }
  39728. }
  39729. }
  39730. };
  39731. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39732. positionFunction(positions);
  39733. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  39734. instance._boundingInfo.update(instance._worldMatrix);
  39735. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  39736. if (options.colors) {
  39737. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39738. for (var c = 0; c < options.colors.length; c++) {
  39739. colors[c * 4] = options.colors[c].r;
  39740. colors[c * 4 + 1] = options.colors[c].g;
  39741. colors[c * 4 + 2] = options.colors[c].b;
  39742. colors[c * 4 + 3] = options.colors[c].a;
  39743. }
  39744. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  39745. }
  39746. if (options.uvs) {
  39747. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39748. for (var i = 0; i < options.uvs.length; i++) {
  39749. uvs[i * 2] = options.uvs[i].x;
  39750. uvs[i * 2 + 1] = options.uvs[i].y;
  39751. }
  39752. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  39753. }
  39754. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  39755. var indices = instance.getIndices();
  39756. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39757. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  39758. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  39759. if (instance._closePath) {
  39760. var indexFirst = 0;
  39761. var indexLast = 0;
  39762. for (var p = 0; p < pathArray.length; p++) {
  39763. indexFirst = instance._idx[p] * 3;
  39764. if (p + 1 < pathArray.length) {
  39765. indexLast = (instance._idx[p + 1] - 1) * 3;
  39766. }
  39767. else {
  39768. indexLast = normals.length - 3;
  39769. }
  39770. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  39771. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  39772. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  39773. normals[indexLast] = normals[indexFirst];
  39774. normals[indexLast + 1] = normals[indexFirst + 1];
  39775. normals[indexLast + 2] = normals[indexFirst + 2];
  39776. }
  39777. }
  39778. if (!(instance.areNormalsFrozen)) {
  39779. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  39780. }
  39781. }
  39782. return instance;
  39783. }
  39784. else {
  39785. var ribbon = new BABYLON.Mesh(name, scene);
  39786. ribbon.sideOrientation = sideOrientation;
  39787. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  39788. if (closePath) {
  39789. ribbon._idx = vertexData._idx;
  39790. }
  39791. ribbon._closePath = closePath;
  39792. ribbon._closeArray = closeArray;
  39793. vertexData.applyToMesh(ribbon, updatable);
  39794. return ribbon;
  39795. }
  39796. };
  39797. /**
  39798. * Creates a cylinder or a cone mesh.
  39799. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  39800. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  39801. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  39802. * 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.
  39803. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  39804. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  39805. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  39806. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  39807. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  39808. * 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).
  39809. * 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
  39810. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  39811. * 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
  39812. * 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.
  39813. * If `enclose` is false, a ring surface is one element.
  39814. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  39815. * 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
  39816. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39817. * 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).
  39818. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39819. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39820. */
  39821. MeshBuilder.CreateCylinder = function (name, options, scene) {
  39822. var cylinder = new BABYLON.Mesh(name, scene);
  39823. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39824. cylinder.sideOrientation = options.sideOrientation;
  39825. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  39826. vertexData.applyToMesh(cylinder, options.updatable);
  39827. return cylinder;
  39828. };
  39829. /**
  39830. * Creates a torus mesh.
  39831. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  39832. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  39833. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  39834. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  39835. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39836. * 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).
  39837. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39838. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39839. */
  39840. MeshBuilder.CreateTorus = function (name, options, scene) {
  39841. var torus = new BABYLON.Mesh(name, scene);
  39842. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39843. torus.sideOrientation = options.sideOrientation;
  39844. var vertexData = BABYLON.VertexData.CreateTorus(options);
  39845. vertexData.applyToMesh(torus, options.updatable);
  39846. return torus;
  39847. };
  39848. /**
  39849. * Creates a torus knot mesh.
  39850. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  39851. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  39852. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  39853. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  39854. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  39855. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39856. * 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).
  39857. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39858. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39859. */
  39860. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  39861. var torusKnot = new BABYLON.Mesh(name, scene);
  39862. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39863. torusKnot.sideOrientation = options.sideOrientation;
  39864. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  39865. vertexData.applyToMesh(torusKnot, options.updatable);
  39866. return torusKnot;
  39867. };
  39868. /**
  39869. * Creates a line system mesh.
  39870. * A line system is a pool of many lines gathered in a single mesh.
  39871. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  39872. * 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.
  39873. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  39874. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  39875. * 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
  39876. * 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
  39877. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  39878. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39879. */
  39880. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  39881. var instance = options.instance;
  39882. var lines = options.lines;
  39883. if (instance) {
  39884. var positionFunction = function (positions) {
  39885. var i = 0;
  39886. for (var l = 0; l < lines.length; l++) {
  39887. var points = lines[l];
  39888. for (var p = 0; p < points.length; p++) {
  39889. positions[i] = points[p].x;
  39890. positions[i + 1] = points[p].y;
  39891. positions[i + 2] = points[p].z;
  39892. i += 3;
  39893. }
  39894. }
  39895. };
  39896. instance.updateMeshPositions(positionFunction, false);
  39897. return instance;
  39898. }
  39899. // line system creation
  39900. var lineSystem = new BABYLON.LinesMesh(name, scene);
  39901. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  39902. vertexData.applyToMesh(lineSystem, options.updatable);
  39903. return lineSystem;
  39904. };
  39905. /**
  39906. * Creates a line mesh.
  39907. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  39908. * 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.
  39909. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39910. * The parameter `points` is an array successive Vector3.
  39911. * 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
  39912. * When updating an instance, remember that only point positions can change, not the number of points.
  39913. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39914. */
  39915. MeshBuilder.CreateLines = function (name, options, scene) {
  39916. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  39917. return lines;
  39918. };
  39919. /**
  39920. * Creates a dashed line mesh.
  39921. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  39922. * 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.
  39923. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39924. * The parameter `points` is an array successive Vector3.
  39925. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  39926. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  39927. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  39928. * 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
  39929. * When updating an instance, remember that only point positions can change, not the number of points.
  39930. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39931. */
  39932. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  39933. var points = options.points;
  39934. var instance = options.instance;
  39935. var gapSize = options.gapSize;
  39936. var dashNb = options.dashNb;
  39937. var dashSize = options.dashSize;
  39938. if (instance) {
  39939. var positionFunction = function (positions) {
  39940. var curvect = BABYLON.Vector3.Zero();
  39941. var nbSeg = positions.length / 6;
  39942. var lg = 0;
  39943. var nb = 0;
  39944. var shft = 0;
  39945. var dashshft = 0;
  39946. var curshft = 0;
  39947. var p = 0;
  39948. var i = 0;
  39949. var j = 0;
  39950. for (i = 0; i < points.length - 1; i++) {
  39951. points[i + 1].subtractToRef(points[i], curvect);
  39952. lg += curvect.length();
  39953. }
  39954. shft = lg / nbSeg;
  39955. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  39956. for (i = 0; i < points.length - 1; i++) {
  39957. points[i + 1].subtractToRef(points[i], curvect);
  39958. nb = Math.floor(curvect.length() / shft);
  39959. curvect.normalize();
  39960. j = 0;
  39961. while (j < nb && p < positions.length) {
  39962. curshft = shft * j;
  39963. positions[p] = points[i].x + curshft * curvect.x;
  39964. positions[p + 1] = points[i].y + curshft * curvect.y;
  39965. positions[p + 2] = points[i].z + curshft * curvect.z;
  39966. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  39967. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  39968. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  39969. p += 6;
  39970. j++;
  39971. }
  39972. }
  39973. while (p < positions.length) {
  39974. positions[p] = points[i].x;
  39975. positions[p + 1] = points[i].y;
  39976. positions[p + 2] = points[i].z;
  39977. p += 3;
  39978. }
  39979. };
  39980. instance.updateMeshPositions(positionFunction, false);
  39981. return instance;
  39982. }
  39983. // dashed lines creation
  39984. var dashedLines = new BABYLON.LinesMesh(name, scene);
  39985. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  39986. vertexData.applyToMesh(dashedLines, options.updatable);
  39987. dashedLines.dashSize = dashSize;
  39988. dashedLines.gapSize = gapSize;
  39989. return dashedLines;
  39990. };
  39991. /**
  39992. * Creates an extruded shape mesh.
  39993. * 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.
  39994. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  39995. *
  39996. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39997. * 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
  39998. * extruded along the Z axis.
  39999. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40000. * 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.
  40001. * The parameter `scale` (float, default 1) is the value to scale the shape.
  40002. * 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
  40003. * 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
  40004. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40005. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40006. * 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).
  40007. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40008. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40009. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40010. */
  40011. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  40012. var path = options.path;
  40013. var shape = options.shape;
  40014. var scale = options.scale || 1;
  40015. var rotation = options.rotation || 0;
  40016. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40017. var updatable = options.updatable;
  40018. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40019. var instance = options.instance;
  40020. var invertUV = options.invertUV || false;
  40021. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40022. };
  40023. /**
  40024. * Creates an custom extruded shape mesh.
  40025. * 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.
  40026. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  40027. *
  40028. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40029. * 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
  40030. * extruded along the Z axis.
  40031. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40032. * 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
  40033. * and the distance of this point from the begining of the path :
  40034. * ```javascript
  40035. * var rotationFunction = function(i, distance) {
  40036. * // do things
  40037. * return rotationValue; }
  40038. * ```
  40039. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  40040. * 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
  40041. * and the distance of this point from the begining of the path :
  40042. * ```javascript
  40043. * var scaleFunction = function(i, distance) {
  40044. * // do things
  40045. * return scaleValue;}
  40046. * ```
  40047. * It must returns a float value that will be the scale value applied to the shape on each path point.
  40048. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  40049. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  40050. * 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
  40051. * 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
  40052. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40053. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40054. * 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).
  40055. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40056. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40057. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40058. */
  40059. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  40060. var path = options.path;
  40061. var shape = options.shape;
  40062. var scaleFunction = options.scaleFunction || (function () { return 1; });
  40063. var rotationFunction = options.rotationFunction || (function () { return 0; });
  40064. var ribbonCloseArray = options.ribbonCloseArray || false;
  40065. var ribbonClosePath = options.ribbonClosePath || false;
  40066. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40067. var updatable = options.updatable;
  40068. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40069. var instance = options.instance;
  40070. var invertUV = options.invertUV || false;
  40071. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40072. };
  40073. /**
  40074. * Creates lathe mesh.
  40075. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  40076. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  40077. *
  40078. * 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
  40079. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  40080. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  40081. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  40082. * 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.
  40083. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  40084. * 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
  40085. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40086. * 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).
  40087. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40088. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40089. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40090. */
  40091. MeshBuilder.CreateLathe = function (name, options, scene) {
  40092. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  40093. var closed = (options.closed === undefined) ? true : options.closed;
  40094. var shape = options.shape;
  40095. var radius = options.radius || 1;
  40096. var tessellation = options.tessellation || 64;
  40097. var updatable = options.updatable;
  40098. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40099. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40100. var pi2 = Math.PI * 2;
  40101. var paths = new Array();
  40102. var invertUV = options.invertUV || false;
  40103. var i = 0;
  40104. var p = 0;
  40105. var step = pi2 / tessellation * arc;
  40106. var rotated;
  40107. var path = new Array();
  40108. ;
  40109. for (i = 0; i <= tessellation; i++) {
  40110. var path = [];
  40111. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  40112. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  40113. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  40114. }
  40115. for (p = 0; p < shape.length; p++) {
  40116. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  40117. path.push(rotated);
  40118. }
  40119. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  40120. 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));
  40121. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  40122. }
  40123. paths.push(path);
  40124. }
  40125. // lathe ribbon
  40126. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40127. return lathe;
  40128. };
  40129. /**
  40130. * Creates a plane mesh.
  40131. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40132. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  40133. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  40134. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  40135. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40136. * 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).
  40137. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40138. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40139. */
  40140. MeshBuilder.CreatePlane = function (name, options, scene) {
  40141. var plane = new BABYLON.Mesh(name, scene);
  40142. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40143. plane.sideOrientation = options.sideOrientation;
  40144. var vertexData = BABYLON.VertexData.CreatePlane(options);
  40145. vertexData.applyToMesh(plane, options.updatable);
  40146. if (options.sourcePlane) {
  40147. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  40148. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  40149. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  40150. plane.rotate(vectorProduct, product);
  40151. }
  40152. return plane;
  40153. };
  40154. /**
  40155. * Creates a ground mesh.
  40156. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40157. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  40158. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  40159. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40160. */
  40161. MeshBuilder.CreateGround = function (name, options, scene) {
  40162. var ground = new BABYLON.GroundMesh(name, scene);
  40163. ground._setReady(false);
  40164. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  40165. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  40166. ground._width = options.width || 1;
  40167. ground._height = options.height || 1;
  40168. ground._maxX = ground._width / 2;
  40169. ground._maxZ = ground._height / 2;
  40170. ground._minX = -ground._maxX;
  40171. ground._minZ = -ground._maxZ;
  40172. var vertexData = BABYLON.VertexData.CreateGround(options);
  40173. vertexData.applyToMesh(ground, options.updatable);
  40174. ground._setReady(true);
  40175. return ground;
  40176. };
  40177. /**
  40178. * Creates a tiled ground mesh.
  40179. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  40180. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  40181. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  40182. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  40183. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  40184. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  40185. * numbers of subdivisions on the ground width and height of each tile.
  40186. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40187. */
  40188. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  40189. var tiledGround = new BABYLON.Mesh(name, scene);
  40190. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  40191. vertexData.applyToMesh(tiledGround, options.updatable);
  40192. return tiledGround;
  40193. };
  40194. /**
  40195. * Creates a ground mesh from a height map.
  40196. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  40197. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  40198. * The parameter `url` sets the URL of the height map image resource.
  40199. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  40200. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  40201. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  40202. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  40203. * 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.
  40204. * 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).
  40205. * This function is passed the newly built mesh :
  40206. * ```javascript
  40207. * function(mesh) { // do things
  40208. * return; }
  40209. * ```
  40210. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40211. */
  40212. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  40213. var width = options.width || 10.0;
  40214. var height = options.height || 10.0;
  40215. var subdivisions = options.subdivisions || 1 | 0;
  40216. var minHeight = options.minHeight || 0.0;
  40217. var maxHeight = options.maxHeight || 10.0;
  40218. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  40219. var updatable = options.updatable;
  40220. var onReady = options.onReady;
  40221. var ground = new BABYLON.GroundMesh(name, scene);
  40222. ground._subdivisionsX = subdivisions;
  40223. ground._subdivisionsY = subdivisions;
  40224. ground._width = width;
  40225. ground._height = height;
  40226. ground._maxX = ground._width / 2.0;
  40227. ground._maxZ = ground._height / 2.0;
  40228. ground._minX = -ground._maxX;
  40229. ground._minZ = -ground._maxZ;
  40230. ground._setReady(false);
  40231. var onload = function (img) {
  40232. // Getting height map data
  40233. var canvas = document.createElement("canvas");
  40234. var context = canvas.getContext("2d");
  40235. var bufferWidth = img.width;
  40236. var bufferHeight = img.height;
  40237. canvas.width = bufferWidth;
  40238. canvas.height = bufferHeight;
  40239. context.drawImage(img, 0, 0);
  40240. // Create VertexData from map data
  40241. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  40242. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  40243. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  40244. width: width, height: height,
  40245. subdivisions: subdivisions,
  40246. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  40247. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  40248. });
  40249. vertexData.applyToMesh(ground, updatable);
  40250. ground._setReady(true);
  40251. //execute ready callback, if set
  40252. if (onReady) {
  40253. onReady(ground);
  40254. }
  40255. };
  40256. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  40257. return ground;
  40258. };
  40259. /**
  40260. * Creates a polygon mesh.
  40261. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  40262. * 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.
  40263. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40264. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40265. * 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).
  40266. * Remember you can only change the shape positions, not their number when updating a polygon.
  40267. */
  40268. MeshBuilder.CreatePolygon = function (name, options, scene) {
  40269. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40270. var shape = options.shape;
  40271. var holes = options.holes || [];
  40272. var depth = options.depth || 0;
  40273. var contours = [];
  40274. var hole = [];
  40275. for (var i = 0; i < shape.length; i++) {
  40276. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  40277. }
  40278. var epsilon = 0.00000001;
  40279. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  40280. contours.pop();
  40281. }
  40282. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  40283. for (var hNb = 0; hNb < holes.length; hNb++) {
  40284. hole = [];
  40285. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  40286. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  40287. }
  40288. polygonTriangulation.addHole(hole);
  40289. }
  40290. var polygon = polygonTriangulation.build(options.updatable, depth);
  40291. polygon.sideOrientation = options.sideOrientation;
  40292. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  40293. vertexData.applyToMesh(polygon, options.updatable);
  40294. return polygon;
  40295. };
  40296. ;
  40297. /**
  40298. * Creates an extruded polygon mesh, with depth in the Y direction.
  40299. * 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).
  40300. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40301. */
  40302. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  40303. return MeshBuilder.CreatePolygon(name, options, scene);
  40304. };
  40305. ;
  40306. /**
  40307. * Creates a tube mesh.
  40308. * 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.
  40309. *
  40310. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  40311. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  40312. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  40313. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  40314. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  40315. * 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.
  40316. * It must return a radius value (positive float) :
  40317. * ```javascript
  40318. * var radiusFunction = function(i, distance) {
  40319. * // do things
  40320. * return radius; }
  40321. * ```
  40322. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  40323. * 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
  40324. * 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
  40325. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40326. * 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).
  40327. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40328. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40329. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40330. */
  40331. MeshBuilder.CreateTube = function (name, options, scene) {
  40332. var path = options.path;
  40333. var radius = options.radius || 1.0;
  40334. var tessellation = options.tessellation || 64 | 0;
  40335. var radiusFunction = options.radiusFunction;
  40336. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40337. var invertUV = options.invertUV || false;
  40338. var updatable = options.updatable;
  40339. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40340. var instance = options.instance;
  40341. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  40342. // tube geometry
  40343. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  40344. var tangents = path3D.getTangents();
  40345. var normals = path3D.getNormals();
  40346. var distances = path3D.getDistances();
  40347. var pi2 = Math.PI * 2;
  40348. var step = pi2 / tessellation * arc;
  40349. var returnRadius = function () { return radius; };
  40350. var radiusFunctionFinal = radiusFunction || returnRadius;
  40351. var circlePath;
  40352. var rad;
  40353. var normal;
  40354. var rotated;
  40355. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  40356. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  40357. for (var i = 0; i < path.length; i++) {
  40358. rad = radiusFunctionFinal(i, distances[i]); // current radius
  40359. circlePath = Array(); // current circle array
  40360. normal = normals[i]; // current normal
  40361. for (var t = 0; t < tessellation; t++) {
  40362. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  40363. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  40364. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  40365. rotated.scaleInPlace(rad).addInPlace(path[i]);
  40366. circlePath[t] = rotated;
  40367. }
  40368. circlePaths[index] = circlePath;
  40369. index++;
  40370. }
  40371. // cap
  40372. var capPath = function (nbPoints, pathIndex) {
  40373. var pointCap = Array();
  40374. for (var i = 0; i < nbPoints; i++) {
  40375. pointCap.push(path[pathIndex]);
  40376. }
  40377. return pointCap;
  40378. };
  40379. switch (cap) {
  40380. case BABYLON.Mesh.NO_CAP:
  40381. break;
  40382. case BABYLON.Mesh.CAP_START:
  40383. circlePaths[0] = capPath(tessellation, 0);
  40384. circlePaths[1] = circlePaths[2].slice(0);
  40385. break;
  40386. case BABYLON.Mesh.CAP_END:
  40387. circlePaths[index] = circlePaths[index - 1].slice(0);
  40388. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40389. break;
  40390. case BABYLON.Mesh.CAP_ALL:
  40391. circlePaths[0] = capPath(tessellation, 0);
  40392. circlePaths[1] = circlePaths[2].slice(0);
  40393. circlePaths[index] = circlePaths[index - 1].slice(0);
  40394. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40395. break;
  40396. default:
  40397. break;
  40398. }
  40399. return circlePaths;
  40400. };
  40401. var path3D;
  40402. var pathArray;
  40403. if (instance) {
  40404. var arc = options.arc || instance.arc;
  40405. path3D = (instance.path3D).update(path);
  40406. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  40407. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  40408. instance.path3D = path3D;
  40409. instance.pathArray = pathArray;
  40410. instance.arc = arc;
  40411. return instance;
  40412. }
  40413. // tube creation
  40414. path3D = new BABYLON.Path3D(path);
  40415. var newPathArray = new Array();
  40416. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40417. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  40418. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40419. tube.pathArray = pathArray;
  40420. tube.path3D = path3D;
  40421. tube.tessellation = tessellation;
  40422. tube.cap = cap;
  40423. tube.arc = options.arc;
  40424. return tube;
  40425. };
  40426. /**
  40427. * Creates a polyhedron mesh.
  40428. *
  40429. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  40430. * 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
  40431. * to choose the wanted type.
  40432. * The parameter `size` (positive float, default 1) sets the polygon size.
  40433. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  40434. * 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`.
  40435. * 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
  40436. * 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)`).
  40437. * 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
  40438. * 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.
  40439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40440. * 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).
  40441. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40443. */
  40444. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  40445. var polyhedron = new BABYLON.Mesh(name, scene);
  40446. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40447. polyhedron.sideOrientation = options.sideOrientation;
  40448. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  40449. vertexData.applyToMesh(polyhedron, options.updatable);
  40450. return polyhedron;
  40451. };
  40452. /**
  40453. * Creates a decal mesh.
  40454. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  40455. * 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.
  40456. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  40457. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  40458. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  40459. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  40460. */
  40461. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  40462. var indices = sourceMesh.getIndices();
  40463. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40464. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40465. var position = options.position || BABYLON.Vector3.Zero();
  40466. var normal = options.normal || BABYLON.Vector3.Up();
  40467. var size = options.size || BABYLON.Vector3.One();
  40468. var angle = options.angle || 0;
  40469. // Getting correct rotation
  40470. if (!normal) {
  40471. var target = new BABYLON.Vector3(0, 0, 1);
  40472. var camera = sourceMesh.getScene().activeCamera;
  40473. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  40474. normal = camera.globalPosition.subtract(cameraWorldTarget);
  40475. }
  40476. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  40477. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  40478. var pitch = Math.atan2(normal.y, len);
  40479. // Matrix
  40480. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  40481. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  40482. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  40483. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  40484. var vertexData = new BABYLON.VertexData();
  40485. vertexData.indices = [];
  40486. vertexData.positions = [];
  40487. vertexData.normals = [];
  40488. vertexData.uvs = [];
  40489. var currentVertexDataIndex = 0;
  40490. var extractDecalVector3 = function (indexId) {
  40491. var vertexId = indices[indexId];
  40492. var result = new BABYLON.PositionNormalVertex();
  40493. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  40494. // Send vector to decal local world
  40495. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  40496. // Get normal
  40497. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  40498. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  40499. return result;
  40500. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  40501. var clip = function (vertices, axis) {
  40502. if (vertices.length === 0) {
  40503. return vertices;
  40504. }
  40505. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  40506. var clipVertices = function (v0, v1) {
  40507. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  40508. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  40509. };
  40510. var result = new Array();
  40511. for (var index = 0; index < vertices.length; index += 3) {
  40512. var v1Out;
  40513. var v2Out;
  40514. var v3Out;
  40515. var total = 0;
  40516. var nV1, nV2, nV3, nV4;
  40517. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  40518. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  40519. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  40520. v1Out = d1 > 0;
  40521. v2Out = d2 > 0;
  40522. v3Out = d3 > 0;
  40523. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  40524. switch (total) {
  40525. case 0:
  40526. result.push(vertices[index]);
  40527. result.push(vertices[index + 1]);
  40528. result.push(vertices[index + 2]);
  40529. break;
  40530. case 1:
  40531. if (v1Out) {
  40532. nV1 = vertices[index + 1];
  40533. nV2 = vertices[index + 2];
  40534. nV3 = clipVertices(vertices[index], nV1);
  40535. nV4 = clipVertices(vertices[index], nV2);
  40536. }
  40537. if (v2Out) {
  40538. nV1 = vertices[index];
  40539. nV2 = vertices[index + 2];
  40540. nV3 = clipVertices(vertices[index + 1], nV1);
  40541. nV4 = clipVertices(vertices[index + 1], nV2);
  40542. result.push(nV3);
  40543. result.push(nV2.clone());
  40544. result.push(nV1.clone());
  40545. result.push(nV2.clone());
  40546. result.push(nV3.clone());
  40547. result.push(nV4);
  40548. break;
  40549. }
  40550. if (v3Out) {
  40551. nV1 = vertices[index];
  40552. nV2 = vertices[index + 1];
  40553. nV3 = clipVertices(vertices[index + 2], nV1);
  40554. nV4 = clipVertices(vertices[index + 2], nV2);
  40555. }
  40556. result.push(nV1.clone());
  40557. result.push(nV2.clone());
  40558. result.push(nV3);
  40559. result.push(nV4);
  40560. result.push(nV3.clone());
  40561. result.push(nV2.clone());
  40562. break;
  40563. case 2:
  40564. if (!v1Out) {
  40565. nV1 = vertices[index].clone();
  40566. nV2 = clipVertices(nV1, vertices[index + 1]);
  40567. nV3 = clipVertices(nV1, vertices[index + 2]);
  40568. result.push(nV1);
  40569. result.push(nV2);
  40570. result.push(nV3);
  40571. }
  40572. if (!v2Out) {
  40573. nV1 = vertices[index + 1].clone();
  40574. nV2 = clipVertices(nV1, vertices[index + 2]);
  40575. nV3 = clipVertices(nV1, vertices[index]);
  40576. result.push(nV1);
  40577. result.push(nV2);
  40578. result.push(nV3);
  40579. }
  40580. if (!v3Out) {
  40581. nV1 = vertices[index + 2].clone();
  40582. nV2 = clipVertices(nV1, vertices[index]);
  40583. nV3 = clipVertices(nV1, vertices[index + 1]);
  40584. result.push(nV1);
  40585. result.push(nV2);
  40586. result.push(nV3);
  40587. }
  40588. break;
  40589. case 3:
  40590. break;
  40591. }
  40592. }
  40593. return result;
  40594. };
  40595. for (var index = 0; index < indices.length; index += 3) {
  40596. var faceVertices = new Array();
  40597. faceVertices.push(extractDecalVector3(index));
  40598. faceVertices.push(extractDecalVector3(index + 1));
  40599. faceVertices.push(extractDecalVector3(index + 2));
  40600. // Clip
  40601. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  40602. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  40603. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  40604. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  40605. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  40606. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  40607. if (faceVertices.length === 0) {
  40608. continue;
  40609. }
  40610. // Add UVs and get back to world
  40611. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  40612. var vertex = faceVertices[vIndex];
  40613. //TODO check for Int32Array | Uint32Array | Uint16Array
  40614. vertexData.indices.push(currentVertexDataIndex);
  40615. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  40616. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  40617. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  40618. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  40619. currentVertexDataIndex++;
  40620. }
  40621. }
  40622. // Return mesh
  40623. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  40624. vertexData.applyToMesh(decal);
  40625. decal.position = position.clone();
  40626. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  40627. return decal;
  40628. };
  40629. // Privates
  40630. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  40631. // extrusion geometry
  40632. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  40633. var tangents = path3D.getTangents();
  40634. var normals = path3D.getNormals();
  40635. var binormals = path3D.getBinormals();
  40636. var distances = path3D.getDistances();
  40637. var angle = 0;
  40638. var returnScale = function () { return scale; };
  40639. var returnRotation = function () { return rotation; };
  40640. var rotate = custom ? rotateFunction : returnRotation;
  40641. var scl = custom ? scaleFunction : returnScale;
  40642. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  40643. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  40644. for (var i = 0; i < curve.length; i++) {
  40645. var shapePath = new Array();
  40646. var angleStep = rotate(i, distances[i]);
  40647. var scaleRatio = scl(i, distances[i]);
  40648. for (var p = 0; p < shape.length; p++) {
  40649. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  40650. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  40651. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  40652. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  40653. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  40654. shapePath[p] = rotated;
  40655. }
  40656. shapePaths[index] = shapePath;
  40657. angle += angleStep;
  40658. index++;
  40659. }
  40660. // cap
  40661. var capPath = function (shapePath) {
  40662. var pointCap = Array();
  40663. var barycenter = BABYLON.Vector3.Zero();
  40664. var i;
  40665. for (i = 0; i < shapePath.length; i++) {
  40666. barycenter.addInPlace(shapePath[i]);
  40667. }
  40668. barycenter.scaleInPlace(1.0 / shapePath.length);
  40669. for (i = 0; i < shapePath.length; i++) {
  40670. pointCap.push(barycenter);
  40671. }
  40672. return pointCap;
  40673. };
  40674. switch (cap) {
  40675. case BABYLON.Mesh.NO_CAP:
  40676. break;
  40677. case BABYLON.Mesh.CAP_START:
  40678. shapePaths[0] = capPath(shapePaths[2]);
  40679. shapePaths[1] = shapePaths[2];
  40680. break;
  40681. case BABYLON.Mesh.CAP_END:
  40682. shapePaths[index] = shapePaths[index - 1];
  40683. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40684. break;
  40685. case BABYLON.Mesh.CAP_ALL:
  40686. shapePaths[0] = capPath(shapePaths[2]);
  40687. shapePaths[1] = shapePaths[2];
  40688. shapePaths[index] = shapePaths[index - 1];
  40689. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40690. break;
  40691. default:
  40692. break;
  40693. }
  40694. return shapePaths;
  40695. };
  40696. var path3D;
  40697. var pathArray;
  40698. if (instance) {
  40699. path3D = (instance.path3D).update(curve);
  40700. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  40701. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  40702. return instance;
  40703. }
  40704. // extruded shape creation
  40705. path3D = new BABYLON.Path3D(curve);
  40706. var newShapePaths = new Array();
  40707. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40708. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  40709. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  40710. extrudedGeneric.pathArray = pathArray;
  40711. extrudedGeneric.path3D = path3D;
  40712. extrudedGeneric.cap = cap;
  40713. return extrudedGeneric;
  40714. };
  40715. return MeshBuilder;
  40716. }());
  40717. BABYLON.MeshBuilder = MeshBuilder;
  40718. })(BABYLON || (BABYLON = {}));
  40719. //# sourceMappingURL=babylon.meshBuilder.js.map
  40720. var BABYLON;
  40721. (function (BABYLON) {
  40722. var Layer = (function () {
  40723. function Layer(name, imgUrl, scene, isBackground, color) {
  40724. this.name = name;
  40725. this.scale = new BABYLON.Vector2(1, 1);
  40726. this.offset = new BABYLON.Vector2(0, 0);
  40727. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  40728. this.layerMask = 0x0FFFFFFF;
  40729. this._vertexBuffers = {};
  40730. // Events
  40731. /**
  40732. * An event triggered when the layer is disposed.
  40733. * @type {BABYLON.Observable}
  40734. */
  40735. this.onDisposeObservable = new BABYLON.Observable();
  40736. /**
  40737. * An event triggered before rendering the scene
  40738. * @type {BABYLON.Observable}
  40739. */
  40740. this.onBeforeRenderObservable = new BABYLON.Observable();
  40741. /**
  40742. * An event triggered after rendering the scene
  40743. * @type {BABYLON.Observable}
  40744. */
  40745. this.onAfterRenderObservable = new BABYLON.Observable();
  40746. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  40747. this.isBackground = isBackground === undefined ? true : isBackground;
  40748. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  40749. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40750. this._scene.layers.push(this);
  40751. var engine = this._scene.getEngine();
  40752. // VBO
  40753. var vertices = [];
  40754. vertices.push(1, 1);
  40755. vertices.push(-1, 1);
  40756. vertices.push(-1, -1);
  40757. vertices.push(1, -1);
  40758. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40759. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  40760. this._createIndexBuffer();
  40761. // Effects
  40762. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  40763. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  40764. }
  40765. Object.defineProperty(Layer.prototype, "onDispose", {
  40766. set: function (callback) {
  40767. if (this._onDisposeObserver) {
  40768. this.onDisposeObservable.remove(this._onDisposeObserver);
  40769. }
  40770. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  40771. },
  40772. enumerable: true,
  40773. configurable: true
  40774. });
  40775. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  40776. set: function (callback) {
  40777. if (this._onBeforeRenderObserver) {
  40778. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40779. }
  40780. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40781. },
  40782. enumerable: true,
  40783. configurable: true
  40784. });
  40785. Object.defineProperty(Layer.prototype, "onAfterRender", {
  40786. set: function (callback) {
  40787. if (this._onAfterRenderObserver) {
  40788. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40789. }
  40790. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40791. },
  40792. enumerable: true,
  40793. configurable: true
  40794. });
  40795. Layer.prototype._createIndexBuffer = function () {
  40796. var engine = this._scene.getEngine();
  40797. // Indices
  40798. var indices = [];
  40799. indices.push(0);
  40800. indices.push(1);
  40801. indices.push(2);
  40802. indices.push(0);
  40803. indices.push(2);
  40804. indices.push(3);
  40805. this._indexBuffer = engine.createIndexBuffer(indices);
  40806. };
  40807. Layer.prototype._rebuild = function () {
  40808. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  40809. this._createIndexBuffer();
  40810. };
  40811. Layer.prototype.render = function () {
  40812. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  40813. // Check
  40814. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  40815. return;
  40816. var engine = this._scene.getEngine();
  40817. this.onBeforeRenderObservable.notifyObservers(this);
  40818. // Render
  40819. engine.enableEffect(currentEffect);
  40820. engine.setState(false);
  40821. // Texture
  40822. currentEffect.setTexture("textureSampler", this.texture);
  40823. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  40824. // Color
  40825. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  40826. // Scale / offset
  40827. currentEffect.setVector2("offset", this.offset);
  40828. currentEffect.setVector2("scale", this.scale);
  40829. // VBOs
  40830. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  40831. // Draw order
  40832. if (!this.alphaTest) {
  40833. engine.setAlphaMode(this.alphaBlendingMode);
  40834. engine.draw(true, 0, 6);
  40835. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40836. }
  40837. else {
  40838. engine.draw(true, 0, 6);
  40839. }
  40840. this.onAfterRenderObservable.notifyObservers(this);
  40841. };
  40842. Layer.prototype.dispose = function () {
  40843. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40844. if (vertexBuffer) {
  40845. vertexBuffer.dispose();
  40846. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40847. }
  40848. if (this._indexBuffer) {
  40849. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40850. this._indexBuffer = null;
  40851. }
  40852. if (this.texture) {
  40853. this.texture.dispose();
  40854. this.texture = null;
  40855. }
  40856. // Remove from scene
  40857. var index = this._scene.layers.indexOf(this);
  40858. this._scene.layers.splice(index, 1);
  40859. // Callback
  40860. this.onDisposeObservable.notifyObservers(this);
  40861. this.onDisposeObservable.clear();
  40862. this.onAfterRenderObservable.clear();
  40863. this.onBeforeRenderObservable.clear();
  40864. };
  40865. return Layer;
  40866. }());
  40867. BABYLON.Layer = Layer;
  40868. })(BABYLON || (BABYLON = {}));
  40869. //# sourceMappingURL=babylon.layer.js.map
  40870. var BABYLON;
  40871. (function (BABYLON) {
  40872. var BlurPostProcess = (function (_super) {
  40873. __extends(BlurPostProcess, _super);
  40874. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  40875. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40876. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40877. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  40878. _this.direction = direction;
  40879. _this._packedFloat = false;
  40880. _this.onApplyObservable.add(function (effect) {
  40881. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  40882. });
  40883. _this.kernel = kernel;
  40884. return _this;
  40885. }
  40886. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  40887. /**
  40888. * Gets the length in pixels of the blur sample region
  40889. */
  40890. get: function () {
  40891. return this._idealKernel;
  40892. },
  40893. /**
  40894. * Sets the length in pixels of the blur sample region
  40895. */
  40896. set: function (v) {
  40897. if (this._idealKernel === v) {
  40898. return;
  40899. }
  40900. v = Math.max(v, 1);
  40901. this._idealKernel = v;
  40902. this._kernel = this._nearestBestKernel(v);
  40903. this._updateParameters();
  40904. },
  40905. enumerable: true,
  40906. configurable: true
  40907. });
  40908. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  40909. /**
  40910. * Gets wether or not the blur is unpacking/repacking floats
  40911. */
  40912. get: function () {
  40913. return this._packedFloat;
  40914. },
  40915. /**
  40916. * Sets wether or not the blur needs to unpack/repack floats
  40917. */
  40918. set: function (v) {
  40919. if (this._packedFloat === v) {
  40920. return;
  40921. }
  40922. this._packedFloat = v;
  40923. this._updateParameters();
  40924. },
  40925. enumerable: true,
  40926. configurable: true
  40927. });
  40928. BlurPostProcess.prototype._updateParameters = function () {
  40929. // Generate sampling offsets and weights
  40930. var N = this._kernel;
  40931. var centerIndex = (N - 1) / 2;
  40932. // Generate Gaussian sampling weights over kernel
  40933. var offsets = [];
  40934. var weights = [];
  40935. var totalWeight = 0;
  40936. for (var i = 0; i < N; i++) {
  40937. var u = i / (N - 1);
  40938. var w = this._gaussianWeight(u * 2.0 - 1);
  40939. offsets[i] = (i - centerIndex);
  40940. weights[i] = w;
  40941. totalWeight += w;
  40942. }
  40943. // Normalize weights
  40944. for (var i = 0; i < weights.length; i++) {
  40945. weights[i] /= totalWeight;
  40946. }
  40947. // Optimize: combine samples to take advantage of hardware linear sampling
  40948. // Walk from left to center, combining pairs (symmetrically)
  40949. var linearSamplingWeights = [];
  40950. var linearSamplingOffsets = [];
  40951. var linearSamplingMap = [];
  40952. for (var i = 0; i <= centerIndex; i += 2) {
  40953. var j = Math.min(i + 1, Math.floor(centerIndex));
  40954. var singleCenterSample = i === j;
  40955. if (singleCenterSample) {
  40956. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  40957. }
  40958. else {
  40959. var sharedCell = j === centerIndex;
  40960. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  40961. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  40962. if (offsetLinear === 0) {
  40963. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  40964. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  40965. }
  40966. else {
  40967. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  40968. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  40969. }
  40970. }
  40971. }
  40972. for (var i = 0; i < linearSamplingMap.length; i++) {
  40973. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  40974. linearSamplingWeights[i] = linearSamplingMap[i].w;
  40975. }
  40976. // Replace with optimized
  40977. offsets = linearSamplingOffsets;
  40978. weights = linearSamplingWeights;
  40979. // Generate shaders
  40980. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  40981. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  40982. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  40983. var defines = "";
  40984. for (var i = 0; i < varyingCount; i++) {
  40985. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  40986. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  40987. }
  40988. var depCount = 0;
  40989. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  40990. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  40991. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  40992. depCount++;
  40993. }
  40994. if (this.packedFloat) {
  40995. defines += "#define PACKEDFLOAT 1";
  40996. }
  40997. this.updateEffect(defines, null, null, {
  40998. varyingCount: varyingCount,
  40999. depCount: depCount
  41000. });
  41001. };
  41002. /**
  41003. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  41004. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  41005. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  41006. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  41007. * The gaps between physical kernels are compensated for in the weighting of the samples
  41008. * @param idealKernel Ideal blur kernel.
  41009. * @return Nearest best kernel.
  41010. */
  41011. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  41012. var v = Math.round(idealKernel);
  41013. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  41014. var k = _a[_i];
  41015. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  41016. return Math.max(k, 3);
  41017. }
  41018. }
  41019. return Math.max(v, 3);
  41020. };
  41021. /**
  41022. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  41023. * @param x The point on the Gaussian distribution to sample.
  41024. * @return the value of the Gaussian function at x.
  41025. */
  41026. BlurPostProcess.prototype._gaussianWeight = function (x) {
  41027. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  41028. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  41029. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  41030. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  41031. // truncated at around 1.3% of peak strength.
  41032. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  41033. var sigma = (1 / 3);
  41034. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  41035. var exponent = -((x * x) / (2.0 * sigma * sigma));
  41036. var weight = (1.0 / denominator) * Math.exp(exponent);
  41037. return weight;
  41038. };
  41039. /**
  41040. * Generates a string that can be used as a floating point number in GLSL.
  41041. * @param x Value to print.
  41042. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  41043. * @return GLSL float string.
  41044. */
  41045. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  41046. if (decimalFigures === void 0) { decimalFigures = 8; }
  41047. return x.toFixed(decimalFigures).replace(/0+$/, '');
  41048. };
  41049. return BlurPostProcess;
  41050. }(BABYLON.PostProcess));
  41051. BABYLON.BlurPostProcess = BlurPostProcess;
  41052. })(BABYLON || (BABYLON = {}));
  41053. //# sourceMappingURL=babylon.blurPostProcess.js.map
  41054. var BABYLON;
  41055. (function (BABYLON) {
  41056. var FxaaPostProcess = (function (_super) {
  41057. __extends(FxaaPostProcess, _super);
  41058. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41059. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41060. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  41061. _this.onApplyObservable.add(function (effect) {
  41062. var texelSize = _this.texelSize;
  41063. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  41064. });
  41065. return _this;
  41066. }
  41067. return FxaaPostProcess;
  41068. }(BABYLON.PostProcess));
  41069. BABYLON.FxaaPostProcess = FxaaPostProcess;
  41070. })(BABYLON || (BABYLON = {}));
  41071. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  41072. var BABYLON;
  41073. (function (BABYLON) {
  41074. var HighlightsPostProcess = (function (_super) {
  41075. __extends(HighlightsPostProcess, _super);
  41076. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41077. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41078. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  41079. }
  41080. return HighlightsPostProcess;
  41081. }(BABYLON.PostProcess));
  41082. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  41083. })(BABYLON || (BABYLON = {}));
  41084. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  41085. var BABYLON;
  41086. (function (BABYLON) {
  41087. var ImageProcessingPostProcess = (function (_super) {
  41088. __extends(ImageProcessingPostProcess, _super);
  41089. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41090. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41091. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  41092. _this._fromLinearSpace = true;
  41093. /**
  41094. * Defines cache preventing GC.
  41095. */
  41096. _this._defines = {
  41097. IMAGEPROCESSING: false,
  41098. VIGNETTE: false,
  41099. VIGNETTEBLENDMODEMULTIPLY: false,
  41100. VIGNETTEBLENDMODEOPAQUE: false,
  41101. TONEMAPPING: false,
  41102. CONTRAST: false,
  41103. COLORCURVES: false,
  41104. COLORGRADING: false,
  41105. FROMLINEARSPACE: false,
  41106. SAMPLER3DGREENDEPTH: false,
  41107. SAMPLER3DBGRMAP: false,
  41108. IMAGEPROCESSINGPOSTPROCESS: false,
  41109. EXPOSURE: false,
  41110. };
  41111. // Setup the default processing configuration to the scene.
  41112. _this._attachImageProcessingConfiguration(null, true);
  41113. _this.imageProcessingConfiguration.applyByPostProcess = true;
  41114. _this.onApply = function (effect) {
  41115. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  41116. };
  41117. return _this;
  41118. }
  41119. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  41120. /**
  41121. * Gets the image processing configuration used either in this material.
  41122. */
  41123. get: function () {
  41124. return this._imageProcessingConfiguration;
  41125. },
  41126. /**
  41127. * Sets the Default image processing configuration used either in the this material.
  41128. *
  41129. * If sets to null, the scene one is in use.
  41130. */
  41131. set: function (value) {
  41132. this._attachImageProcessingConfiguration(value);
  41133. },
  41134. enumerable: true,
  41135. configurable: true
  41136. });
  41137. /**
  41138. * Attaches a new image processing configuration to the PBR Material.
  41139. * @param configuration
  41140. */
  41141. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  41142. var _this = this;
  41143. if (doNotBuild === void 0) { doNotBuild = false; }
  41144. if (configuration === this._imageProcessingConfiguration) {
  41145. return;
  41146. }
  41147. // Detaches observer.
  41148. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41149. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41150. }
  41151. // Pick the scene configuration if needed.
  41152. if (!configuration) {
  41153. var camera = this.getCamera();
  41154. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  41155. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  41156. }
  41157. else {
  41158. this._imageProcessingConfiguration = configuration;
  41159. }
  41160. // Attaches observer.
  41161. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41162. _this._updateParameters();
  41163. });
  41164. // Ensure the effect will be rebuilt.
  41165. if (!doNotBuild) {
  41166. this._updateParameters();
  41167. }
  41168. };
  41169. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  41170. /**
  41171. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  41172. */
  41173. get: function () {
  41174. return this.imageProcessingConfiguration.colorCurves;
  41175. },
  41176. /**
  41177. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  41178. */
  41179. set: function (value) {
  41180. this.imageProcessingConfiguration.colorCurves = value;
  41181. },
  41182. enumerable: true,
  41183. configurable: true
  41184. });
  41185. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  41186. /**
  41187. * Gets wether the color curves effect is enabled.
  41188. */
  41189. get: function () {
  41190. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41191. },
  41192. /**
  41193. * Sets wether the color curves effect is enabled.
  41194. */
  41195. set: function (value) {
  41196. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41197. },
  41198. enumerable: true,
  41199. configurable: true
  41200. });
  41201. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  41202. /**
  41203. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  41204. */
  41205. get: function () {
  41206. return this.imageProcessingConfiguration.colorGradingTexture;
  41207. },
  41208. /**
  41209. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  41210. */
  41211. set: function (value) {
  41212. this.imageProcessingConfiguration.colorGradingTexture = value;
  41213. },
  41214. enumerable: true,
  41215. configurable: true
  41216. });
  41217. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  41218. /**
  41219. * Gets wether the color grading effect is enabled.
  41220. */
  41221. get: function () {
  41222. return this.imageProcessingConfiguration.colorGradingEnabled;
  41223. },
  41224. /**
  41225. * Gets wether the color grading effect is enabled.
  41226. */
  41227. set: function (value) {
  41228. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41229. },
  41230. enumerable: true,
  41231. configurable: true
  41232. });
  41233. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  41234. /**
  41235. * Gets exposure used in the effect.
  41236. */
  41237. get: function () {
  41238. return this.imageProcessingConfiguration.exposure;
  41239. },
  41240. /**
  41241. * Sets exposure used in the effect.
  41242. */
  41243. set: function (value) {
  41244. this.imageProcessingConfiguration.exposure = value;
  41245. },
  41246. enumerable: true,
  41247. configurable: true
  41248. });
  41249. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  41250. /**
  41251. * Gets wether tonemapping is enabled or not.
  41252. */
  41253. get: function () {
  41254. return this._imageProcessingConfiguration.toneMappingEnabled;
  41255. },
  41256. /**
  41257. * Sets wether tonemapping is enabled or not
  41258. */
  41259. set: function (value) {
  41260. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41261. },
  41262. enumerable: true,
  41263. configurable: true
  41264. });
  41265. ;
  41266. ;
  41267. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  41268. /**
  41269. * Gets contrast used in the effect.
  41270. */
  41271. get: function () {
  41272. return this.imageProcessingConfiguration.contrast;
  41273. },
  41274. /**
  41275. * Sets contrast used in the effect.
  41276. */
  41277. set: function (value) {
  41278. this.imageProcessingConfiguration.contrast = value;
  41279. },
  41280. enumerable: true,
  41281. configurable: true
  41282. });
  41283. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  41284. /**
  41285. * Gets Vignette stretch size.
  41286. */
  41287. get: function () {
  41288. return this.imageProcessingConfiguration.vignetteStretch;
  41289. },
  41290. /**
  41291. * Sets Vignette stretch size.
  41292. */
  41293. set: function (value) {
  41294. this.imageProcessingConfiguration.vignetteStretch = value;
  41295. },
  41296. enumerable: true,
  41297. configurable: true
  41298. });
  41299. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  41300. /**
  41301. * Gets Vignette centre X Offset.
  41302. */
  41303. get: function () {
  41304. return this.imageProcessingConfiguration.vignetteCentreX;
  41305. },
  41306. /**
  41307. * Sets Vignette centre X Offset.
  41308. */
  41309. set: function (value) {
  41310. this.imageProcessingConfiguration.vignetteCentreX = value;
  41311. },
  41312. enumerable: true,
  41313. configurable: true
  41314. });
  41315. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  41316. /**
  41317. * Gets Vignette centre Y Offset.
  41318. */
  41319. get: function () {
  41320. return this.imageProcessingConfiguration.vignetteCentreY;
  41321. },
  41322. /**
  41323. * Sets Vignette centre Y Offset.
  41324. */
  41325. set: function (value) {
  41326. this.imageProcessingConfiguration.vignetteCentreY = value;
  41327. },
  41328. enumerable: true,
  41329. configurable: true
  41330. });
  41331. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  41332. /**
  41333. * Gets Vignette weight or intensity of the vignette effect.
  41334. */
  41335. get: function () {
  41336. return this.imageProcessingConfiguration.vignetteWeight;
  41337. },
  41338. /**
  41339. * Sets Vignette weight or intensity of the vignette effect.
  41340. */
  41341. set: function (value) {
  41342. this.imageProcessingConfiguration.vignetteWeight = value;
  41343. },
  41344. enumerable: true,
  41345. configurable: true
  41346. });
  41347. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  41348. /**
  41349. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41350. * if vignetteEnabled is set to true.
  41351. */
  41352. get: function () {
  41353. return this.imageProcessingConfiguration.vignetteColor;
  41354. },
  41355. /**
  41356. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41357. * if vignetteEnabled is set to true.
  41358. */
  41359. set: function (value) {
  41360. this.imageProcessingConfiguration.vignetteColor = value;
  41361. },
  41362. enumerable: true,
  41363. configurable: true
  41364. });
  41365. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  41366. /**
  41367. * Gets Camera field of view used by the Vignette effect.
  41368. */
  41369. get: function () {
  41370. return this.imageProcessingConfiguration.vignetteCameraFov;
  41371. },
  41372. /**
  41373. * Sets Camera field of view used by the Vignette effect.
  41374. */
  41375. set: function (value) {
  41376. this.imageProcessingConfiguration.vignetteCameraFov = value;
  41377. },
  41378. enumerable: true,
  41379. configurable: true
  41380. });
  41381. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  41382. /**
  41383. * Gets the vignette blend mode allowing different kind of effect.
  41384. */
  41385. get: function () {
  41386. return this.imageProcessingConfiguration.vignetteBlendMode;
  41387. },
  41388. /**
  41389. * Sets the vignette blend mode allowing different kind of effect.
  41390. */
  41391. set: function (value) {
  41392. this.imageProcessingConfiguration.vignetteBlendMode = value;
  41393. },
  41394. enumerable: true,
  41395. configurable: true
  41396. });
  41397. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  41398. /**
  41399. * Gets wether the vignette effect is enabled.
  41400. */
  41401. get: function () {
  41402. return this.imageProcessingConfiguration.vignetteEnabled;
  41403. },
  41404. /**
  41405. * Sets wether the vignette effect is enabled.
  41406. */
  41407. set: function (value) {
  41408. this.imageProcessingConfiguration.vignetteEnabled = value;
  41409. },
  41410. enumerable: true,
  41411. configurable: true
  41412. });
  41413. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  41414. /**
  41415. * Gets wether the input of the processing is in Gamma or Linear Space.
  41416. */
  41417. get: function () {
  41418. return this._fromLinearSpace;
  41419. },
  41420. /**
  41421. * Sets wether the input of the processing is in Gamma or Linear Space.
  41422. */
  41423. set: function (value) {
  41424. if (this._fromLinearSpace === value) {
  41425. return;
  41426. }
  41427. this._fromLinearSpace = value;
  41428. this._updateParameters();
  41429. },
  41430. enumerable: true,
  41431. configurable: true
  41432. });
  41433. ImageProcessingPostProcess.prototype.getClassName = function () {
  41434. return "ImageProcessingPostProcess";
  41435. };
  41436. ImageProcessingPostProcess.prototype._updateParameters = function () {
  41437. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  41438. this.imageProcessingConfiguration.prepareDefines(this._defines);
  41439. var defines = "";
  41440. for (var define in this._defines) {
  41441. if (this._defines[define]) {
  41442. defines += "#define " + define + ";\r\n";
  41443. }
  41444. }
  41445. var samplers = ["textureSampler"];
  41446. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  41447. var uniforms = ["scale"];
  41448. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  41449. this.updateEffect(defines, uniforms, samplers);
  41450. };
  41451. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  41452. _super.prototype.dispose.call(this, camera);
  41453. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41454. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41455. }
  41456. this.imageProcessingConfiguration.applyByPostProcess = false;
  41457. };
  41458. __decorate([
  41459. BABYLON.serialize()
  41460. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  41461. return ImageProcessingPostProcess;
  41462. }(BABYLON.PostProcess));
  41463. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  41464. })(BABYLON || (BABYLON = {}));
  41465. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  41466. var BABYLON;
  41467. (function (BABYLON) {
  41468. /**
  41469. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41470. * It can help converting any input color in a desired output one. This can then be used to create effects
  41471. * from sepia, black and white to sixties or futuristic rendering...
  41472. *
  41473. * The only supported format is currently 3dl.
  41474. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41475. */
  41476. var ColorGradingTexture = (function (_super) {
  41477. __extends(ColorGradingTexture, _super);
  41478. /**
  41479. * Instantiates a ColorGradingTexture from the following parameters.
  41480. *
  41481. * @param url The location of the color gradind data (currently only supporting 3dl)
  41482. * @param scene The scene the texture will be used in
  41483. */
  41484. function ColorGradingTexture(url, scene) {
  41485. var _this = _super.call(this, scene) || this;
  41486. if (!url) {
  41487. return _this;
  41488. }
  41489. _this._textureMatrix = BABYLON.Matrix.Identity();
  41490. _this.name = url;
  41491. _this.url = url;
  41492. _this.hasAlpha = false;
  41493. _this.isCube = false;
  41494. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41495. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41496. _this.anisotropicFilteringLevel = 1;
  41497. _this._texture = _this._getFromCache(url, true);
  41498. if (!_this._texture) {
  41499. if (!scene.useDelayedTextureLoading) {
  41500. _this.loadTexture();
  41501. }
  41502. else {
  41503. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41504. }
  41505. }
  41506. return _this;
  41507. }
  41508. /**
  41509. * Returns the texture matrix used in most of the material.
  41510. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41511. */
  41512. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41513. return this._textureMatrix;
  41514. };
  41515. /**
  41516. * Occurs when the file being loaded is a .3dl LUT file.
  41517. */
  41518. ColorGradingTexture.prototype.load3dlTexture = function () {
  41519. var _this = this;
  41520. var mipLevels = 0;
  41521. var floatArrayView = null;
  41522. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41523. this._texture = texture;
  41524. var callback = function (text) {
  41525. var data;
  41526. var tempData;
  41527. var line;
  41528. var lines = text.split('\n');
  41529. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41530. var maxColor = 0;
  41531. for (var i = 0; i < lines.length; i++) {
  41532. line = lines[i];
  41533. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41534. continue;
  41535. if (line.indexOf('#') === 0)
  41536. continue;
  41537. var words = line.split(" ");
  41538. if (size === 0) {
  41539. // Number of space + one
  41540. size = words.length;
  41541. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41542. tempData = new Float32Array(size * size * size * 4);
  41543. continue;
  41544. }
  41545. if (size != 0) {
  41546. var r = Math.max(parseInt(words[0]), 0);
  41547. var g = Math.max(parseInt(words[1]), 0);
  41548. var b = Math.max(parseInt(words[2]), 0);
  41549. maxColor = Math.max(r, maxColor);
  41550. maxColor = Math.max(g, maxColor);
  41551. maxColor = Math.max(b, maxColor);
  41552. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41553. tempData[pixelStorageIndex + 0] = r;
  41554. tempData[pixelStorageIndex + 1] = g;
  41555. tempData[pixelStorageIndex + 2] = b;
  41556. pixelIndexSlice++;
  41557. if (pixelIndexSlice % size == 0) {
  41558. pixelIndexH++;
  41559. pixelIndexSlice = 0;
  41560. if (pixelIndexH % size == 0) {
  41561. pixelIndexW++;
  41562. pixelIndexH = 0;
  41563. }
  41564. }
  41565. }
  41566. }
  41567. for (var i = 0; i < tempData.length; i++) {
  41568. if (i > 0 && (i + 1) % 4 === 0) {
  41569. data[i] = 255;
  41570. }
  41571. else {
  41572. var value = tempData[i];
  41573. data[i] = (value / maxColor * 255);
  41574. }
  41575. }
  41576. texture.updateSize(size * size, size);
  41577. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41578. };
  41579. BABYLON.Tools.LoadFile(this.url, callback);
  41580. return this._texture;
  41581. };
  41582. /**
  41583. * Starts the loading process of the texture.
  41584. */
  41585. ColorGradingTexture.prototype.loadTexture = function () {
  41586. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41587. this.load3dlTexture();
  41588. }
  41589. };
  41590. /**
  41591. * Clones the color gradind texture.
  41592. */
  41593. ColorGradingTexture.prototype.clone = function () {
  41594. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41595. // Base texture
  41596. newTexture.level = this.level;
  41597. return newTexture;
  41598. };
  41599. /**
  41600. * Called during delayed load for textures.
  41601. */
  41602. ColorGradingTexture.prototype.delayLoad = function () {
  41603. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41604. return;
  41605. }
  41606. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41607. this._texture = this._getFromCache(this.url, true);
  41608. if (!this._texture) {
  41609. this.loadTexture();
  41610. }
  41611. };
  41612. /**
  41613. * Parses a color grading texture serialized by Babylon.
  41614. * @param parsedTexture The texture information being parsedTexture
  41615. * @param scene The scene to load the texture in
  41616. * @param rootUrl The root url of the data assets to load
  41617. * @return A color gradind texture
  41618. */
  41619. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41620. var texture = null;
  41621. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41622. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  41623. texture.name = parsedTexture.name;
  41624. texture.level = parsedTexture.level;
  41625. }
  41626. return texture;
  41627. };
  41628. /**
  41629. * Serializes the LUT texture to json format.
  41630. */
  41631. ColorGradingTexture.prototype.serialize = function () {
  41632. if (!this.name) {
  41633. return null;
  41634. }
  41635. var serializationObject = {};
  41636. serializationObject.name = this.name;
  41637. serializationObject.level = this.level;
  41638. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41639. return serializationObject;
  41640. };
  41641. /**
  41642. * Empty line regex stored for GC.
  41643. */
  41644. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41645. return ColorGradingTexture;
  41646. }(BABYLON.BaseTexture));
  41647. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41648. })(BABYLON || (BABYLON = {}));
  41649. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41650. var BABYLON;
  41651. (function (BABYLON) {
  41652. /**
  41653. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41654. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41655. * 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;
  41656. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41657. */
  41658. var ColorCurves = (function () {
  41659. function ColorCurves() {
  41660. this._dirty = true;
  41661. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41662. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41663. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41664. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41665. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41666. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41667. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41668. this._globalHue = 30;
  41669. this._globalDensity = 0;
  41670. this._globalSaturation = 0;
  41671. this._globalExposure = 0;
  41672. this._highlightsHue = 30;
  41673. this._highlightsDensity = 0;
  41674. this._highlightsSaturation = 0;
  41675. this._highlightsExposure = 0;
  41676. this._midtonesHue = 30;
  41677. this._midtonesDensity = 0;
  41678. this._midtonesSaturation = 0;
  41679. this._midtonesExposure = 0;
  41680. this._shadowsHue = 30;
  41681. this._shadowsDensity = 0;
  41682. this._shadowsSaturation = 0;
  41683. this._shadowsExposure = 0;
  41684. }
  41685. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41686. /**
  41687. * Gets the global Hue value.
  41688. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  41689. */
  41690. get: function () {
  41691. return this._globalHue;
  41692. },
  41693. /**
  41694. * Sets the global Hue value.
  41695. * 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).
  41696. */
  41697. set: function (value) {
  41698. this._globalHue = value;
  41699. this._dirty = true;
  41700. },
  41701. enumerable: true,
  41702. configurable: true
  41703. });
  41704. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41705. /**
  41706. * Gets the global Density value.
  41707. * 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.
  41708. * Values less than zero provide a filter of opposite hue.
  41709. */
  41710. get: function () {
  41711. return this._globalDensity;
  41712. },
  41713. /**
  41714. * Sets the global Density value.
  41715. * 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.
  41716. * Values less than zero provide a filter of opposite hue.
  41717. */
  41718. set: function (value) {
  41719. this._globalDensity = value;
  41720. this._dirty = true;
  41721. },
  41722. enumerable: true,
  41723. configurable: true
  41724. });
  41725. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41726. /**
  41727. * Gets the global Saturation value.
  41728. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  41729. */
  41730. get: function () {
  41731. return this._globalSaturation;
  41732. },
  41733. /**
  41734. * Sets the global Saturation value.
  41735. * 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.
  41736. */
  41737. set: function (value) {
  41738. this._globalSaturation = value;
  41739. this._dirty = true;
  41740. },
  41741. enumerable: true,
  41742. configurable: true
  41743. });
  41744. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41745. /**
  41746. * Gets the highlights Hue value.
  41747. * 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).
  41748. */
  41749. get: function () {
  41750. return this._highlightsHue;
  41751. },
  41752. /**
  41753. * Sets the highlights Hue value.
  41754. * 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).
  41755. */
  41756. set: function (value) {
  41757. this._highlightsHue = value;
  41758. this._dirty = true;
  41759. },
  41760. enumerable: true,
  41761. configurable: true
  41762. });
  41763. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41764. /**
  41765. * Gets the highlights Density value.
  41766. * 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.
  41767. * Values less than zero provide a filter of opposite hue.
  41768. */
  41769. get: function () {
  41770. return this._highlightsDensity;
  41771. },
  41772. /**
  41773. * Sets the highlights Density value.
  41774. * 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.
  41775. * Values less than zero provide a filter of opposite hue.
  41776. */
  41777. set: function (value) {
  41778. this._highlightsDensity = value;
  41779. this._dirty = true;
  41780. },
  41781. enumerable: true,
  41782. configurable: true
  41783. });
  41784. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41785. /**
  41786. * Gets the highlights Saturation value.
  41787. * 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.
  41788. */
  41789. get: function () {
  41790. return this._highlightsSaturation;
  41791. },
  41792. /**
  41793. * Sets the highlights Saturation value.
  41794. * 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.
  41795. */
  41796. set: function (value) {
  41797. this._highlightsSaturation = value;
  41798. this._dirty = true;
  41799. },
  41800. enumerable: true,
  41801. configurable: true
  41802. });
  41803. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41804. /**
  41805. * Gets the highlights Exposure value.
  41806. * 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.
  41807. */
  41808. get: function () {
  41809. return this._highlightsExposure;
  41810. },
  41811. /**
  41812. * Sets the highlights Exposure value.
  41813. * 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.
  41814. */
  41815. set: function (value) {
  41816. this._highlightsExposure = value;
  41817. this._dirty = true;
  41818. },
  41819. enumerable: true,
  41820. configurable: true
  41821. });
  41822. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41823. /**
  41824. * Gets the midtones Hue value.
  41825. * 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).
  41826. */
  41827. get: function () {
  41828. return this._midtonesHue;
  41829. },
  41830. /**
  41831. * Sets the midtones Hue value.
  41832. * 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).
  41833. */
  41834. set: function (value) {
  41835. this._midtonesHue = value;
  41836. this._dirty = true;
  41837. },
  41838. enumerable: true,
  41839. configurable: true
  41840. });
  41841. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41842. /**
  41843. * Gets the midtones Density value.
  41844. * 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.
  41845. * Values less than zero provide a filter of opposite hue.
  41846. */
  41847. get: function () {
  41848. return this._midtonesDensity;
  41849. },
  41850. /**
  41851. * Sets the midtones Density value.
  41852. * 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.
  41853. * Values less than zero provide a filter of opposite hue.
  41854. */
  41855. set: function (value) {
  41856. this._midtonesDensity = value;
  41857. this._dirty = true;
  41858. },
  41859. enumerable: true,
  41860. configurable: true
  41861. });
  41862. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41863. /**
  41864. * Gets the midtones Saturation value.
  41865. * 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.
  41866. */
  41867. get: function () {
  41868. return this._midtonesSaturation;
  41869. },
  41870. /**
  41871. * Sets the midtones Saturation value.
  41872. * 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.
  41873. */
  41874. set: function (value) {
  41875. this._midtonesSaturation = value;
  41876. this._dirty = true;
  41877. },
  41878. enumerable: true,
  41879. configurable: true
  41880. });
  41881. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41882. /**
  41883. * Gets the midtones Exposure value.
  41884. * 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.
  41885. */
  41886. get: function () {
  41887. return this._midtonesExposure;
  41888. },
  41889. /**
  41890. * Sets the midtones Exposure value.
  41891. * 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.
  41892. */
  41893. set: function (value) {
  41894. this._midtonesExposure = value;
  41895. this._dirty = true;
  41896. },
  41897. enumerable: true,
  41898. configurable: true
  41899. });
  41900. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41901. /**
  41902. * Gets the shadows Hue value.
  41903. * 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).
  41904. */
  41905. get: function () {
  41906. return this._shadowsHue;
  41907. },
  41908. /**
  41909. * Sets the shadows Hue value.
  41910. * 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).
  41911. */
  41912. set: function (value) {
  41913. this._shadowsHue = value;
  41914. this._dirty = true;
  41915. },
  41916. enumerable: true,
  41917. configurable: true
  41918. });
  41919. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41920. /**
  41921. * Gets the shadows Density value.
  41922. * 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.
  41923. * Values less than zero provide a filter of opposite hue.
  41924. */
  41925. get: function () {
  41926. return this._shadowsDensity;
  41927. },
  41928. /**
  41929. * Sets the shadows Density value.
  41930. * 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.
  41931. * Values less than zero provide a filter of opposite hue.
  41932. */
  41933. set: function (value) {
  41934. this._shadowsDensity = value;
  41935. this._dirty = true;
  41936. },
  41937. enumerable: true,
  41938. configurable: true
  41939. });
  41940. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41941. /**
  41942. * Gets the shadows Saturation value.
  41943. * 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.
  41944. */
  41945. get: function () {
  41946. return this._shadowsSaturation;
  41947. },
  41948. /**
  41949. * Sets the shadows Saturation value.
  41950. * 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.
  41951. */
  41952. set: function (value) {
  41953. this._shadowsSaturation = value;
  41954. this._dirty = true;
  41955. },
  41956. enumerable: true,
  41957. configurable: true
  41958. });
  41959. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41960. /**
  41961. * Gets the shadows Exposure value.
  41962. * 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.
  41963. */
  41964. get: function () {
  41965. return this._shadowsExposure;
  41966. },
  41967. /**
  41968. * Sets the shadows Exposure value.
  41969. * 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.
  41970. */
  41971. set: function (value) {
  41972. this._shadowsExposure = value;
  41973. this._dirty = true;
  41974. },
  41975. enumerable: true,
  41976. configurable: true
  41977. });
  41978. ColorCurves.prototype.getClassName = function () {
  41979. return "ColorCurves";
  41980. };
  41981. /**
  41982. * Binds the color curves to the shader.
  41983. * @param colorCurves The color curve to bind
  41984. * @param effect The effect to bind to
  41985. */
  41986. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41987. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41988. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41989. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41990. if (colorCurves._dirty) {
  41991. colorCurves._dirty = false;
  41992. // Fill in global info.
  41993. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41994. // Compute highlights info.
  41995. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41996. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41997. // Compute midtones info.
  41998. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41999. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42000. // Compute shadows info.
  42001. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42002. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42003. // Compute deltas (neutral is midtones).
  42004. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42005. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42006. }
  42007. if (effect) {
  42008. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42009. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42010. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42011. }
  42012. };
  42013. /**
  42014. * Prepare the list of uniforms associated with the ColorCurves effects.
  42015. * @param uniformsList The list of uniforms used in the effect
  42016. */
  42017. ColorCurves.PrepareUniforms = function (uniformsList) {
  42018. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42019. };
  42020. /**
  42021. * Returns color grading data based on a hue, density, saturation and exposure value.
  42022. * @param filterHue The hue of the color filter.
  42023. * @param filterDensity The density of the color filter.
  42024. * @param saturation The saturation.
  42025. * @param exposure The exposure.
  42026. * @param result The result data container.
  42027. */
  42028. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42029. if (hue == null) {
  42030. return;
  42031. }
  42032. hue = ColorCurves.clamp(hue, 0, 360);
  42033. density = ColorCurves.clamp(density, -100, 100);
  42034. saturation = ColorCurves.clamp(saturation, -100, 100);
  42035. exposure = ColorCurves.clamp(exposure, -100, 100);
  42036. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42037. // so that the maximum filter density is only 50% control. This provides fine control
  42038. // for small values and reasonable range.
  42039. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42040. density *= 0.5;
  42041. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42042. if (density < 0) {
  42043. density *= -1;
  42044. hue = (hue + 180) % 360;
  42045. }
  42046. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42047. result.scaleToRef(2, result);
  42048. result.a = 1 + 0.01 * saturation;
  42049. };
  42050. /**
  42051. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42052. * @param value The input slider value in range [-100,100].
  42053. * @returns Adjusted value.
  42054. */
  42055. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42056. value /= 100;
  42057. var x = Math.abs(value);
  42058. x = Math.pow(x, 2);
  42059. if (value < 0) {
  42060. x *= -1;
  42061. }
  42062. x *= 100;
  42063. return x;
  42064. };
  42065. /**
  42066. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42067. * @param hue The hue (H) input.
  42068. * @param saturation The saturation (S) input.
  42069. * @param brightness The brightness (B) input.
  42070. * @result An RGBA color represented as Vector4.
  42071. */
  42072. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42073. var h = ColorCurves.clamp(hue, 0, 360);
  42074. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42075. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42076. if (s === 0) {
  42077. result.r = v;
  42078. result.g = v;
  42079. result.b = v;
  42080. }
  42081. else {
  42082. // sector 0 to 5
  42083. h /= 60;
  42084. var i = Math.floor(h);
  42085. // fractional part of h
  42086. var f = h - i;
  42087. var p = v * (1 - s);
  42088. var q = v * (1 - s * f);
  42089. var t = v * (1 - s * (1 - f));
  42090. switch (i) {
  42091. case 0:
  42092. result.r = v;
  42093. result.g = t;
  42094. result.b = p;
  42095. break;
  42096. case 1:
  42097. result.r = q;
  42098. result.g = v;
  42099. result.b = p;
  42100. break;
  42101. case 2:
  42102. result.r = p;
  42103. result.g = v;
  42104. result.b = t;
  42105. break;
  42106. case 3:
  42107. result.r = p;
  42108. result.g = q;
  42109. result.b = v;
  42110. break;
  42111. case 4:
  42112. result.r = t;
  42113. result.g = p;
  42114. result.b = v;
  42115. break;
  42116. default:// case 5:
  42117. result.r = v;
  42118. result.g = p;
  42119. result.b = q;
  42120. break;
  42121. }
  42122. }
  42123. result.a = 1;
  42124. };
  42125. /**
  42126. * Returns a value clamped between min and max
  42127. * @param value The value to clamp
  42128. * @param min The minimum of value
  42129. * @param max The maximum of value
  42130. * @returns The clamped value.
  42131. */
  42132. ColorCurves.clamp = function (value, min, max) {
  42133. return Math.min(Math.max(value, min), max);
  42134. };
  42135. /**
  42136. * Clones the current color curve instance.
  42137. * @return The cloned curves
  42138. */
  42139. ColorCurves.prototype.clone = function () {
  42140. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42141. };
  42142. /**
  42143. * Serializes the current color curve instance to a json representation.
  42144. * @return a JSON representation
  42145. */
  42146. ColorCurves.prototype.serialize = function () {
  42147. return BABYLON.SerializationHelper.Serialize(this);
  42148. };
  42149. /**
  42150. * Parses the color curve from a json representation.
  42151. * @param source the JSON source to parse
  42152. * @return The parsed curves
  42153. */
  42154. ColorCurves.Parse = function (source) {
  42155. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42156. };
  42157. __decorate([
  42158. BABYLON.serialize()
  42159. ], ColorCurves.prototype, "_globalHue", void 0);
  42160. __decorate([
  42161. BABYLON.serialize()
  42162. ], ColorCurves.prototype, "_globalDensity", void 0);
  42163. __decorate([
  42164. BABYLON.serialize()
  42165. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42166. __decorate([
  42167. BABYLON.serialize()
  42168. ], ColorCurves.prototype, "_globalExposure", void 0);
  42169. __decorate([
  42170. BABYLON.serialize()
  42171. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42172. __decorate([
  42173. BABYLON.serialize()
  42174. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42175. __decorate([
  42176. BABYLON.serialize()
  42177. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42178. __decorate([
  42179. BABYLON.serialize()
  42180. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42181. __decorate([
  42182. BABYLON.serialize()
  42183. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42184. __decorate([
  42185. BABYLON.serialize()
  42186. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42187. __decorate([
  42188. BABYLON.serialize()
  42189. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42190. __decorate([
  42191. BABYLON.serialize()
  42192. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42193. return ColorCurves;
  42194. }());
  42195. BABYLON.ColorCurves = ColorCurves;
  42196. })(BABYLON || (BABYLON = {}));
  42197. //# sourceMappingURL=babylon.colorCurves.js.map
  42198. var BABYLON;
  42199. (function (BABYLON) {
  42200. var PostProcessRenderPipelineManager = (function () {
  42201. function PostProcessRenderPipelineManager() {
  42202. this._renderPipelines = {};
  42203. }
  42204. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  42205. this._renderPipelines[renderPipeline._name] = renderPipeline;
  42206. };
  42207. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  42208. var renderPipeline = this._renderPipelines[renderPipelineName];
  42209. if (!renderPipeline) {
  42210. return;
  42211. }
  42212. renderPipeline._attachCameras(cameras, unique);
  42213. };
  42214. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  42215. var renderPipeline = this._renderPipelines[renderPipelineName];
  42216. if (!renderPipeline) {
  42217. return;
  42218. }
  42219. renderPipeline._detachCameras(cameras);
  42220. };
  42221. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42222. var renderPipeline = this._renderPipelines[renderPipelineName];
  42223. if (!renderPipeline) {
  42224. return;
  42225. }
  42226. renderPipeline._enableEffect(renderEffectName, cameras);
  42227. };
  42228. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42229. var renderPipeline = this._renderPipelines[renderPipelineName];
  42230. if (!renderPipeline) {
  42231. return;
  42232. }
  42233. renderPipeline._disableEffect(renderEffectName, cameras);
  42234. };
  42235. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  42236. var renderPipeline = this._renderPipelines[renderPipelineName];
  42237. if (!renderPipeline) {
  42238. return;
  42239. }
  42240. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  42241. };
  42242. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  42243. var renderPipeline = this._renderPipelines[renderPipelineName];
  42244. if (!renderPipeline) {
  42245. return;
  42246. }
  42247. renderPipeline._disableDisplayOnlyPass(cameras);
  42248. };
  42249. PostProcessRenderPipelineManager.prototype.update = function () {
  42250. for (var renderPipelineName in this._renderPipelines) {
  42251. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  42252. var pipeline = this._renderPipelines[renderPipelineName];
  42253. if (!pipeline.isSupported) {
  42254. pipeline.dispose();
  42255. delete this._renderPipelines[renderPipelineName];
  42256. }
  42257. else {
  42258. pipeline._update();
  42259. }
  42260. }
  42261. }
  42262. };
  42263. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  42264. for (var renderPipelineName in this._renderPipelines) {
  42265. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  42266. var pipeline = this._renderPipelines[renderPipelineName];
  42267. pipeline._rebuild();
  42268. }
  42269. }
  42270. };
  42271. PostProcessRenderPipelineManager.prototype.dispose = function () {
  42272. for (var renderPipelineName in this._renderPipelines) {
  42273. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  42274. var pipeline = this._renderPipelines[renderPipelineName];
  42275. pipeline.dispose();
  42276. }
  42277. }
  42278. };
  42279. return PostProcessRenderPipelineManager;
  42280. }());
  42281. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  42282. })(BABYLON || (BABYLON = {}));
  42283. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  42284. var BABYLON;
  42285. (function (BABYLON) {
  42286. var PostProcessRenderPass = (function () {
  42287. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  42288. this._enabled = true;
  42289. this._refCount = 0;
  42290. this._name = name;
  42291. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  42292. this.setRenderList(renderList);
  42293. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  42294. this._renderTexture.onAfterRenderObservable.add(afterRender);
  42295. this._scene = scene;
  42296. this._renderList = renderList;
  42297. }
  42298. // private
  42299. PostProcessRenderPass.prototype._incRefCount = function () {
  42300. if (this._refCount === 0) {
  42301. this._scene.customRenderTargets.push(this._renderTexture);
  42302. }
  42303. return ++this._refCount;
  42304. };
  42305. PostProcessRenderPass.prototype._decRefCount = function () {
  42306. this._refCount--;
  42307. if (this._refCount <= 0) {
  42308. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  42309. }
  42310. return this._refCount;
  42311. };
  42312. PostProcessRenderPass.prototype._update = function () {
  42313. this.setRenderList(this._renderList);
  42314. };
  42315. // public
  42316. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  42317. this._renderTexture.renderList = renderList;
  42318. };
  42319. PostProcessRenderPass.prototype.getRenderTexture = function () {
  42320. return this._renderTexture;
  42321. };
  42322. return PostProcessRenderPass;
  42323. }());
  42324. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  42325. })(BABYLON || (BABYLON = {}));
  42326. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  42327. var BABYLON;
  42328. (function (BABYLON) {
  42329. var PostProcessRenderEffect = (function () {
  42330. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  42331. this._engine = engine;
  42332. this._name = name;
  42333. this._singleInstance = singleInstance || true;
  42334. this._getPostProcess = getPostProcess;
  42335. this._cameras = [];
  42336. this._indicesForCamera = [];
  42337. this._postProcesses = {};
  42338. this._renderPasses = {};
  42339. this._renderEffectAsPasses = {};
  42340. }
  42341. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  42342. get: function () {
  42343. for (var index in this._postProcesses) {
  42344. if (!this._postProcesses[index].isSupported) {
  42345. return false;
  42346. }
  42347. }
  42348. return true;
  42349. },
  42350. enumerable: true,
  42351. configurable: true
  42352. });
  42353. PostProcessRenderEffect.prototype._update = function () {
  42354. for (var renderPassName in this._renderPasses) {
  42355. this._renderPasses[renderPassName]._update();
  42356. }
  42357. };
  42358. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  42359. this._renderPasses[renderPass._name] = renderPass;
  42360. this._linkParameters();
  42361. };
  42362. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  42363. delete this._renderPasses[renderPass._name];
  42364. this._linkParameters();
  42365. };
  42366. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  42367. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  42368. this._linkParameters();
  42369. };
  42370. PostProcessRenderEffect.prototype.getPass = function (passName) {
  42371. for (var renderPassName in this._renderPasses) {
  42372. if (renderPassName === passName) {
  42373. return this._renderPasses[passName];
  42374. }
  42375. }
  42376. };
  42377. PostProcessRenderEffect.prototype.emptyPasses = function () {
  42378. this._renderPasses = {};
  42379. this._linkParameters();
  42380. };
  42381. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  42382. var cameraKey;
  42383. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42384. for (var i = 0; i < _cam.length; i++) {
  42385. var camera = _cam[i];
  42386. var cameraName = camera.name;
  42387. if (this._singleInstance) {
  42388. cameraKey = 0;
  42389. }
  42390. else {
  42391. cameraKey = cameraName;
  42392. }
  42393. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  42394. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  42395. if (!this._indicesForCamera[cameraName]) {
  42396. this._indicesForCamera[cameraName] = [];
  42397. }
  42398. this._indicesForCamera[cameraName].push(index);
  42399. if (this._cameras.indexOf(camera) === -1) {
  42400. this._cameras[cameraName] = camera;
  42401. }
  42402. for (var passName in this._renderPasses) {
  42403. this._renderPasses[passName]._incRefCount();
  42404. }
  42405. }
  42406. this._linkParameters();
  42407. };
  42408. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  42409. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42410. for (var i = 0; i < _cam.length; i++) {
  42411. var camera = _cam[i];
  42412. var cameraName = camera.name;
  42413. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42414. var index = this._cameras.indexOf(cameraName);
  42415. this._indicesForCamera.splice(index, 1);
  42416. this._cameras.splice(index, 1);
  42417. for (var passName in this._renderPasses) {
  42418. this._renderPasses[passName]._decRefCount();
  42419. }
  42420. }
  42421. };
  42422. PostProcessRenderEffect.prototype._enable = function (cameras) {
  42423. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42424. for (var i = 0; i < _cam.length; i++) {
  42425. var camera = _cam[i];
  42426. var cameraName = camera.name;
  42427. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  42428. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  42429. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  42430. }
  42431. }
  42432. for (var passName in this._renderPasses) {
  42433. this._renderPasses[passName]._incRefCount();
  42434. }
  42435. }
  42436. };
  42437. PostProcessRenderEffect.prototype._disable = function (cameras) {
  42438. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42439. for (var i = 0; i < _cam.length; i++) {
  42440. var camera = _cam[i];
  42441. var cameraName = camera.Name;
  42442. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42443. for (var passName in this._renderPasses) {
  42444. this._renderPasses[passName]._decRefCount();
  42445. }
  42446. }
  42447. };
  42448. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  42449. if (this._singleInstance) {
  42450. return this._postProcesses[0];
  42451. }
  42452. else {
  42453. return this._postProcesses[camera.name];
  42454. }
  42455. };
  42456. PostProcessRenderEffect.prototype._linkParameters = function () {
  42457. var _this = this;
  42458. for (var index in this._postProcesses) {
  42459. if (this.applyParameters) {
  42460. this.applyParameters(this._postProcesses[index]);
  42461. }
  42462. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  42463. _this._linkTextures(effect);
  42464. });
  42465. }
  42466. };
  42467. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  42468. for (var renderPassName in this._renderPasses) {
  42469. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  42470. }
  42471. for (var renderEffectName in this._renderEffectAsPasses) {
  42472. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  42473. }
  42474. };
  42475. return PostProcessRenderEffect;
  42476. }());
  42477. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  42478. })(BABYLON || (BABYLON = {}));
  42479. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  42480. var BABYLON;
  42481. (function (BABYLON) {
  42482. var PostProcessRenderPipeline = (function () {
  42483. function PostProcessRenderPipeline(engine, name) {
  42484. this._engine = engine;
  42485. this._name = name;
  42486. this._renderEffects = new Array();
  42487. this._renderEffectsForIsolatedPass = new Array();
  42488. this._cameras = [];
  42489. }
  42490. PostProcessRenderPipeline.prototype.getClassName = function () {
  42491. return "PostProcessRenderPipeline";
  42492. };
  42493. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  42494. get: function () {
  42495. for (var renderEffectName in this._renderEffects) {
  42496. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42497. if (!this._renderEffects[renderEffectName].isSupported) {
  42498. return false;
  42499. }
  42500. }
  42501. }
  42502. return true;
  42503. },
  42504. enumerable: true,
  42505. configurable: true
  42506. });
  42507. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  42508. this._renderEffects[renderEffect._name] = renderEffect;
  42509. };
  42510. // private
  42511. PostProcessRenderPipeline.prototype._rebuild = function () {
  42512. };
  42513. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  42514. var renderEffects = this._renderEffects[renderEffectName];
  42515. if (!renderEffects) {
  42516. return;
  42517. }
  42518. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42519. };
  42520. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  42521. var renderEffects = this._renderEffects[renderEffectName];
  42522. if (!renderEffects) {
  42523. return;
  42524. }
  42525. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42526. };
  42527. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  42528. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42529. var indicesToDelete = [];
  42530. var i;
  42531. for (i = 0; i < _cam.length; i++) {
  42532. var camera = _cam[i];
  42533. var cameraName = camera.name;
  42534. if (this._cameras.indexOf(camera) === -1) {
  42535. this._cameras[cameraName] = camera;
  42536. }
  42537. else if (unique) {
  42538. indicesToDelete.push(i);
  42539. }
  42540. }
  42541. for (i = 0; i < indicesToDelete.length; i++) {
  42542. cameras.splice(indicesToDelete[i], 1);
  42543. }
  42544. for (var renderEffectName in this._renderEffects) {
  42545. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42546. this._renderEffects[renderEffectName]._attachCameras(_cam);
  42547. }
  42548. }
  42549. };
  42550. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  42551. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42552. for (var renderEffectName in this._renderEffects) {
  42553. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42554. this._renderEffects[renderEffectName]._detachCameras(_cam);
  42555. }
  42556. }
  42557. for (var i = 0; i < _cam.length; i++) {
  42558. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  42559. }
  42560. };
  42561. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  42562. var _this = this;
  42563. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42564. var pass = null;
  42565. var renderEffectName;
  42566. for (renderEffectName in this._renderEffects) {
  42567. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42568. pass = this._renderEffects[renderEffectName].getPass(passName);
  42569. if (pass != null) {
  42570. break;
  42571. }
  42572. }
  42573. }
  42574. if (pass === null) {
  42575. return;
  42576. }
  42577. for (renderEffectName in this._renderEffects) {
  42578. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42579. this._renderEffects[renderEffectName]._disable(_cam);
  42580. }
  42581. }
  42582. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  42583. for (var i = 0; i < _cam.length; i++) {
  42584. var camera = _cam[i];
  42585. var cameraName = camera.name;
  42586. 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); });
  42587. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  42588. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  42589. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  42590. }
  42591. };
  42592. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  42593. var _this = this;
  42594. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42595. for (var i = 0; i < _cam.length; i++) {
  42596. var camera = _cam[i];
  42597. var cameraName = camera.name;
  42598. 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); });
  42599. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  42600. }
  42601. for (var renderEffectName in this._renderEffects) {
  42602. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42603. this._renderEffects[renderEffectName]._enable(_cam);
  42604. }
  42605. }
  42606. };
  42607. PostProcessRenderPipeline.prototype._update = function () {
  42608. for (var renderEffectName in this._renderEffects) {
  42609. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42610. this._renderEffects[renderEffectName]._update();
  42611. }
  42612. }
  42613. for (var i = 0; i < this._cameras.length; i++) {
  42614. var cameraName = this._cameras[i].name;
  42615. if (this._renderEffectsForIsolatedPass[cameraName]) {
  42616. this._renderEffectsForIsolatedPass[cameraName]._update();
  42617. }
  42618. }
  42619. };
  42620. PostProcessRenderPipeline.prototype._reset = function () {
  42621. this._renderEffects = new Array();
  42622. this._renderEffectsForIsolatedPass = new Array();
  42623. };
  42624. PostProcessRenderPipeline.prototype.dispose = function () {
  42625. // Must be implemented by children
  42626. };
  42627. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  42628. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  42629. __decorate([
  42630. BABYLON.serialize()
  42631. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  42632. return PostProcessRenderPipeline;
  42633. }());
  42634. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  42635. })(BABYLON || (BABYLON = {}));
  42636. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  42637. var BABYLON;
  42638. (function (BABYLON) {
  42639. var DefaultRenderingPipeline = (function (_super) {
  42640. __extends(DefaultRenderingPipeline, _super);
  42641. /**
  42642. * @constructor
  42643. * @param {string} name - The rendering pipeline name
  42644. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  42645. * @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)
  42646. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  42647. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  42648. */
  42649. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  42650. if (automaticBuild === void 0) { automaticBuild = true; }
  42651. var _this = _super.call(this, scene.getEngine(), name) || this;
  42652. _this.PassPostProcessId = "PassPostProcessEffect";
  42653. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  42654. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  42655. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  42656. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  42657. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  42658. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  42659. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  42660. // IAnimatable
  42661. _this.animations = [];
  42662. // Values
  42663. _this._bloomEnabled = false;
  42664. _this._fxaaEnabled = false;
  42665. _this._imageProcessingEnabled = true;
  42666. _this._bloomScale = 0.6;
  42667. _this._buildAllowed = true;
  42668. /**
  42669. * Specifies the size of the bloom blur kernel, relative to the final output size
  42670. */
  42671. _this.bloomKernel = 64;
  42672. /**
  42673. * Specifies the weight of the bloom in the final rendering
  42674. */
  42675. _this._bloomWeight = 0.15;
  42676. _this._cameras = cameras || [];
  42677. _this._buildAllowed = automaticBuild;
  42678. // Initialize
  42679. _this._scene = scene;
  42680. var caps = _this._scene.getEngine().getCaps();
  42681. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  42682. // Misc
  42683. if (_this._hdr) {
  42684. if (caps.textureHalfFloatRender) {
  42685. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  42686. }
  42687. else if (caps.textureFloatRender) {
  42688. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42689. }
  42690. }
  42691. else {
  42692. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42693. }
  42694. // Attach
  42695. scene.postProcessRenderPipelineManager.addPipeline(_this);
  42696. _this._buildPipeline();
  42697. return _this;
  42698. }
  42699. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  42700. get: function () {
  42701. return this._bloomWeight;
  42702. },
  42703. set: function (value) {
  42704. if (this._bloomWeight === value) {
  42705. return;
  42706. }
  42707. this._bloomWeight = value;
  42708. if (this._hdr && this.copyBack) {
  42709. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  42710. }
  42711. },
  42712. enumerable: true,
  42713. configurable: true
  42714. });
  42715. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  42716. get: function () {
  42717. return this._bloomScale;
  42718. },
  42719. set: function (value) {
  42720. if (this._bloomScale === value) {
  42721. return;
  42722. }
  42723. this._bloomScale = value;
  42724. this._buildPipeline();
  42725. },
  42726. enumerable: true,
  42727. configurable: true
  42728. });
  42729. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  42730. get: function () {
  42731. return this._bloomEnabled;
  42732. },
  42733. set: function (enabled) {
  42734. if (this._bloomEnabled === enabled) {
  42735. return;
  42736. }
  42737. this._bloomEnabled = enabled;
  42738. this._buildPipeline();
  42739. },
  42740. enumerable: true,
  42741. configurable: true
  42742. });
  42743. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  42744. get: function () {
  42745. return this._fxaaEnabled;
  42746. },
  42747. set: function (enabled) {
  42748. if (this._fxaaEnabled === enabled) {
  42749. return;
  42750. }
  42751. this._fxaaEnabled = enabled;
  42752. this._buildPipeline();
  42753. },
  42754. enumerable: true,
  42755. configurable: true
  42756. });
  42757. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  42758. get: function () {
  42759. return this._imageProcessingEnabled;
  42760. },
  42761. set: function (enabled) {
  42762. if (this._imageProcessingEnabled === enabled) {
  42763. return;
  42764. }
  42765. this._imageProcessingEnabled = enabled;
  42766. this._buildPipeline();
  42767. },
  42768. enumerable: true,
  42769. configurable: true
  42770. });
  42771. /**
  42772. * Force the compilation of the entire pipeline.
  42773. */
  42774. DefaultRenderingPipeline.prototype.prepare = function () {
  42775. var previousState = this._buildAllowed;
  42776. this._buildAllowed = true;
  42777. this._buildPipeline();
  42778. this._buildAllowed = previousState;
  42779. };
  42780. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  42781. var _this = this;
  42782. if (!this._buildAllowed) {
  42783. return;
  42784. }
  42785. var engine = this._scene.getEngine();
  42786. this._disposePostProcesses();
  42787. this._reset();
  42788. if (this.bloomEnabled) {
  42789. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42790. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  42791. if (!this._hdr) {
  42792. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42793. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  42794. this.highlights.autoClear = false;
  42795. this.highlights.alwaysForcePOT = true;
  42796. }
  42797. 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);
  42798. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  42799. this.blurX.alwaysForcePOT = true;
  42800. this.blurX.autoClear = false;
  42801. this.blurX.onActivateObservable.add(function () {
  42802. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  42803. _this.blurX.kernel = _this.bloomKernel * dw;
  42804. });
  42805. 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);
  42806. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  42807. this.blurY.alwaysForcePOT = true;
  42808. this.blurY.autoClear = false;
  42809. this.blurY.onActivateObservable.add(function () {
  42810. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  42811. _this.blurY.kernel = _this.bloomKernel * dh;
  42812. });
  42813. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42814. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  42815. this.copyBack.alwaysForcePOT = true;
  42816. if (this._hdr) {
  42817. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  42818. var w = this.bloomWeight;
  42819. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  42820. }
  42821. else {
  42822. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  42823. }
  42824. this.copyBack.autoClear = false;
  42825. }
  42826. if (this._imageProcessingEnabled) {
  42827. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42828. if (this._hdr) {
  42829. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  42830. }
  42831. }
  42832. if (this.fxaaEnabled) {
  42833. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42834. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  42835. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42836. }
  42837. else {
  42838. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42839. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  42840. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42841. }
  42842. if (this.bloomEnabled) {
  42843. if (this._hdr) {
  42844. this.copyBack.shareOutputWith(this.blurX);
  42845. if (this.imageProcessing) {
  42846. this.imageProcessing.shareOutputWith(this.pass);
  42847. this.imageProcessing.autoClear = false;
  42848. }
  42849. else if (this.fxaa) {
  42850. this.fxaa.shareOutputWith(this.pass);
  42851. }
  42852. else {
  42853. this.finalMerge.shareOutputWith(this.pass);
  42854. }
  42855. }
  42856. else {
  42857. if (this.fxaa) {
  42858. this.fxaa.shareOutputWith(this.pass);
  42859. }
  42860. else {
  42861. this.finalMerge.shareOutputWith(this.pass);
  42862. }
  42863. }
  42864. }
  42865. if (this._cameras !== null) {
  42866. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  42867. }
  42868. };
  42869. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  42870. for (var i = 0; i < this._cameras.length; i++) {
  42871. var camera = this._cameras[i];
  42872. if (this.pass) {
  42873. this.pass.dispose(camera);
  42874. }
  42875. if (this.highlights) {
  42876. this.highlights.dispose(camera);
  42877. }
  42878. if (this.blurX) {
  42879. this.blurX.dispose(camera);
  42880. }
  42881. if (this.blurY) {
  42882. this.blurY.dispose(camera);
  42883. }
  42884. if (this.copyBack) {
  42885. this.copyBack.dispose(camera);
  42886. }
  42887. if (this.imageProcessing) {
  42888. this.imageProcessing.dispose(camera);
  42889. }
  42890. if (this.fxaa) {
  42891. this.fxaa.dispose(camera);
  42892. }
  42893. if (this.finalMerge) {
  42894. this.finalMerge.dispose(camera);
  42895. }
  42896. }
  42897. this.pass = null;
  42898. this.highlights = null;
  42899. this.blurX = null;
  42900. this.blurY = null;
  42901. this.copyBack = null;
  42902. this.imageProcessing = null;
  42903. this.fxaa = null;
  42904. this.finalMerge = null;
  42905. };
  42906. // Dispose
  42907. DefaultRenderingPipeline.prototype.dispose = function () {
  42908. this._disposePostProcesses();
  42909. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  42910. _super.prototype.dispose.call(this);
  42911. };
  42912. // Serialize rendering pipeline
  42913. DefaultRenderingPipeline.prototype.serialize = function () {
  42914. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42915. serializationObject.customType = "DefaultRenderingPipeline";
  42916. return serializationObject;
  42917. };
  42918. // Parse serialized pipeline
  42919. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  42920. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  42921. };
  42922. __decorate([
  42923. BABYLON.serialize()
  42924. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  42925. __decorate([
  42926. BABYLON.serialize()
  42927. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  42928. __decorate([
  42929. BABYLON.serialize()
  42930. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  42931. __decorate([
  42932. BABYLON.serialize()
  42933. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  42934. __decorate([
  42935. BABYLON.serialize()
  42936. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  42937. __decorate([
  42938. BABYLON.serialize()
  42939. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  42940. __decorate([
  42941. BABYLON.serialize()
  42942. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  42943. __decorate([
  42944. BABYLON.serialize()
  42945. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  42946. return DefaultRenderingPipeline;
  42947. }(BABYLON.PostProcessRenderPipeline));
  42948. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  42949. })(BABYLON || (BABYLON = {}));
  42950. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  42951. var BABYLON;
  42952. (function (BABYLON) {
  42953. /**
  42954. * This groups together the common properties used for image processing either in direct forward pass
  42955. * or through post processing effect depending on the use of the image processing pipeline in your scene
  42956. * or not.
  42957. */
  42958. var ImageProcessingConfiguration = (function () {
  42959. function ImageProcessingConfiguration() {
  42960. /**
  42961. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  42962. */
  42963. this.colorCurves = new BABYLON.ColorCurves();
  42964. this._colorCurvesEnabled = false;
  42965. this._colorGradingEnabled = false;
  42966. this._colorGradingWithGreenDepth = false;
  42967. this._colorGradingBGR = false;
  42968. this._exposure = 1.0;
  42969. this._toneMappingEnabled = false;
  42970. this._contrast = 1.0;
  42971. /**
  42972. * Vignette stretch size.
  42973. */
  42974. this.vignetteStretch = 0;
  42975. /**
  42976. * Vignette centre X Offset.
  42977. */
  42978. this.vignetteCentreX = 0;
  42979. /**
  42980. * Vignette centre Y Offset.
  42981. */
  42982. this.vignetteCentreY = 0;
  42983. /**
  42984. * Vignette weight or intensity of the vignette effect.
  42985. */
  42986. this.vignetteWeight = 1.5;
  42987. /**
  42988. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  42989. * if vignetteEnabled is set to true.
  42990. */
  42991. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  42992. /**
  42993. * Camera field of view used by the Vignette effect.
  42994. */
  42995. this.vignetteCameraFov = 0.5;
  42996. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  42997. this._vignetteEnabled = false;
  42998. this._applyByPostProcess = false;
  42999. /**
  43000. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  43001. * @type {BABYLON.Observable}
  43002. */
  43003. this.onUpdateParameters = new BABYLON.Observable();
  43004. }
  43005. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  43006. /**
  43007. * Gets wether the color curves effect is enabled.
  43008. */
  43009. get: function () {
  43010. return this._colorCurvesEnabled;
  43011. },
  43012. /**
  43013. * Sets wether the color curves effect is enabled.
  43014. */
  43015. set: function (value) {
  43016. if (this._colorCurvesEnabled === value) {
  43017. return;
  43018. }
  43019. this._colorCurvesEnabled = value;
  43020. this._updateParameters();
  43021. },
  43022. enumerable: true,
  43023. configurable: true
  43024. });
  43025. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  43026. /**
  43027. * Gets wether the color grading effect is enabled.
  43028. */
  43029. get: function () {
  43030. return this._colorGradingEnabled;
  43031. },
  43032. /**
  43033. * Sets wether the color grading effect is enabled.
  43034. */
  43035. set: function (value) {
  43036. if (this._colorGradingEnabled === value) {
  43037. return;
  43038. }
  43039. this._colorGradingEnabled = value;
  43040. this._updateParameters();
  43041. },
  43042. enumerable: true,
  43043. configurable: true
  43044. });
  43045. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  43046. /**
  43047. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  43048. */
  43049. get: function () {
  43050. return this._colorGradingWithGreenDepth;
  43051. },
  43052. /**
  43053. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  43054. */
  43055. set: function (value) {
  43056. if (this._colorGradingWithGreenDepth === value) {
  43057. return;
  43058. }
  43059. this._colorGradingWithGreenDepth = value;
  43060. this._updateParameters();
  43061. },
  43062. enumerable: true,
  43063. configurable: true
  43064. });
  43065. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  43066. /**
  43067. * Gets wether the color grading texture contains BGR values.
  43068. */
  43069. get: function () {
  43070. return this._colorGradingBGR;
  43071. },
  43072. /**
  43073. * Sets wether the color grading texture contains BGR values.
  43074. */
  43075. set: function (value) {
  43076. if (this._colorGradingBGR === value) {
  43077. return;
  43078. }
  43079. this._colorGradingBGR = value;
  43080. this._updateParameters();
  43081. },
  43082. enumerable: true,
  43083. configurable: true
  43084. });
  43085. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  43086. /**
  43087. * Gets the Exposure used in the effect.
  43088. */
  43089. get: function () {
  43090. return this._exposure;
  43091. },
  43092. /**
  43093. * Sets the Exposure used in the effect.
  43094. */
  43095. set: function (value) {
  43096. if (this._exposure === value) {
  43097. return;
  43098. }
  43099. this._exposure = value;
  43100. this._updateParameters();
  43101. },
  43102. enumerable: true,
  43103. configurable: true
  43104. });
  43105. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  43106. /**
  43107. * Gets wether the tone mapping effect is enabled.
  43108. */
  43109. get: function () {
  43110. return this._toneMappingEnabled;
  43111. },
  43112. /**
  43113. * Sets wether the tone mapping effect is enabled.
  43114. */
  43115. set: function (value) {
  43116. if (this._toneMappingEnabled === value) {
  43117. return;
  43118. }
  43119. this._toneMappingEnabled = value;
  43120. this._updateParameters();
  43121. },
  43122. enumerable: true,
  43123. configurable: true
  43124. });
  43125. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  43126. /**
  43127. * Gets the contrast used in the effect.
  43128. */
  43129. get: function () {
  43130. return this._contrast;
  43131. },
  43132. /**
  43133. * Sets the contrast used in the effect.
  43134. */
  43135. set: function (value) {
  43136. if (this._contrast === value) {
  43137. return;
  43138. }
  43139. this._contrast = value;
  43140. this._updateParameters();
  43141. },
  43142. enumerable: true,
  43143. configurable: true
  43144. });
  43145. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  43146. /**
  43147. * Gets the vignette blend mode allowing different kind of effect.
  43148. */
  43149. get: function () {
  43150. return this._vignetteBlendMode;
  43151. },
  43152. /**
  43153. * Sets the vignette blend mode allowing different kind of effect.
  43154. */
  43155. set: function (value) {
  43156. if (this._vignetteBlendMode === value) {
  43157. return;
  43158. }
  43159. this._vignetteBlendMode = value;
  43160. this._updateParameters();
  43161. },
  43162. enumerable: true,
  43163. configurable: true
  43164. });
  43165. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  43166. /**
  43167. * Gets wether the vignette effect is enabled.
  43168. */
  43169. get: function () {
  43170. return this._vignetteEnabled;
  43171. },
  43172. /**
  43173. * Sets wether the vignette effect is enabled.
  43174. */
  43175. set: function (value) {
  43176. if (this._vignetteEnabled === value) {
  43177. return;
  43178. }
  43179. this._vignetteEnabled = value;
  43180. this._updateParameters();
  43181. },
  43182. enumerable: true,
  43183. configurable: true
  43184. });
  43185. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  43186. /**
  43187. * Gets wether the image processing is applied through a post process or not.
  43188. */
  43189. get: function () {
  43190. return this._applyByPostProcess;
  43191. },
  43192. /**
  43193. * Sets wether the image processing is applied through a post process or not.
  43194. */
  43195. set: function (value) {
  43196. if (this._applyByPostProcess === value) {
  43197. return;
  43198. }
  43199. this._applyByPostProcess = value;
  43200. this._updateParameters();
  43201. },
  43202. enumerable: true,
  43203. configurable: true
  43204. });
  43205. /**
  43206. * Method called each time the image processing information changes requires to recompile the effect.
  43207. */
  43208. ImageProcessingConfiguration.prototype._updateParameters = function () {
  43209. this.onUpdateParameters.notifyObservers(this);
  43210. };
  43211. ImageProcessingConfiguration.prototype.getClassName = function () {
  43212. return "ImageProcessingConfiguration";
  43213. };
  43214. /**
  43215. * Prepare the list of uniforms associated with the Image Processing effects.
  43216. * @param uniformsList The list of uniforms used in the effect
  43217. * @param defines the list of defines currently in use
  43218. */
  43219. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  43220. if (defines.EXPOSURE) {
  43221. uniforms.push("exposureLinear");
  43222. }
  43223. if (defines.CONTRAST) {
  43224. uniforms.push("contrast");
  43225. }
  43226. if (defines.COLORGRADING) {
  43227. uniforms.push("colorTransformSettings");
  43228. }
  43229. if (defines.VIGNETTE) {
  43230. uniforms.push("vInverseScreenSize");
  43231. uniforms.push("vignetteSettings1");
  43232. uniforms.push("vignetteSettings2");
  43233. }
  43234. if (defines.COLORCURVES) {
  43235. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  43236. }
  43237. };
  43238. /**
  43239. * Prepare the list of samplers associated with the Image Processing effects.
  43240. * @param uniformsList The list of uniforms used in the effect
  43241. * @param defines the list of defines currently in use
  43242. */
  43243. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  43244. if (defines.COLORGRADING) {
  43245. samplersList.push("txColorTransform");
  43246. }
  43247. };
  43248. /**
  43249. * Prepare the list of defines associated to the shader.
  43250. * @param defines the list of defines to complete
  43251. */
  43252. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  43253. defines.VIGNETTE = this.vignetteEnabled;
  43254. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  43255. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  43256. defines.TONEMAPPING = this.toneMappingEnabled;
  43257. defines.CONTRAST = (this.contrast !== 1.0);
  43258. defines.EXPOSURE = (this.exposure !== 1.0);
  43259. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  43260. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  43261. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  43262. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  43263. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  43264. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  43265. };
  43266. /**
  43267. * Returns true if all the image processing information are ready.
  43268. */
  43269. ImageProcessingConfiguration.prototype.isReady = function () {
  43270. // Color Grading texure can not be none blocking.
  43271. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  43272. };
  43273. /**
  43274. * Binds the image processing to the shader.
  43275. * @param effect The effect to bind to
  43276. */
  43277. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  43278. if (aspectRatio === void 0) { aspectRatio = 1; }
  43279. // Color Curves
  43280. if (this._colorCurvesEnabled) {
  43281. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  43282. }
  43283. // Vignette
  43284. if (this._vignetteEnabled) {
  43285. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  43286. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  43287. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  43288. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  43289. var vignetteScaleX = vignetteScaleY * aspectRatio;
  43290. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  43291. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  43292. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  43293. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  43294. var vignettePower = -2.0 * this.vignetteWeight;
  43295. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  43296. }
  43297. // Exposure
  43298. effect.setFloat("exposureLinear", this.exposure);
  43299. // Contrast
  43300. effect.setFloat("contrast", this.contrast);
  43301. // Color transform settings
  43302. if (this.colorGradingTexture) {
  43303. effect.setTexture("txColorTransform", this.colorGradingTexture);
  43304. var textureSize = this.colorGradingTexture.getSize().height;
  43305. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  43306. 0.5 / textureSize, // textureOffset
  43307. textureSize, // textureSize
  43308. this.colorGradingTexture.level // weight
  43309. );
  43310. }
  43311. };
  43312. /**
  43313. * Clones the current image processing instance.
  43314. * @return The cloned image processing
  43315. */
  43316. ImageProcessingConfiguration.prototype.clone = function () {
  43317. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  43318. };
  43319. /**
  43320. * Serializes the current image processing instance to a json representation.
  43321. * @return a JSON representation
  43322. */
  43323. ImageProcessingConfiguration.prototype.serialize = function () {
  43324. return BABYLON.SerializationHelper.Serialize(this);
  43325. };
  43326. /**
  43327. * Parses the image processing from a json representation.
  43328. * @param source the JSON source to parse
  43329. * @return The parsed image processing
  43330. */
  43331. ImageProcessingConfiguration.Parse = function (source) {
  43332. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  43333. };
  43334. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  43335. /**
  43336. * Used to apply the vignette as a mix with the pixel color.
  43337. */
  43338. get: function () {
  43339. return this._VIGNETTEMODE_MULTIPLY;
  43340. },
  43341. enumerable: true,
  43342. configurable: true
  43343. });
  43344. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  43345. /**
  43346. * Used to apply the vignette as a replacement of the pixel color.
  43347. */
  43348. get: function () {
  43349. return this._VIGNETTEMODE_OPAQUE;
  43350. },
  43351. enumerable: true,
  43352. configurable: true
  43353. });
  43354. // Static constants associated to the image processing.
  43355. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  43356. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  43357. __decorate([
  43358. BABYLON.serializeAsColorCurves()
  43359. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  43360. __decorate([
  43361. BABYLON.serialize()
  43362. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  43363. __decorate([
  43364. BABYLON.serializeAsTexture()
  43365. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  43366. __decorate([
  43367. BABYLON.serialize()
  43368. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  43369. __decorate([
  43370. BABYLON.serialize()
  43371. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  43372. __decorate([
  43373. BABYLON.serialize()
  43374. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  43375. __decorate([
  43376. BABYLON.serialize()
  43377. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  43378. __decorate([
  43379. BABYLON.serialize()
  43380. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  43381. __decorate([
  43382. BABYLON.serialize()
  43383. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  43384. __decorate([
  43385. BABYLON.serialize()
  43386. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  43387. __decorate([
  43388. BABYLON.serialize()
  43389. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  43390. __decorate([
  43391. BABYLON.serialize()
  43392. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  43393. __decorate([
  43394. BABYLON.serialize()
  43395. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  43396. __decorate([
  43397. BABYLON.serializeAsColor4()
  43398. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  43399. __decorate([
  43400. BABYLON.serialize()
  43401. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  43402. __decorate([
  43403. BABYLON.serialize()
  43404. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  43405. __decorate([
  43406. BABYLON.serialize()
  43407. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  43408. __decorate([
  43409. BABYLON.serialize()
  43410. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  43411. return ImageProcessingConfiguration;
  43412. }());
  43413. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  43414. })(BABYLON || (BABYLON = {}));
  43415. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  43416. /// <reference path="babylon.mesh.ts" />
  43417. var BABYLON;
  43418. (function (BABYLON) {
  43419. var GroundMesh = (function (_super) {
  43420. __extends(GroundMesh, _super);
  43421. function GroundMesh(name, scene) {
  43422. var _this = _super.call(this, name, scene) || this;
  43423. _this.generateOctree = false;
  43424. _this._worldInverse = new BABYLON.Matrix();
  43425. return _this;
  43426. }
  43427. GroundMesh.prototype.getClassName = function () {
  43428. return "GroundMesh";
  43429. };
  43430. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  43431. get: function () {
  43432. return Math.min(this._subdivisionsX, this._subdivisionsY);
  43433. },
  43434. enumerable: true,
  43435. configurable: true
  43436. });
  43437. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  43438. get: function () {
  43439. return this._subdivisionsX;
  43440. },
  43441. enumerable: true,
  43442. configurable: true
  43443. });
  43444. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  43445. get: function () {
  43446. return this._subdivisionsY;
  43447. },
  43448. enumerable: true,
  43449. configurable: true
  43450. });
  43451. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  43452. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  43453. this._subdivisionsX = chunksCount;
  43454. this._subdivisionsY = chunksCount;
  43455. this.subdivide(chunksCount);
  43456. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  43457. };
  43458. /**
  43459. * Returns a height (y) value in the Worl system :
  43460. * the ground altitude at the coordinates (x, z) expressed in the World system.
  43461. * Returns the ground y position if (x, z) are outside the ground surface.
  43462. */
  43463. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  43464. var world = this.getWorldMatrix();
  43465. var invMat = BABYLON.Tmp.Matrix[5];
  43466. world.invertToRef(invMat);
  43467. var tmpVect = BABYLON.Tmp.Vector3[8];
  43468. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  43469. x = tmpVect.x;
  43470. z = tmpVect.z;
  43471. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43472. return this.position.y;
  43473. }
  43474. if (!this._heightQuads || this._heightQuads.length == 0) {
  43475. this._initHeightQuads();
  43476. this._computeHeightQuads();
  43477. }
  43478. var facet = this._getFacetAt(x, z);
  43479. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  43480. // return y in the World system
  43481. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  43482. return tmpVect.y;
  43483. };
  43484. /**
  43485. * Returns a normalized vector (Vector3) orthogonal to the ground
  43486. * at the ground coordinates (x, z) expressed in the World system.
  43487. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  43488. */
  43489. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  43490. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  43491. this.getNormalAtCoordinatesToRef(x, z, normal);
  43492. return normal;
  43493. };
  43494. /**
  43495. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  43496. * at the ground coordinates (x, z) expressed in the World system.
  43497. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  43498. * Returns the GroundMesh.
  43499. */
  43500. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  43501. var world = this.getWorldMatrix();
  43502. var tmpMat = BABYLON.Tmp.Matrix[5];
  43503. world.invertToRef(tmpMat);
  43504. var tmpVect = BABYLON.Tmp.Vector3[8];
  43505. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  43506. x = tmpVect.x;
  43507. z = tmpVect.z;
  43508. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43509. return this;
  43510. }
  43511. if (!this._heightQuads || this._heightQuads.length == 0) {
  43512. this._initHeightQuads();
  43513. this._computeHeightQuads();
  43514. }
  43515. var facet = this._getFacetAt(x, z);
  43516. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  43517. return this;
  43518. };
  43519. /**
  43520. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  43521. * if the ground has been updated.
  43522. * This can be used in the render loop.
  43523. * Returns the GroundMesh.
  43524. */
  43525. GroundMesh.prototype.updateCoordinateHeights = function () {
  43526. if (!this._heightQuads || this._heightQuads.length == 0) {
  43527. this._initHeightQuads();
  43528. }
  43529. this._computeHeightQuads();
  43530. return this;
  43531. };
  43532. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  43533. GroundMesh.prototype._getFacetAt = function (x, z) {
  43534. // retrieve col and row from x, z coordinates in the ground local system
  43535. var subdivisionsX = this._subdivisionsX;
  43536. var subdivisionsY = this._subdivisionsY;
  43537. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  43538. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  43539. var quad = this._heightQuads[row * this._subdivisionsX + col];
  43540. var facet;
  43541. if (z < quad.slope.x * x + quad.slope.y) {
  43542. facet = quad.facet1;
  43543. }
  43544. else {
  43545. facet = quad.facet2;
  43546. }
  43547. return facet;
  43548. };
  43549. // Creates and populates the heightMap array with "facet" elements :
  43550. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  43551. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43552. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43553. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43554. // Returns the GroundMesh.
  43555. GroundMesh.prototype._initHeightQuads = function () {
  43556. var subdivisionsX = this._subdivisionsX;
  43557. var subdivisionsY = this._subdivisionsY;
  43558. this._heightQuads = new Array();
  43559. for (var row = 0; row < subdivisionsY; row++) {
  43560. for (var col = 0; col < subdivisionsX; col++) {
  43561. 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) };
  43562. this._heightQuads[row * subdivisionsX + col] = quad;
  43563. }
  43564. }
  43565. return this;
  43566. };
  43567. // Compute each quad element values and update the the heightMap array :
  43568. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43569. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43570. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43571. // Returns the GroundMesh.
  43572. GroundMesh.prototype._computeHeightQuads = function () {
  43573. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43574. var v1 = BABYLON.Tmp.Vector3[3];
  43575. var v2 = BABYLON.Tmp.Vector3[2];
  43576. var v3 = BABYLON.Tmp.Vector3[1];
  43577. var v4 = BABYLON.Tmp.Vector3[0];
  43578. var v1v2 = BABYLON.Tmp.Vector3[4];
  43579. var v1v3 = BABYLON.Tmp.Vector3[5];
  43580. var v1v4 = BABYLON.Tmp.Vector3[6];
  43581. var norm1 = BABYLON.Tmp.Vector3[7];
  43582. var norm2 = BABYLON.Tmp.Vector3[8];
  43583. var i = 0;
  43584. var j = 0;
  43585. var k = 0;
  43586. var cd = 0; // 2D slope coefficient : z = cd * x + h
  43587. var h = 0;
  43588. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  43589. var d2 = 0;
  43590. var subdivisionsX = this._subdivisionsX;
  43591. var subdivisionsY = this._subdivisionsY;
  43592. for (var row = 0; row < subdivisionsY; row++) {
  43593. for (var col = 0; col < subdivisionsX; col++) {
  43594. i = col * 3;
  43595. j = row * (subdivisionsX + 1) * 3;
  43596. k = (row + 1) * (subdivisionsX + 1) * 3;
  43597. v1.x = positions[j + i];
  43598. v1.y = positions[j + i + 1];
  43599. v1.z = positions[j + i + 2];
  43600. v2.x = positions[j + i + 3];
  43601. v2.y = positions[j + i + 4];
  43602. v2.z = positions[j + i + 5];
  43603. v3.x = positions[k + i];
  43604. v3.y = positions[k + i + 1];
  43605. v3.z = positions[k + i + 2];
  43606. v4.x = positions[k + i + 3];
  43607. v4.y = positions[k + i + 4];
  43608. v4.z = positions[k + i + 5];
  43609. // 2D slope V1V4
  43610. cd = (v4.z - v1.z) / (v4.x - v1.x);
  43611. h = v1.z - cd * v1.x; // v1 belongs to the slope
  43612. // facet equations :
  43613. // we compute each facet normal vector
  43614. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  43615. // we compute the value d by applying the equation to v1 which belongs to the plane
  43616. // then we store the facet equation in a Vector4
  43617. v2.subtractToRef(v1, v1v2);
  43618. v3.subtractToRef(v1, v1v3);
  43619. v4.subtractToRef(v1, v1v4);
  43620. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  43621. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  43622. norm1.normalize();
  43623. norm2.normalize();
  43624. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  43625. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  43626. var quad = this._heightQuads[row * subdivisionsX + col];
  43627. quad.slope.copyFromFloats(cd, h);
  43628. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  43629. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  43630. }
  43631. }
  43632. return this;
  43633. };
  43634. GroundMesh.prototype.serialize = function (serializationObject) {
  43635. _super.prototype.serialize.call(this, serializationObject);
  43636. serializationObject.subdivisionsX = this._subdivisionsX;
  43637. serializationObject.subdivisionsY = this._subdivisionsY;
  43638. serializationObject.minX = this._minX;
  43639. serializationObject.maxX = this._maxX;
  43640. serializationObject.minZ = this._minZ;
  43641. serializationObject.maxZ = this._maxZ;
  43642. serializationObject.width = this._width;
  43643. serializationObject.height = this._height;
  43644. };
  43645. GroundMesh.Parse = function (parsedMesh, scene) {
  43646. var result = new GroundMesh(parsedMesh.name, scene);
  43647. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  43648. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  43649. result._minX = parsedMesh.minX;
  43650. result._maxX = parsedMesh.maxX;
  43651. result._minZ = parsedMesh.minZ;
  43652. result._maxZ = parsedMesh.maxZ;
  43653. result._width = parsedMesh.width;
  43654. result._height = parsedMesh.height;
  43655. return result;
  43656. };
  43657. return GroundMesh;
  43658. }(BABYLON.Mesh));
  43659. BABYLON.GroundMesh = GroundMesh;
  43660. })(BABYLON || (BABYLON = {}));
  43661. //# sourceMappingURL=babylon.groundMesh.js.map
  43662. var BABYLON;
  43663. (function (BABYLON) {
  43664. /**
  43665. * Creates an instance based on a source mesh.
  43666. */
  43667. var InstancedMesh = (function (_super) {
  43668. __extends(InstancedMesh, _super);
  43669. function InstancedMesh(name, source) {
  43670. var _this = _super.call(this, name, source.getScene()) || this;
  43671. source.instances.push(_this);
  43672. _this._sourceMesh = source;
  43673. _this.position.copyFrom(source.position);
  43674. _this.rotation.copyFrom(source.rotation);
  43675. _this.scaling.copyFrom(source.scaling);
  43676. if (source.rotationQuaternion) {
  43677. _this.rotationQuaternion = source.rotationQuaternion.clone();
  43678. }
  43679. _this.infiniteDistance = source.infiniteDistance;
  43680. _this.setPivotMatrix(source.getPivotMatrix());
  43681. _this.refreshBoundingInfo();
  43682. _this._syncSubMeshes();
  43683. return _this;
  43684. }
  43685. /**
  43686. * Returns the string "InstancedMesh".
  43687. */
  43688. InstancedMesh.prototype.getClassName = function () {
  43689. return "InstancedMesh";
  43690. };
  43691. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  43692. // Methods
  43693. get: function () {
  43694. return this._sourceMesh.receiveShadows;
  43695. },
  43696. enumerable: true,
  43697. configurable: true
  43698. });
  43699. Object.defineProperty(InstancedMesh.prototype, "material", {
  43700. get: function () {
  43701. return this._sourceMesh.material;
  43702. },
  43703. enumerable: true,
  43704. configurable: true
  43705. });
  43706. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  43707. get: function () {
  43708. return this._sourceMesh.visibility;
  43709. },
  43710. enumerable: true,
  43711. configurable: true
  43712. });
  43713. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  43714. get: function () {
  43715. return this._sourceMesh.skeleton;
  43716. },
  43717. enumerable: true,
  43718. configurable: true
  43719. });
  43720. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  43721. get: function () {
  43722. return this._sourceMesh.renderingGroupId;
  43723. },
  43724. enumerable: true,
  43725. configurable: true
  43726. });
  43727. /**
  43728. * Returns the total number of vertices (integer).
  43729. */
  43730. InstancedMesh.prototype.getTotalVertices = function () {
  43731. return this._sourceMesh.getTotalVertices();
  43732. };
  43733. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  43734. get: function () {
  43735. return this._sourceMesh;
  43736. },
  43737. enumerable: true,
  43738. configurable: true
  43739. });
  43740. /**
  43741. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  43742. */
  43743. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  43744. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  43745. };
  43746. /**
  43747. * Sets the vertex data of the mesh geometry for the requested `kind`.
  43748. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  43749. * The `data` are either a numeric array either a Float32Array.
  43750. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  43751. * 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).
  43752. * Note that a new underlying VertexBuffer object is created each call.
  43753. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  43754. *
  43755. * Possible `kind` values :
  43756. * - BABYLON.VertexBuffer.PositionKind
  43757. * - BABYLON.VertexBuffer.UVKind
  43758. * - BABYLON.VertexBuffer.UV2Kind
  43759. * - BABYLON.VertexBuffer.UV3Kind
  43760. * - BABYLON.VertexBuffer.UV4Kind
  43761. * - BABYLON.VertexBuffer.UV5Kind
  43762. * - BABYLON.VertexBuffer.UV6Kind
  43763. * - BABYLON.VertexBuffer.ColorKind
  43764. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43765. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43766. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43767. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43768. *
  43769. * Returns the Mesh.
  43770. */
  43771. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  43772. if (this.sourceMesh) {
  43773. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  43774. }
  43775. return this.sourceMesh;
  43776. };
  43777. /**
  43778. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  43779. * If the mesh has no geometry, it is simply returned as it is.
  43780. * The `data` are either a numeric array either a Float32Array.
  43781. * No new underlying VertexBuffer object is created.
  43782. * 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.
  43783. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  43784. *
  43785. * Possible `kind` values :
  43786. * - BABYLON.VertexBuffer.PositionKind
  43787. * - BABYLON.VertexBuffer.UVKind
  43788. * - BABYLON.VertexBuffer.UV2Kind
  43789. * - BABYLON.VertexBuffer.UV3Kind
  43790. * - BABYLON.VertexBuffer.UV4Kind
  43791. * - BABYLON.VertexBuffer.UV5Kind
  43792. * - BABYLON.VertexBuffer.UV6Kind
  43793. * - BABYLON.VertexBuffer.ColorKind
  43794. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43795. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43796. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43797. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43798. *
  43799. * Returns the Mesh.
  43800. */
  43801. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  43802. if (this.sourceMesh) {
  43803. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  43804. }
  43805. return this.sourceMesh;
  43806. };
  43807. /**
  43808. * Sets the mesh indices.
  43809. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  43810. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  43811. * This method creates a new index buffer each call.
  43812. * Returns the Mesh.
  43813. */
  43814. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  43815. if (this.sourceMesh) {
  43816. this.sourceMesh.setIndices(indices, totalVertices);
  43817. }
  43818. return this.sourceMesh;
  43819. };
  43820. /**
  43821. * Boolean : True if the mesh owns the requested kind of data.
  43822. */
  43823. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  43824. return this._sourceMesh.isVerticesDataPresent(kind);
  43825. };
  43826. /**
  43827. * Returns an array of indices (IndicesArray).
  43828. */
  43829. InstancedMesh.prototype.getIndices = function () {
  43830. return this._sourceMesh.getIndices();
  43831. };
  43832. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  43833. get: function () {
  43834. return this._sourceMesh._positions;
  43835. },
  43836. enumerable: true,
  43837. configurable: true
  43838. });
  43839. /**
  43840. * Sets a new updated BoundingInfo to the mesh.
  43841. * Returns the mesh.
  43842. */
  43843. InstancedMesh.prototype.refreshBoundingInfo = function () {
  43844. var meshBB = this._sourceMesh.getBoundingInfo();
  43845. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  43846. this._updateBoundingInfo();
  43847. return this;
  43848. };
  43849. InstancedMesh.prototype._preActivate = function () {
  43850. if (this._currentLOD) {
  43851. this._currentLOD._preActivate();
  43852. }
  43853. return this;
  43854. };
  43855. InstancedMesh.prototype._activate = function (renderId) {
  43856. if (this._currentLOD) {
  43857. this._currentLOD._registerInstanceForRenderId(this, renderId);
  43858. }
  43859. return this;
  43860. };
  43861. /**
  43862. * Returns the current associated LOD AbstractMesh.
  43863. */
  43864. InstancedMesh.prototype.getLOD = function (camera) {
  43865. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  43866. if (this._currentLOD === this.sourceMesh) {
  43867. return this;
  43868. }
  43869. return this._currentLOD;
  43870. };
  43871. InstancedMesh.prototype._syncSubMeshes = function () {
  43872. this.releaseSubMeshes();
  43873. if (this._sourceMesh.subMeshes) {
  43874. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  43875. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  43876. }
  43877. }
  43878. return this;
  43879. };
  43880. InstancedMesh.prototype._generatePointsArray = function () {
  43881. return this._sourceMesh._generatePointsArray();
  43882. };
  43883. /**
  43884. * Creates a new InstancedMesh from the current mesh.
  43885. * - name (string) : the cloned mesh name
  43886. * - newParent (optional Node) : the optional Node to parent the clone to.
  43887. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  43888. *
  43889. * Returns the clone.
  43890. */
  43891. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43892. var result = this._sourceMesh.createInstance(name);
  43893. // Deep copy
  43894. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  43895. // Bounding info
  43896. this.refreshBoundingInfo();
  43897. // Parent
  43898. if (newParent) {
  43899. result.parent = newParent;
  43900. }
  43901. if (!doNotCloneChildren) {
  43902. // Children
  43903. for (var index = 0; index < this.getScene().meshes.length; index++) {
  43904. var mesh = this.getScene().meshes[index];
  43905. if (mesh.parent === this) {
  43906. mesh.clone(mesh.name, result);
  43907. }
  43908. }
  43909. }
  43910. result.computeWorldMatrix(true);
  43911. return result;
  43912. };
  43913. /**
  43914. * Disposes the InstancedMesh.
  43915. * Returns nothing.
  43916. */
  43917. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  43918. // Remove from mesh
  43919. var index = this._sourceMesh.instances.indexOf(this);
  43920. this._sourceMesh.instances.splice(index, 1);
  43921. _super.prototype.dispose.call(this, doNotRecurse);
  43922. };
  43923. return InstancedMesh;
  43924. }(BABYLON.AbstractMesh));
  43925. BABYLON.InstancedMesh = InstancedMesh;
  43926. })(BABYLON || (BABYLON = {}));
  43927. //# sourceMappingURL=babylon.instancedMesh.js.map
  43928. /// <reference path="babylon.mesh.ts" />
  43929. var BABYLON;
  43930. (function (BABYLON) {
  43931. var LinesMesh = (function (_super) {
  43932. __extends(LinesMesh, _super);
  43933. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  43934. if (parent === void 0) { parent = null; }
  43935. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  43936. _this.useVertexColor = useVertexColor;
  43937. _this.color = new BABYLON.Color3(1, 1, 1);
  43938. _this.alpha = 1;
  43939. if (source) {
  43940. _this.color = source.color.clone();
  43941. _this.alpha = source.alpha;
  43942. _this.useVertexColor = source.useVertexColor;
  43943. }
  43944. _this._intersectionThreshold = 0.1;
  43945. var options = {
  43946. attributes: [BABYLON.VertexBuffer.PositionKind],
  43947. uniforms: ["world", "viewProjection"],
  43948. needAlphaBlending: false,
  43949. };
  43950. if (!useVertexColor) {
  43951. options.uniforms.push("color");
  43952. options.needAlphaBlending = true;
  43953. }
  43954. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  43955. return _this;
  43956. }
  43957. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  43958. /**
  43959. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43960. * This margin is expressed in world space coordinates, so its value may vary.
  43961. * Default value is 0.1
  43962. * @returns the intersection Threshold value.
  43963. */
  43964. get: function () {
  43965. return this._intersectionThreshold;
  43966. },
  43967. /**
  43968. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43969. * This margin is expressed in world space coordinates, so its value may vary.
  43970. * @param value the new threshold to apply
  43971. */
  43972. set: function (value) {
  43973. if (this._intersectionThreshold === value) {
  43974. return;
  43975. }
  43976. this._intersectionThreshold = value;
  43977. if (this.geometry) {
  43978. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  43979. }
  43980. },
  43981. enumerable: true,
  43982. configurable: true
  43983. });
  43984. /**
  43985. * Returns the string "LineMesh"
  43986. */
  43987. LinesMesh.prototype.getClassName = function () {
  43988. return "LinesMesh";
  43989. };
  43990. Object.defineProperty(LinesMesh.prototype, "material", {
  43991. get: function () {
  43992. return this._colorShader;
  43993. },
  43994. enumerable: true,
  43995. configurable: true
  43996. });
  43997. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  43998. get: function () {
  43999. return false;
  44000. },
  44001. enumerable: true,
  44002. configurable: true
  44003. });
  44004. LinesMesh.prototype.createInstance = function (name) {
  44005. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  44006. return null;
  44007. };
  44008. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  44009. // VBOs
  44010. this._geometry._bind(this._colorShader.getEffect());
  44011. // Color
  44012. if (!this.useVertexColor) {
  44013. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  44014. }
  44015. return this;
  44016. };
  44017. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  44018. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  44019. return this;
  44020. }
  44021. var engine = this.getScene().getEngine();
  44022. // Draw order
  44023. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  44024. return this;
  44025. };
  44026. LinesMesh.prototype.dispose = function (doNotRecurse) {
  44027. this._colorShader.dispose();
  44028. _super.prototype.dispose.call(this, doNotRecurse);
  44029. };
  44030. /**
  44031. * Returns a new LineMesh object cloned from the current one.
  44032. */
  44033. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  44034. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  44035. };
  44036. return LinesMesh;
  44037. }(BABYLON.Mesh));
  44038. BABYLON.LinesMesh = LinesMesh;
  44039. })(BABYLON || (BABYLON = {}));
  44040. //# sourceMappingURL=babylon.linesMesh.js.map
  44041. var BABYLON;
  44042. (function (BABYLON) {
  44043. var StandardMaterialDefines = (function (_super) {
  44044. __extends(StandardMaterialDefines, _super);
  44045. function StandardMaterialDefines() {
  44046. var _this = _super.call(this) || this;
  44047. _this.MAINUV1 = false;
  44048. _this.MAINUV2 = false;
  44049. _this.DIFFUSE = false;
  44050. _this.DIFFUSEDIRECTUV = 0;
  44051. _this.AMBIENT = false;
  44052. _this.AMBIENTDIRECTUV = 0;
  44053. _this.OPACITY = false;
  44054. _this.OPACITYDIRECTUV = 0;
  44055. _this.OPACITYRGB = false;
  44056. _this.REFLECTION = false;
  44057. _this.EMISSIVE = false;
  44058. _this.EMISSIVEDIRECTUV = 0;
  44059. _this.SPECULAR = false;
  44060. _this.SPECULARDIRECTUV = 0;
  44061. _this.BUMP = false;
  44062. _this.BUMPDIRECTUV = 0;
  44063. _this.PARALLAX = false;
  44064. _this.PARALLAXOCCLUSION = false;
  44065. _this.SPECULAROVERALPHA = false;
  44066. _this.CLIPPLANE = false;
  44067. _this.ALPHATEST = false;
  44068. _this.ALPHAFROMDIFFUSE = false;
  44069. _this.POINTSIZE = false;
  44070. _this.FOG = false;
  44071. _this.SPECULARTERM = false;
  44072. _this.DIFFUSEFRESNEL = false;
  44073. _this.OPACITYFRESNEL = false;
  44074. _this.REFLECTIONFRESNEL = false;
  44075. _this.REFRACTIONFRESNEL = false;
  44076. _this.EMISSIVEFRESNEL = false;
  44077. _this.FRESNEL = false;
  44078. _this.NORMAL = false;
  44079. _this.UV1 = false;
  44080. _this.UV2 = false;
  44081. _this.VERTEXCOLOR = false;
  44082. _this.VERTEXALPHA = false;
  44083. _this.NUM_BONE_INFLUENCERS = 0;
  44084. _this.BonesPerMesh = 0;
  44085. _this.INSTANCES = false;
  44086. _this.GLOSSINESS = false;
  44087. _this.ROUGHNESS = false;
  44088. _this.EMISSIVEASILLUMINATION = false;
  44089. _this.LINKEMISSIVEWITHDIFFUSE = false;
  44090. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  44091. _this.LIGHTMAP = false;
  44092. _this.LIGHTMAPDIRECTUV = 0;
  44093. _this.USELIGHTMAPASSHADOWMAP = false;
  44094. _this.REFLECTIONMAP_3D = false;
  44095. _this.REFLECTIONMAP_SPHERICAL = false;
  44096. _this.REFLECTIONMAP_PLANAR = false;
  44097. _this.REFLECTIONMAP_CUBIC = false;
  44098. _this.REFLECTIONMAP_PROJECTION = false;
  44099. _this.REFLECTIONMAP_SKYBOX = false;
  44100. _this.REFLECTIONMAP_EXPLICIT = false;
  44101. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44102. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44103. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44104. _this.INVERTCUBICMAP = false;
  44105. _this.LOGARITHMICDEPTH = false;
  44106. _this.REFRACTION = false;
  44107. _this.REFRACTIONMAP_3D = false;
  44108. _this.REFLECTIONOVERALPHA = false;
  44109. _this.TWOSIDEDLIGHTING = false;
  44110. _this.SHADOWFLOAT = false;
  44111. _this.MORPHTARGETS = false;
  44112. _this.MORPHTARGETS_NORMAL = false;
  44113. _this.MORPHTARGETS_TANGENT = false;
  44114. _this.NUM_MORPH_INFLUENCERS = 0;
  44115. _this.USERIGHTHANDEDSYSTEM = false;
  44116. _this.IMAGEPROCESSING = false;
  44117. _this.VIGNETTE = false;
  44118. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44119. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44120. _this.TONEMAPPING = false;
  44121. _this.CONTRAST = false;
  44122. _this.COLORCURVES = false;
  44123. _this.COLORGRADING = false;
  44124. _this.SAMPLER3DGREENDEPTH = false;
  44125. _this.SAMPLER3DBGRMAP = false;
  44126. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44127. _this.EXPOSURE = false;
  44128. _this.rebuild();
  44129. return _this;
  44130. }
  44131. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  44132. var modes = [
  44133. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  44134. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  44135. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  44136. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  44137. ];
  44138. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  44139. var mode = modes_1[_i];
  44140. this[mode] = (mode === modeToEnable);
  44141. }
  44142. };
  44143. return StandardMaterialDefines;
  44144. }(BABYLON.MaterialDefines));
  44145. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  44146. var StandardMaterial = (function (_super) {
  44147. __extends(StandardMaterial, _super);
  44148. function StandardMaterial(name, scene) {
  44149. var _this = _super.call(this, name, scene) || this;
  44150. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44151. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  44152. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  44153. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44154. _this.specularPower = 64;
  44155. _this._useAlphaFromDiffuseTexture = false;
  44156. _this._useEmissiveAsIllumination = false;
  44157. _this._linkEmissiveWithDiffuse = false;
  44158. _this._useSpecularOverAlpha = false;
  44159. _this._useReflectionOverAlpha = false;
  44160. _this._disableLighting = false;
  44161. _this._useParallax = false;
  44162. _this._useParallaxOcclusion = false;
  44163. _this.parallaxScaleBias = 0.05;
  44164. _this._roughness = 0;
  44165. _this.indexOfRefraction = 0.98;
  44166. _this.invertRefractionY = true;
  44167. _this._useLightmapAsShadowmap = false;
  44168. _this._useReflectionFresnelFromSpecular = false;
  44169. _this._useGlossinessFromSpecularMapAlpha = false;
  44170. _this._maxSimultaneousLights = 4;
  44171. /**
  44172. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44173. */
  44174. _this._invertNormalMapX = false;
  44175. /**
  44176. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44177. */
  44178. _this._invertNormalMapY = false;
  44179. /**
  44180. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44181. */
  44182. _this._twoSidedLighting = false;
  44183. _this._renderTargets = new BABYLON.SmartArray(16);
  44184. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  44185. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44186. // Setup the default processing configuration to the scene.
  44187. _this._attachImageProcessingConfiguration(null);
  44188. _this.getRenderTargetTextures = function () {
  44189. _this._renderTargets.reset();
  44190. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44191. _this._renderTargets.push(_this._reflectionTexture);
  44192. }
  44193. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44194. _this._renderTargets.push(_this._refractionTexture);
  44195. }
  44196. return _this._renderTargets;
  44197. };
  44198. return _this;
  44199. }
  44200. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  44201. /**
  44202. * Gets the image processing configuration used either in this material.
  44203. */
  44204. get: function () {
  44205. return this._imageProcessingConfiguration;
  44206. },
  44207. /**
  44208. * Sets the Default image processing configuration used either in the this material.
  44209. *
  44210. * If sets to null, the scene one is in use.
  44211. */
  44212. set: function (value) {
  44213. this._attachImageProcessingConfiguration(value);
  44214. // Ensure the effect will be rebuilt.
  44215. this._markAllSubMeshesAsTexturesDirty();
  44216. },
  44217. enumerable: true,
  44218. configurable: true
  44219. });
  44220. /**
  44221. * Attaches a new image processing configuration to the Standard Material.
  44222. * @param configuration
  44223. */
  44224. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44225. var _this = this;
  44226. if (configuration === this._imageProcessingConfiguration) {
  44227. return;
  44228. }
  44229. // Detaches observer.
  44230. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44231. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44232. }
  44233. // Pick the scene configuration if needed.
  44234. if (!configuration) {
  44235. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44236. }
  44237. else {
  44238. this._imageProcessingConfiguration = configuration;
  44239. }
  44240. // Attaches observer.
  44241. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44242. _this._markAllSubMeshesAsImageProcessingDirty();
  44243. });
  44244. };
  44245. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  44246. /**
  44247. * Gets wether the color curves effect is enabled.
  44248. */
  44249. get: function () {
  44250. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44251. },
  44252. /**
  44253. * Sets wether the color curves effect is enabled.
  44254. */
  44255. set: function (value) {
  44256. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44257. },
  44258. enumerable: true,
  44259. configurable: true
  44260. });
  44261. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  44262. /**
  44263. * Gets wether the color grading effect is enabled.
  44264. */
  44265. get: function () {
  44266. return this.imageProcessingConfiguration.colorGradingEnabled;
  44267. },
  44268. /**
  44269. * Gets wether the color grading effect is enabled.
  44270. */
  44271. set: function (value) {
  44272. this.imageProcessingConfiguration.colorGradingEnabled = value;
  44273. },
  44274. enumerable: true,
  44275. configurable: true
  44276. });
  44277. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  44278. /**
  44279. * Gets wether tonemapping is enabled or not.
  44280. */
  44281. get: function () {
  44282. return this._imageProcessingConfiguration.toneMappingEnabled;
  44283. },
  44284. /**
  44285. * Sets wether tonemapping is enabled or not
  44286. */
  44287. set: function (value) {
  44288. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44289. },
  44290. enumerable: true,
  44291. configurable: true
  44292. });
  44293. ;
  44294. ;
  44295. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  44296. /**
  44297. * The camera exposure used on this material.
  44298. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44299. * This corresponds to a photographic exposure.
  44300. */
  44301. get: function () {
  44302. return this._imageProcessingConfiguration.exposure;
  44303. },
  44304. /**
  44305. * The camera exposure used on this material.
  44306. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44307. * This corresponds to a photographic exposure.
  44308. */
  44309. set: function (value) {
  44310. this._imageProcessingConfiguration.exposure = value;
  44311. },
  44312. enumerable: true,
  44313. configurable: true
  44314. });
  44315. ;
  44316. ;
  44317. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  44318. /**
  44319. * Gets The camera contrast used on this material.
  44320. */
  44321. get: function () {
  44322. return this._imageProcessingConfiguration.contrast;
  44323. },
  44324. /**
  44325. * Sets The camera contrast used on this material.
  44326. */
  44327. set: function (value) {
  44328. this._imageProcessingConfiguration.contrast = value;
  44329. },
  44330. enumerable: true,
  44331. configurable: true
  44332. });
  44333. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  44334. /**
  44335. * Gets the Color Grading 2D Lookup Texture.
  44336. */
  44337. get: function () {
  44338. return this._imageProcessingConfiguration.colorGradingTexture;
  44339. },
  44340. /**
  44341. * Sets the Color Grading 2D Lookup Texture.
  44342. */
  44343. set: function (value) {
  44344. this._imageProcessingConfiguration.colorGradingTexture = value;
  44345. },
  44346. enumerable: true,
  44347. configurable: true
  44348. });
  44349. StandardMaterial.prototype.getClassName = function () {
  44350. return "StandardMaterial";
  44351. };
  44352. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  44353. get: function () {
  44354. return this._useLogarithmicDepth;
  44355. },
  44356. set: function (value) {
  44357. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44358. this._markAllSubMeshesAsMiscDirty();
  44359. },
  44360. enumerable: true,
  44361. configurable: true
  44362. });
  44363. StandardMaterial.prototype.needAlphaBlending = function () {
  44364. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  44365. };
  44366. StandardMaterial.prototype.needAlphaTesting = function () {
  44367. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  44368. };
  44369. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  44370. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  44371. };
  44372. StandardMaterial.prototype.getAlphaTestTexture = function () {
  44373. return this._diffuseTexture;
  44374. };
  44375. /**
  44376. * Child classes can use it to update shaders
  44377. */
  44378. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44379. if (this.isFrozen) {
  44380. if (this._wasPreviouslyReady && subMesh.effect) {
  44381. return true;
  44382. }
  44383. }
  44384. if (!subMesh._materialDefines) {
  44385. subMesh._materialDefines = new StandardMaterialDefines();
  44386. }
  44387. var scene = this.getScene();
  44388. var defines = subMesh._materialDefines;
  44389. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44390. if (defines._renderId === scene.getRenderId()) {
  44391. return true;
  44392. }
  44393. }
  44394. var engine = scene.getEngine();
  44395. // Lights
  44396. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44397. // Textures
  44398. if (defines._areTexturesDirty) {
  44399. defines._needUVs = false;
  44400. defines.MAINUV1 = false;
  44401. defines.MAINUV2 = false;
  44402. if (scene.texturesEnabled) {
  44403. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44404. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  44405. return false;
  44406. }
  44407. else {
  44408. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  44409. }
  44410. }
  44411. else {
  44412. defines.DIFFUSE = false;
  44413. }
  44414. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44415. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44416. return false;
  44417. }
  44418. else {
  44419. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44420. }
  44421. }
  44422. else {
  44423. defines.AMBIENT = false;
  44424. }
  44425. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44426. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44427. return false;
  44428. }
  44429. else {
  44430. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44431. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44432. }
  44433. }
  44434. else {
  44435. defines.OPACITY = false;
  44436. }
  44437. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44438. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  44439. return false;
  44440. }
  44441. else {
  44442. defines._needNormals = true;
  44443. defines.REFLECTION = true;
  44444. defines.ROUGHNESS = (this._roughness > 0);
  44445. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  44446. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  44447. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  44448. switch (this._reflectionTexture.coordinatesMode) {
  44449. case BABYLON.Texture.CUBIC_MODE:
  44450. case BABYLON.Texture.INVCUBIC_MODE:
  44451. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  44452. break;
  44453. case BABYLON.Texture.EXPLICIT_MODE:
  44454. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  44455. break;
  44456. case BABYLON.Texture.PLANAR_MODE:
  44457. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  44458. break;
  44459. case BABYLON.Texture.PROJECTION_MODE:
  44460. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  44461. break;
  44462. case BABYLON.Texture.SKYBOX_MODE:
  44463. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  44464. break;
  44465. case BABYLON.Texture.SPHERICAL_MODE:
  44466. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  44467. break;
  44468. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44469. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  44470. break;
  44471. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44472. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  44473. break;
  44474. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44475. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  44476. break;
  44477. }
  44478. }
  44479. }
  44480. else {
  44481. defines.REFLECTION = false;
  44482. }
  44483. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44484. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44485. return false;
  44486. }
  44487. else {
  44488. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44489. }
  44490. }
  44491. else {
  44492. defines.EMISSIVE = false;
  44493. }
  44494. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44495. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44496. return false;
  44497. }
  44498. else {
  44499. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44500. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44501. }
  44502. }
  44503. else {
  44504. defines.LIGHTMAP = false;
  44505. }
  44506. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44507. if (!this._specularTexture.isReadyOrNotBlocking()) {
  44508. return false;
  44509. }
  44510. else {
  44511. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  44512. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  44513. }
  44514. }
  44515. else {
  44516. defines.SPECULAR = false;
  44517. }
  44518. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  44519. // Bump texure can not be not blocking.
  44520. if (!this._bumpTexture.isReady()) {
  44521. return false;
  44522. }
  44523. else {
  44524. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44525. defines.PARALLAX = this._useParallax;
  44526. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  44527. }
  44528. }
  44529. else {
  44530. defines.BUMP = false;
  44531. }
  44532. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44533. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  44534. return false;
  44535. }
  44536. else {
  44537. defines._needUVs = true;
  44538. defines.REFRACTION = true;
  44539. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  44540. }
  44541. }
  44542. else {
  44543. defines.REFRACTION = false;
  44544. }
  44545. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  44546. }
  44547. else {
  44548. defines.DIFFUSE = false;
  44549. defines.AMBIENT = false;
  44550. defines.OPACITY = false;
  44551. defines.REFLECTION = false;
  44552. defines.EMISSIVE = false;
  44553. defines.LIGHTMAP = false;
  44554. defines.BUMP = false;
  44555. defines.REFRACTION = false;
  44556. }
  44557. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  44558. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  44559. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  44560. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44561. }
  44562. if (defines._areImageProcessingDirty) {
  44563. if (!this._imageProcessingConfiguration.isReady()) {
  44564. return false;
  44565. }
  44566. this._imageProcessingConfiguration.prepareDefines(defines);
  44567. }
  44568. if (defines._areFresnelDirty) {
  44569. if (StandardMaterial.FresnelEnabled) {
  44570. // Fresnel
  44571. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  44572. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  44573. this._reflectionFresnelParameters) {
  44574. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  44575. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  44576. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  44577. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  44578. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  44579. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  44580. defines._needNormals = true;
  44581. defines.FRESNEL = true;
  44582. }
  44583. }
  44584. else {
  44585. defines.FRESNEL = false;
  44586. }
  44587. }
  44588. // Misc.
  44589. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  44590. // Attribs
  44591. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  44592. // Values that need to be evaluated on every frame
  44593. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  44594. // Get correct effect
  44595. if (defines.isDirty) {
  44596. defines.markAsProcessed();
  44597. scene.resetCachedMaterial();
  44598. // Fallbacks
  44599. var fallbacks = new BABYLON.EffectFallbacks();
  44600. if (defines.REFLECTION) {
  44601. fallbacks.addFallback(0, "REFLECTION");
  44602. }
  44603. if (defines.SPECULAR) {
  44604. fallbacks.addFallback(0, "SPECULAR");
  44605. }
  44606. if (defines.BUMP) {
  44607. fallbacks.addFallback(0, "BUMP");
  44608. }
  44609. if (defines.PARALLAX) {
  44610. fallbacks.addFallback(1, "PARALLAX");
  44611. }
  44612. if (defines.PARALLAXOCCLUSION) {
  44613. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44614. }
  44615. if (defines.SPECULAROVERALPHA) {
  44616. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44617. }
  44618. if (defines.FOG) {
  44619. fallbacks.addFallback(1, "FOG");
  44620. }
  44621. if (defines.POINTSIZE) {
  44622. fallbacks.addFallback(0, "POINTSIZE");
  44623. }
  44624. if (defines.LOGARITHMICDEPTH) {
  44625. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44626. }
  44627. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  44628. if (defines.SPECULARTERM) {
  44629. fallbacks.addFallback(0, "SPECULARTERM");
  44630. }
  44631. if (defines.DIFFUSEFRESNEL) {
  44632. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  44633. }
  44634. if (defines.OPACITYFRESNEL) {
  44635. fallbacks.addFallback(2, "OPACITYFRESNEL");
  44636. }
  44637. if (defines.REFLECTIONFRESNEL) {
  44638. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  44639. }
  44640. if (defines.EMISSIVEFRESNEL) {
  44641. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  44642. }
  44643. if (defines.FRESNEL) {
  44644. fallbacks.addFallback(4, "FRESNEL");
  44645. }
  44646. //Attributes
  44647. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44648. if (defines.NORMAL) {
  44649. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44650. }
  44651. if (defines.UV1) {
  44652. attribs.push(BABYLON.VertexBuffer.UVKind);
  44653. }
  44654. if (defines.UV2) {
  44655. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44656. }
  44657. if (defines.VERTEXCOLOR) {
  44658. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44659. }
  44660. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44661. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44662. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44663. var shaderName = "default";
  44664. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  44665. "vFogInfos", "vFogColor", "pointSize",
  44666. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44667. "mBones",
  44668. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44669. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  44670. "logarithmicDepthConstant", "vNormalReoderParams"
  44671. ];
  44672. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  44673. var uniformBuffers = ["Material", "Scene"];
  44674. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44675. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44676. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44677. uniformsNames: uniforms,
  44678. uniformBuffersNames: uniformBuffers,
  44679. samplers: samplers,
  44680. defines: defines,
  44681. maxSimultaneousLights: this._maxSimultaneousLights
  44682. });
  44683. if (this.customShaderNameResolve) {
  44684. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  44685. }
  44686. var join = defines.toString();
  44687. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  44688. attributes: attribs,
  44689. uniformsNames: uniforms,
  44690. uniformBuffersNames: uniformBuffers,
  44691. samplers: samplers,
  44692. defines: join,
  44693. fallbacks: fallbacks,
  44694. onCompiled: this.onCompiled,
  44695. onError: this.onError,
  44696. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44697. }, engine), defines);
  44698. this.buildUniformLayout();
  44699. }
  44700. if (!subMesh.effect.isReady()) {
  44701. return false;
  44702. }
  44703. defines._renderId = scene.getRenderId();
  44704. this._wasPreviouslyReady = true;
  44705. return true;
  44706. };
  44707. StandardMaterial.prototype.buildUniformLayout = function () {
  44708. // Order is important !
  44709. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  44710. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  44711. this._uniformBuffer.addUniform("opacityParts", 4);
  44712. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  44713. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  44714. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  44715. this._uniformBuffer.addUniform("refractionRightColor", 4);
  44716. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  44717. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  44718. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  44719. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  44720. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44721. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44722. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44723. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44724. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  44725. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44726. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  44727. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44728. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44729. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44730. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44731. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44732. this._uniformBuffer.addUniform("specularMatrix", 16);
  44733. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44734. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  44735. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44736. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44737. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44738. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44739. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44740. this._uniformBuffer.addUniform("pointSize", 1);
  44741. this._uniformBuffer.create();
  44742. };
  44743. StandardMaterial.prototype.unbind = function () {
  44744. if (this._activeEffect) {
  44745. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44746. this._activeEffect.setTexture("reflection2DSampler", null);
  44747. }
  44748. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44749. this._activeEffect.setTexture("refraction2DSampler", null);
  44750. }
  44751. }
  44752. _super.prototype.unbind.call(this);
  44753. };
  44754. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44755. var scene = this.getScene();
  44756. var defines = subMesh._materialDefines;
  44757. if (!defines) {
  44758. return;
  44759. }
  44760. var effect = subMesh.effect;
  44761. this._activeEffect = effect;
  44762. // Matrices
  44763. this.bindOnlyWorldMatrix(world);
  44764. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44765. // Bones
  44766. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44767. if (mustRebind) {
  44768. this._uniformBuffer.bindToEffect(effect, "Material");
  44769. this.bindViewProjection(effect);
  44770. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44771. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44772. // Fresnel
  44773. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44774. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44775. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44776. }
  44777. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44778. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44779. }
  44780. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44781. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44782. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44783. }
  44784. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44785. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44786. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44787. }
  44788. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44789. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44790. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44791. }
  44792. }
  44793. // Textures
  44794. if (scene.texturesEnabled) {
  44795. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44796. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44797. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44798. }
  44799. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44800. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44801. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44802. }
  44803. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44804. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44805. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44806. }
  44807. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44808. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44809. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44810. }
  44811. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44812. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44813. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44814. }
  44815. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44816. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44817. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44818. }
  44819. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44820. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44821. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44822. }
  44823. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44824. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44825. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44826. if (scene._mirroredCameraPosition) {
  44827. 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);
  44828. }
  44829. else {
  44830. 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);
  44831. }
  44832. }
  44833. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44834. var depth = 1.0;
  44835. if (!this._refractionTexture.isCube) {
  44836. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44837. if (this._refractionTexture.depth) {
  44838. depth = this._refractionTexture.depth;
  44839. }
  44840. }
  44841. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44842. }
  44843. }
  44844. // Point size
  44845. if (this.pointsCloud) {
  44846. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44847. }
  44848. if (defines.SPECULARTERM) {
  44849. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44850. }
  44851. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44852. // Diffuse
  44853. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44854. }
  44855. // Textures
  44856. if (scene.texturesEnabled) {
  44857. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44858. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44859. }
  44860. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44861. effect.setTexture("ambientSampler", this._ambientTexture);
  44862. }
  44863. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44864. effect.setTexture("opacitySampler", this._opacityTexture);
  44865. }
  44866. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44867. if (this._reflectionTexture.isCube) {
  44868. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44869. }
  44870. else {
  44871. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44872. }
  44873. }
  44874. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44875. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44876. }
  44877. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44878. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44879. }
  44880. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44881. effect.setTexture("specularSampler", this._specularTexture);
  44882. }
  44883. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44884. effect.setTexture("bumpSampler", this._bumpTexture);
  44885. }
  44886. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44887. var depth = 1.0;
  44888. if (this._refractionTexture.isCube) {
  44889. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44890. }
  44891. else {
  44892. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44893. }
  44894. }
  44895. }
  44896. // Clip plane
  44897. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44898. // Colors
  44899. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44900. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44901. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44902. }
  44903. if (mustRebind || !this.isFrozen) {
  44904. // Lights
  44905. if (scene.lightsEnabled && !this._disableLighting) {
  44906. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44907. }
  44908. // View
  44909. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44910. this.bindView(effect);
  44911. }
  44912. // Fog
  44913. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44914. // Morph targets
  44915. if (defines.NUM_MORPH_INFLUENCERS) {
  44916. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44917. }
  44918. // Log. depth
  44919. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44920. // image processing
  44921. this._imageProcessingConfiguration.bind(this._activeEffect);
  44922. }
  44923. this._uniformBuffer.update();
  44924. this._afterBind(mesh, this._activeEffect);
  44925. };
  44926. StandardMaterial.prototype.getAnimatables = function () {
  44927. var results = [];
  44928. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44929. results.push(this._diffuseTexture);
  44930. }
  44931. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44932. results.push(this._ambientTexture);
  44933. }
  44934. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44935. results.push(this._opacityTexture);
  44936. }
  44937. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44938. results.push(this._reflectionTexture);
  44939. }
  44940. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44941. results.push(this._emissiveTexture);
  44942. }
  44943. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44944. results.push(this._specularTexture);
  44945. }
  44946. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44947. results.push(this._bumpTexture);
  44948. }
  44949. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44950. results.push(this._lightmapTexture);
  44951. }
  44952. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44953. results.push(this._refractionTexture);
  44954. }
  44955. return results;
  44956. };
  44957. StandardMaterial.prototype.getActiveTextures = function () {
  44958. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44959. if (this._diffuseTexture) {
  44960. activeTextures.push(this._diffuseTexture);
  44961. }
  44962. if (this._ambientTexture) {
  44963. activeTextures.push(this._ambientTexture);
  44964. }
  44965. if (this._opacityTexture) {
  44966. activeTextures.push(this._opacityTexture);
  44967. }
  44968. if (this._reflectionTexture) {
  44969. activeTextures.push(this._reflectionTexture);
  44970. }
  44971. if (this._emissiveTexture) {
  44972. activeTextures.push(this._emissiveTexture);
  44973. }
  44974. if (this._specularTexture) {
  44975. activeTextures.push(this._specularTexture);
  44976. }
  44977. if (this._bumpTexture) {
  44978. activeTextures.push(this._bumpTexture);
  44979. }
  44980. if (this._lightmapTexture) {
  44981. activeTextures.push(this._lightmapTexture);
  44982. }
  44983. if (this._refractionTexture) {
  44984. activeTextures.push(this._refractionTexture);
  44985. }
  44986. return activeTextures;
  44987. };
  44988. StandardMaterial.prototype.hasTexture = function (texture) {
  44989. if (_super.prototype.hasTexture.call(this, texture)) {
  44990. return true;
  44991. }
  44992. if (this._diffuseTexture === texture) {
  44993. return true;
  44994. }
  44995. if (this._ambientTexture === texture) {
  44996. return true;
  44997. }
  44998. if (this._opacityTexture === texture) {
  44999. return true;
  45000. }
  45001. if (this._reflectionTexture === texture) {
  45002. return true;
  45003. }
  45004. if (this._emissiveTexture === texture) {
  45005. return true;
  45006. }
  45007. if (this._specularTexture === texture) {
  45008. return true;
  45009. }
  45010. if (this._bumpTexture === texture) {
  45011. return true;
  45012. }
  45013. if (this._lightmapTexture === texture) {
  45014. return true;
  45015. }
  45016. if (this._refractionTexture === texture) {
  45017. return true;
  45018. }
  45019. return false;
  45020. };
  45021. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45022. if (forceDisposeTextures) {
  45023. if (this._diffuseTexture) {
  45024. this._diffuseTexture.dispose();
  45025. }
  45026. if (this._ambientTexture) {
  45027. this._ambientTexture.dispose();
  45028. }
  45029. if (this._opacityTexture) {
  45030. this._opacityTexture.dispose();
  45031. }
  45032. if (this._reflectionTexture) {
  45033. this._reflectionTexture.dispose();
  45034. }
  45035. if (this._emissiveTexture) {
  45036. this._emissiveTexture.dispose();
  45037. }
  45038. if (this._specularTexture) {
  45039. this._specularTexture.dispose();
  45040. }
  45041. if (this._bumpTexture) {
  45042. this._bumpTexture.dispose();
  45043. }
  45044. if (this._lightmapTexture) {
  45045. this._lightmapTexture.dispose();
  45046. }
  45047. if (this._refractionTexture) {
  45048. this._refractionTexture.dispose();
  45049. }
  45050. }
  45051. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45052. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45053. }
  45054. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45055. };
  45056. StandardMaterial.prototype.clone = function (name) {
  45057. var _this = this;
  45058. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  45059. result.name = name;
  45060. result.id = name;
  45061. return result;
  45062. };
  45063. StandardMaterial.prototype.serialize = function () {
  45064. return BABYLON.SerializationHelper.Serialize(this);
  45065. };
  45066. // Statics
  45067. StandardMaterial.Parse = function (source, scene, rootUrl) {
  45068. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  45069. };
  45070. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  45071. get: function () {
  45072. return StandardMaterial._DiffuseTextureEnabled;
  45073. },
  45074. set: function (value) {
  45075. if (StandardMaterial._DiffuseTextureEnabled === value) {
  45076. return;
  45077. }
  45078. StandardMaterial._DiffuseTextureEnabled = value;
  45079. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45080. },
  45081. enumerable: true,
  45082. configurable: true
  45083. });
  45084. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  45085. get: function () {
  45086. return StandardMaterial._AmbientTextureEnabled;
  45087. },
  45088. set: function (value) {
  45089. if (StandardMaterial._AmbientTextureEnabled === value) {
  45090. return;
  45091. }
  45092. StandardMaterial._AmbientTextureEnabled = value;
  45093. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45094. },
  45095. enumerable: true,
  45096. configurable: true
  45097. });
  45098. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  45099. get: function () {
  45100. return StandardMaterial._OpacityTextureEnabled;
  45101. },
  45102. set: function (value) {
  45103. if (StandardMaterial._OpacityTextureEnabled === value) {
  45104. return;
  45105. }
  45106. StandardMaterial._OpacityTextureEnabled = value;
  45107. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45108. },
  45109. enumerable: true,
  45110. configurable: true
  45111. });
  45112. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  45113. get: function () {
  45114. return StandardMaterial._ReflectionTextureEnabled;
  45115. },
  45116. set: function (value) {
  45117. if (StandardMaterial._ReflectionTextureEnabled === value) {
  45118. return;
  45119. }
  45120. StandardMaterial._ReflectionTextureEnabled = value;
  45121. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45122. },
  45123. enumerable: true,
  45124. configurable: true
  45125. });
  45126. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  45127. get: function () {
  45128. return StandardMaterial._EmissiveTextureEnabled;
  45129. },
  45130. set: function (value) {
  45131. if (StandardMaterial._EmissiveTextureEnabled === value) {
  45132. return;
  45133. }
  45134. StandardMaterial._EmissiveTextureEnabled = value;
  45135. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45136. },
  45137. enumerable: true,
  45138. configurable: true
  45139. });
  45140. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  45141. get: function () {
  45142. return StandardMaterial._SpecularTextureEnabled;
  45143. },
  45144. set: function (value) {
  45145. if (StandardMaterial._SpecularTextureEnabled === value) {
  45146. return;
  45147. }
  45148. StandardMaterial._SpecularTextureEnabled = value;
  45149. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45150. },
  45151. enumerable: true,
  45152. configurable: true
  45153. });
  45154. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  45155. get: function () {
  45156. return StandardMaterial._BumpTextureEnabled;
  45157. },
  45158. set: function (value) {
  45159. if (StandardMaterial._BumpTextureEnabled === value) {
  45160. return;
  45161. }
  45162. StandardMaterial._BumpTextureEnabled = value;
  45163. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45164. },
  45165. enumerable: true,
  45166. configurable: true
  45167. });
  45168. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  45169. get: function () {
  45170. return StandardMaterial._LightmapTextureEnabled;
  45171. },
  45172. set: function (value) {
  45173. if (StandardMaterial._LightmapTextureEnabled === value) {
  45174. return;
  45175. }
  45176. StandardMaterial._LightmapTextureEnabled = value;
  45177. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45178. },
  45179. enumerable: true,
  45180. configurable: true
  45181. });
  45182. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  45183. get: function () {
  45184. return StandardMaterial._RefractionTextureEnabled;
  45185. },
  45186. set: function (value) {
  45187. if (StandardMaterial._RefractionTextureEnabled === value) {
  45188. return;
  45189. }
  45190. StandardMaterial._RefractionTextureEnabled = value;
  45191. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45192. },
  45193. enumerable: true,
  45194. configurable: true
  45195. });
  45196. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  45197. get: function () {
  45198. return StandardMaterial._ColorGradingTextureEnabled;
  45199. },
  45200. set: function (value) {
  45201. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  45202. return;
  45203. }
  45204. StandardMaterial._ColorGradingTextureEnabled = value;
  45205. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45206. },
  45207. enumerable: true,
  45208. configurable: true
  45209. });
  45210. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  45211. get: function () {
  45212. return StandardMaterial._FresnelEnabled;
  45213. },
  45214. set: function (value) {
  45215. if (StandardMaterial._FresnelEnabled === value) {
  45216. return;
  45217. }
  45218. StandardMaterial._FresnelEnabled = value;
  45219. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  45220. },
  45221. enumerable: true,
  45222. configurable: true
  45223. });
  45224. // Flags used to enable or disable a type of texture for all Standard Materials
  45225. StandardMaterial._DiffuseTextureEnabled = true;
  45226. StandardMaterial._AmbientTextureEnabled = true;
  45227. StandardMaterial._OpacityTextureEnabled = true;
  45228. StandardMaterial._ReflectionTextureEnabled = true;
  45229. StandardMaterial._EmissiveTextureEnabled = true;
  45230. StandardMaterial._SpecularTextureEnabled = true;
  45231. StandardMaterial._BumpTextureEnabled = true;
  45232. StandardMaterial._LightmapTextureEnabled = true;
  45233. StandardMaterial._RefractionTextureEnabled = true;
  45234. StandardMaterial._ColorGradingTextureEnabled = true;
  45235. StandardMaterial._FresnelEnabled = true;
  45236. __decorate([
  45237. BABYLON.serializeAsTexture("diffuseTexture")
  45238. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  45239. __decorate([
  45240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45241. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  45242. __decorate([
  45243. BABYLON.serializeAsTexture("ambientTexture")
  45244. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  45245. __decorate([
  45246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45247. ], StandardMaterial.prototype, "ambientTexture", void 0);
  45248. __decorate([
  45249. BABYLON.serializeAsTexture("opacityTexture")
  45250. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  45251. __decorate([
  45252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45253. ], StandardMaterial.prototype, "opacityTexture", void 0);
  45254. __decorate([
  45255. BABYLON.serializeAsTexture("reflectionTexture")
  45256. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  45257. __decorate([
  45258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45259. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  45260. __decorate([
  45261. BABYLON.serializeAsTexture("emissiveTexture")
  45262. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  45263. __decorate([
  45264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45265. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  45266. __decorate([
  45267. BABYLON.serializeAsTexture("specularTexture")
  45268. ], StandardMaterial.prototype, "_specularTexture", void 0);
  45269. __decorate([
  45270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45271. ], StandardMaterial.prototype, "specularTexture", void 0);
  45272. __decorate([
  45273. BABYLON.serializeAsTexture("bumpTexture")
  45274. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  45275. __decorate([
  45276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45277. ], StandardMaterial.prototype, "bumpTexture", void 0);
  45278. __decorate([
  45279. BABYLON.serializeAsTexture("lightmapTexture")
  45280. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  45281. __decorate([
  45282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45283. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  45284. __decorate([
  45285. BABYLON.serializeAsTexture("refractionTexture")
  45286. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  45287. __decorate([
  45288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45289. ], StandardMaterial.prototype, "refractionTexture", void 0);
  45290. __decorate([
  45291. BABYLON.serializeAsColor3("ambient")
  45292. ], StandardMaterial.prototype, "ambientColor", void 0);
  45293. __decorate([
  45294. BABYLON.serializeAsColor3("diffuse")
  45295. ], StandardMaterial.prototype, "diffuseColor", void 0);
  45296. __decorate([
  45297. BABYLON.serializeAsColor3("specular")
  45298. ], StandardMaterial.prototype, "specularColor", void 0);
  45299. __decorate([
  45300. BABYLON.serializeAsColor3("emissive")
  45301. ], StandardMaterial.prototype, "emissiveColor", void 0);
  45302. __decorate([
  45303. BABYLON.serialize()
  45304. ], StandardMaterial.prototype, "specularPower", void 0);
  45305. __decorate([
  45306. BABYLON.serialize("useAlphaFromDiffuseTexture")
  45307. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  45308. __decorate([
  45309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45310. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  45311. __decorate([
  45312. BABYLON.serialize("useEmissiveAsIllumination")
  45313. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  45314. __decorate([
  45315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45316. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  45317. __decorate([
  45318. BABYLON.serialize("linkEmissiveWithDiffuse")
  45319. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  45320. __decorate([
  45321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45322. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  45323. __decorate([
  45324. BABYLON.serialize("useSpecularOverAlpha")
  45325. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  45326. __decorate([
  45327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45328. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  45329. __decorate([
  45330. BABYLON.serialize("useReflectionOverAlpha")
  45331. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  45332. __decorate([
  45333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45334. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  45335. __decorate([
  45336. BABYLON.serialize("disableLighting")
  45337. ], StandardMaterial.prototype, "_disableLighting", void 0);
  45338. __decorate([
  45339. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45340. ], StandardMaterial.prototype, "disableLighting", void 0);
  45341. __decorate([
  45342. BABYLON.serialize("useParallax")
  45343. ], StandardMaterial.prototype, "_useParallax", void 0);
  45344. __decorate([
  45345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45346. ], StandardMaterial.prototype, "useParallax", void 0);
  45347. __decorate([
  45348. BABYLON.serialize("useParallaxOcclusion")
  45349. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  45350. __decorate([
  45351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45352. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  45353. __decorate([
  45354. BABYLON.serialize()
  45355. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  45356. __decorate([
  45357. BABYLON.serialize("roughness")
  45358. ], StandardMaterial.prototype, "_roughness", void 0);
  45359. __decorate([
  45360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45361. ], StandardMaterial.prototype, "roughness", void 0);
  45362. __decorate([
  45363. BABYLON.serialize()
  45364. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  45365. __decorate([
  45366. BABYLON.serialize()
  45367. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  45368. __decorate([
  45369. BABYLON.serialize("useLightmapAsShadowmap")
  45370. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  45371. __decorate([
  45372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45373. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45374. __decorate([
  45375. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  45376. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  45377. __decorate([
  45378. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45379. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  45380. __decorate([
  45381. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  45382. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  45383. __decorate([
  45384. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45385. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  45386. __decorate([
  45387. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  45388. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  45389. __decorate([
  45390. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45391. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  45392. __decorate([
  45393. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  45394. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  45395. __decorate([
  45396. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45397. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  45398. __decorate([
  45399. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  45400. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  45401. __decorate([
  45402. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45403. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  45404. __decorate([
  45405. BABYLON.serialize("useReflectionFresnelFromSpecular")
  45406. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  45407. __decorate([
  45408. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45409. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  45410. __decorate([
  45411. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  45412. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  45413. __decorate([
  45414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45415. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  45416. __decorate([
  45417. BABYLON.serialize("maxSimultaneousLights")
  45418. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  45419. __decorate([
  45420. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45421. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  45422. __decorate([
  45423. BABYLON.serialize("invertNormalMapX")
  45424. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  45425. __decorate([
  45426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45427. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  45428. __decorate([
  45429. BABYLON.serialize("invertNormalMapY")
  45430. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  45431. __decorate([
  45432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45433. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  45434. __decorate([
  45435. BABYLON.serialize("twoSidedLighting")
  45436. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  45437. __decorate([
  45438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45439. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  45440. __decorate([
  45441. BABYLON.serialize()
  45442. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  45443. return StandardMaterial;
  45444. }(BABYLON.PushMaterial));
  45445. BABYLON.StandardMaterial = StandardMaterial;
  45446. })(BABYLON || (BABYLON = {}));
  45447. //# sourceMappingURL=babylon.standardMaterial.js.map
  45448. var BABYLON;
  45449. (function (BABYLON) {
  45450. /**
  45451. * This class implement a typical dictionary using a string as key and the generic type T as value.
  45452. * The underlying implementation relies on an associative array to ensure the best performances.
  45453. * The value can be anything including 'null' but except 'undefined'
  45454. */
  45455. var StringDictionary = (function () {
  45456. function StringDictionary() {
  45457. this._count = 0;
  45458. this._data = {};
  45459. }
  45460. /**
  45461. * This will clear this dictionary and copy the content from the 'source' one.
  45462. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  45463. * @param source the dictionary to take the content from and copy to this dictionary
  45464. */
  45465. StringDictionary.prototype.copyFrom = function (source) {
  45466. var _this = this;
  45467. this.clear();
  45468. source.forEach(function (t, v) { return _this.add(t, v); });
  45469. };
  45470. /**
  45471. * Get a value based from its key
  45472. * @param key the given key to get the matching value from
  45473. * @return the value if found, otherwise undefined is returned
  45474. */
  45475. StringDictionary.prototype.get = function (key) {
  45476. var val = this._data[key];
  45477. if (val !== undefined) {
  45478. return val;
  45479. }
  45480. return undefined;
  45481. };
  45482. /**
  45483. * Get a value from its key or add it if it doesn't exist.
  45484. * This method will ensure you that a given key/data will be present in the dictionary.
  45485. * @param key the given key to get the matching value from
  45486. * @param factory the factory that will create the value if the key is not present in the dictionary.
  45487. * The factory will only be invoked if there's no data for the given key.
  45488. * @return the value corresponding to the key.
  45489. */
  45490. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  45491. var val = this.get(key);
  45492. if (val !== undefined) {
  45493. return val;
  45494. }
  45495. val = factory(key);
  45496. if (val) {
  45497. this.add(key, val);
  45498. }
  45499. return val;
  45500. };
  45501. /**
  45502. * Get a value from its key if present in the dictionary otherwise add it
  45503. * @param key the key to get the value from
  45504. * @param val if there's no such key/value pair in the dictionary add it with this value
  45505. * @return the value corresponding to the key
  45506. */
  45507. StringDictionary.prototype.getOrAdd = function (key, val) {
  45508. var curVal = this.get(key);
  45509. if (curVal !== undefined) {
  45510. return curVal;
  45511. }
  45512. this.add(key, val);
  45513. return val;
  45514. };
  45515. /**
  45516. * Check if there's a given key in the dictionary
  45517. * @param key the key to check for
  45518. * @return true if the key is present, false otherwise
  45519. */
  45520. StringDictionary.prototype.contains = function (key) {
  45521. return this._data[key] !== undefined;
  45522. };
  45523. /**
  45524. * Add a new key and its corresponding value
  45525. * @param key the key to add
  45526. * @param value the value corresponding to the key
  45527. * @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
  45528. */
  45529. StringDictionary.prototype.add = function (key, value) {
  45530. if (this._data[key] !== undefined) {
  45531. return false;
  45532. }
  45533. this._data[key] = value;
  45534. ++this._count;
  45535. return true;
  45536. };
  45537. StringDictionary.prototype.set = function (key, value) {
  45538. if (this._data[key] === undefined) {
  45539. return false;
  45540. }
  45541. this._data[key] = value;
  45542. return true;
  45543. };
  45544. /**
  45545. * Get the element of the given key and remove it from the dictionary
  45546. * @param key
  45547. */
  45548. StringDictionary.prototype.getAndRemove = function (key) {
  45549. var val = this.get(key);
  45550. if (val !== undefined) {
  45551. delete this._data[key];
  45552. --this._count;
  45553. return val;
  45554. }
  45555. return null;
  45556. };
  45557. /**
  45558. * Remove a key/value from the dictionary.
  45559. * @param key the key to remove
  45560. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  45561. */
  45562. StringDictionary.prototype.remove = function (key) {
  45563. if (this.contains(key)) {
  45564. delete this._data[key];
  45565. --this._count;
  45566. return true;
  45567. }
  45568. return false;
  45569. };
  45570. /**
  45571. * Clear the whole content of the dictionary
  45572. */
  45573. StringDictionary.prototype.clear = function () {
  45574. this._data = {};
  45575. this._count = 0;
  45576. };
  45577. Object.defineProperty(StringDictionary.prototype, "count", {
  45578. get: function () {
  45579. return this._count;
  45580. },
  45581. enumerable: true,
  45582. configurable: true
  45583. });
  45584. /**
  45585. * Execute a callback on each key/val of the dictionary.
  45586. * Note that you can remove any element in this dictionary in the callback implementation
  45587. * @param callback the callback to execute on a given key/value pair
  45588. */
  45589. StringDictionary.prototype.forEach = function (callback) {
  45590. for (var cur in this._data) {
  45591. var val = this._data[cur];
  45592. callback(cur, val);
  45593. }
  45594. };
  45595. /**
  45596. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  45597. * If the callback returns null or undefined the method will iterate to the next key/value pair
  45598. * Note that you can remove any element in this dictionary in the callback implementation
  45599. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  45600. */
  45601. StringDictionary.prototype.first = function (callback) {
  45602. for (var cur in this._data) {
  45603. var val = this._data[cur];
  45604. var res = callback(cur, val);
  45605. if (res) {
  45606. return res;
  45607. }
  45608. }
  45609. return null;
  45610. };
  45611. return StringDictionary;
  45612. }());
  45613. BABYLON.StringDictionary = StringDictionary;
  45614. })(BABYLON || (BABYLON = {}));
  45615. //# sourceMappingURL=babylon.stringDictionary.js.map
  45616. var BABYLON;
  45617. (function (BABYLON) {
  45618. var DynamicFloatArrayElementInfo = (function () {
  45619. function DynamicFloatArrayElementInfo() {
  45620. }
  45621. return DynamicFloatArrayElementInfo;
  45622. }());
  45623. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  45624. /**
  45625. * 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.
  45626. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  45627. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  45628. * 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.
  45629. * 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.
  45630. * 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".
  45631. */
  45632. var DynamicFloatArray = (function () {
  45633. /**
  45634. * Construct an instance of the dynamic float array
  45635. * @param stride size of one element in float (i.e. not bytes!)
  45636. * @param initialElementCount the number of available entries at construction
  45637. */
  45638. function DynamicFloatArray(stride, initialElementCount) {
  45639. this.compareValueOffset = null;
  45640. this.sortingAscending = true;
  45641. this._stride = stride;
  45642. this.buffer = new Float32Array(stride * initialElementCount);
  45643. this._lastUsed = 0;
  45644. this._firstFree = 0;
  45645. this._allEntries = new Array(initialElementCount);
  45646. this._freeEntries = new Array(initialElementCount);
  45647. for (var i = 0; i < initialElementCount; i++) {
  45648. var element = new DynamicFloatArrayElementInfo();
  45649. element.offset = i * stride;
  45650. this._allEntries[i] = element;
  45651. this._freeEntries[initialElementCount - i - 1] = element;
  45652. }
  45653. }
  45654. /**
  45655. * Allocate an element in the array.
  45656. * @return the element info instance that contains the offset into the main buffer of the element's location.
  45657. * Beware, this offset may change when you call pack()
  45658. */
  45659. DynamicFloatArray.prototype.allocElement = function () {
  45660. if (this._freeEntries.length === 0) {
  45661. this._growBuffer();
  45662. }
  45663. var el = this._freeEntries.pop();
  45664. this._lastUsed = Math.max(el.offset, this._lastUsed);
  45665. if (el.offset === this._firstFree) {
  45666. if (this._freeEntries.length > 0) {
  45667. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  45668. }
  45669. else {
  45670. this._firstFree += this._stride;
  45671. }
  45672. }
  45673. return el;
  45674. };
  45675. /**
  45676. * Free the element corresponding to the given element info
  45677. * @param elInfo the element that describe the allocated element
  45678. */
  45679. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  45680. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  45681. this._freeEntries.push(elInfo);
  45682. };
  45683. /**
  45684. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  45685. * 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().
  45686. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  45687. */
  45688. DynamicFloatArray.prototype.pack = function () {
  45689. // no free slot? no need to pack
  45690. if (this._freeEntries.length === 0) {
  45691. return this.buffer;
  45692. }
  45693. // If the buffer is already packed the last used will always be lower than the first free
  45694. // 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.
  45695. if (this._lastUsed < this._firstFree) {
  45696. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  45697. return elementsBuffer_1;
  45698. }
  45699. var s = this._stride;
  45700. // 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
  45701. var lastFree = new DynamicFloatArrayElementInfo();
  45702. lastFree.offset = this.totalElementCount * s;
  45703. this._freeEntries.push(lastFree);
  45704. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  45705. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45706. var firstFreeSlotOffset = sortedFree[0].offset;
  45707. var freeZoneSize = 1;
  45708. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  45709. var prevOffset = sortedFree[0].offset;
  45710. for (var i = 1; i < sortedFree.length; i++) {
  45711. // 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
  45712. if (firstFreeSlotOffset >= occupiedZoneSize) {
  45713. break;
  45714. }
  45715. var curFree = sortedFree[i];
  45716. var curOffset = curFree.offset;
  45717. // Compute the distance between this offset and the previous
  45718. var distance = curOffset - prevOffset;
  45719. // If the distance is the stride size, they are adjacent, it good, move to the next
  45720. if (distance === s) {
  45721. // Free zone is one element bigger
  45722. ++freeZoneSize;
  45723. // as we're about to iterate to the next, the cur becomes the previous...
  45724. prevOffset = curOffset;
  45725. continue;
  45726. }
  45727. // Distance is bigger, which means there's x element between the previous free and this one
  45728. var usedRange = (distance / s) - 1;
  45729. // Two cases the free zone is smaller than the data to move or bigger
  45730. // Copy what can fit in the free zone
  45731. var curMoveOffset = curOffset - s;
  45732. var copyCount = Math.min(freeZoneSize, usedRange);
  45733. for (var j = 0; j < copyCount; j++) {
  45734. var freeI = firstFreeSlotOffset / s;
  45735. var curI = curMoveOffset / s;
  45736. var moveEl = sortedAll[curI];
  45737. this._moveElement(moveEl, firstFreeSlotOffset);
  45738. var replacedEl = sortedAll[freeI];
  45739. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  45740. replacedEl.offset = curMoveOffset;
  45741. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  45742. sortedAll[freeI] = moveEl;
  45743. sortedAll[curI] = replacedEl;
  45744. curMoveOffset -= s;
  45745. firstFreeSlotOffset += s;
  45746. }
  45747. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  45748. if (freeZoneSize <= usedRange) {
  45749. firstFreeSlotOffset = curMoveOffset + s;
  45750. freeZoneSize = 1 + copyCount;
  45751. }
  45752. else {
  45753. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  45754. }
  45755. // as we're about to iterate to the next, the cur becomes the previous...
  45756. prevOffset = curOffset;
  45757. }
  45758. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  45759. this._lastUsed = firstFreeSlotOffset - s;
  45760. this._firstFree = firstFreeSlotOffset;
  45761. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  45762. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  45763. this._allEntries = sortedAll;
  45764. return elementsBuffer;
  45765. };
  45766. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  45767. for (var i = 0; i < this._stride; i++) {
  45768. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  45769. }
  45770. element.offset = destOffset;
  45771. };
  45772. DynamicFloatArray.prototype._growBuffer = function () {
  45773. // Allocate the new buffer with 50% more entries, copy the content of the current one
  45774. var newElCount = Math.floor(this.totalElementCount * 1.5);
  45775. var newBuffer = new Float32Array(newElCount * this._stride);
  45776. newBuffer.set(this.buffer);
  45777. var curCount = this.totalElementCount;
  45778. var addedCount = newElCount - this.totalElementCount;
  45779. for (var i = 0; i < addedCount; i++) {
  45780. var element = new DynamicFloatArrayElementInfo();
  45781. element.offset = (curCount + i) * this.stride;
  45782. this._allEntries.push(element);
  45783. this._freeEntries[addedCount - i - 1] = element;
  45784. }
  45785. this._firstFree = curCount * this.stride;
  45786. this.buffer = newBuffer;
  45787. };
  45788. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  45789. /**
  45790. * Get the total count of entries that can fit in the current buffer
  45791. * @returns the elements count
  45792. */
  45793. get: function () {
  45794. return this._allEntries.length;
  45795. },
  45796. enumerable: true,
  45797. configurable: true
  45798. });
  45799. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  45800. /**
  45801. * Get the count of free entries that can still be allocated without resizing the buffer
  45802. * @returns the free elements count
  45803. */
  45804. get: function () {
  45805. return this._freeEntries.length;
  45806. },
  45807. enumerable: true,
  45808. configurable: true
  45809. });
  45810. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  45811. /**
  45812. * Get the count of allocated elements
  45813. * @returns the allocated elements count
  45814. */
  45815. get: function () {
  45816. return this._allEntries.length - this._freeEntries.length;
  45817. },
  45818. enumerable: true,
  45819. configurable: true
  45820. });
  45821. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  45822. /**
  45823. * Return the size of one element in float
  45824. * @returns the size in float
  45825. */
  45826. get: function () {
  45827. return this._stride;
  45828. },
  45829. enumerable: true,
  45830. configurable: true
  45831. });
  45832. DynamicFloatArray.prototype.sort = function () {
  45833. var _this = this;
  45834. if (!this.compareValueOffset) {
  45835. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  45836. }
  45837. var count = this.usedElementCount;
  45838. // Do we have to (re)create the sort table?
  45839. if (!this._sortTable || this._sortTable.length < count) {
  45840. // 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...
  45841. var newCount = Math.min(this.totalElementCount, count * 2);
  45842. this._sortTable = new Array(newCount);
  45843. }
  45844. if (!this._sortedTable || this._sortedTable.length !== count) {
  45845. this._sortedTable = new Array(count);
  45846. }
  45847. // Because, you know...
  45848. this.pack();
  45849. //let stride = this.stride;
  45850. //for (let i = 0; i < count; i++) {
  45851. // let si = this._sortTable[i];
  45852. // if (!si) {
  45853. // si = new SortInfo();
  45854. // this._sortTable[i] = si;
  45855. // }
  45856. // si.entry = this._allEntries[i];
  45857. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  45858. // si.swapedOffset = null;
  45859. // this._sortedTable[i] = si;
  45860. //}
  45861. var curOffset = 0;
  45862. var stride = this.stride;
  45863. for (var i = 0; i < count; i++, curOffset += stride) {
  45864. var si = this._sortTable[i];
  45865. if (!si) {
  45866. si = new SortInfo();
  45867. this._sortTable[i] = si;
  45868. }
  45869. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  45870. si.offset = curOffset;
  45871. si.swapedOffset = null;
  45872. this._sortedTable[i] = si;
  45873. }
  45874. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  45875. if (this.sortingAscending) {
  45876. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  45877. }
  45878. else {
  45879. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  45880. }
  45881. var swapElements = function (src, dst) {
  45882. for (var i = 0; i < stride; i++) {
  45883. var tps = _this.buffer[dst + i];
  45884. _this.buffer[dst + i] = _this.buffer[src + i];
  45885. _this.buffer[src + i] = tps;
  45886. }
  45887. };
  45888. // 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:
  45889. // 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),
  45890. // and I still want something with a good algorithm complexity.
  45891. // 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,
  45892. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  45893. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  45894. // 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
  45895. // until we find a SortInfo object without a swapedOffset which means we got the right location
  45896. // 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
  45897. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  45898. for (var i = 0; i < count; i++) {
  45899. // Get the element to move
  45900. var sourceSI = this._sortedTable[i];
  45901. var destSI = this._sortTable[i];
  45902. var sourceOff = sourceSI.offset;
  45903. // If the source changed location, find the new one
  45904. if (sourceSI.swapedOffset) {
  45905. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  45906. var curSI = sourceSI;
  45907. while (curSI.swapedOffset) {
  45908. curSI = this._sortTable[curSI.swapedOffset / stride];
  45909. }
  45910. // Finally get the right location
  45911. sourceOff = curSI.offset;
  45912. }
  45913. // Tag the element being replaced with its new location
  45914. destSI.swapedOffset = sourceOff;
  45915. // Swap elements (only if needed)
  45916. if (sourceOff !== destSI.offset) {
  45917. swapElements(sourceOff, destSI.offset);
  45918. }
  45919. // Update the offset in the corresponding DFAE
  45920. //sourceSI.entry.offset = destSI.entry.offset;
  45921. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  45922. }
  45923. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45924. return true;
  45925. };
  45926. return DynamicFloatArray;
  45927. }());
  45928. BABYLON.DynamicFloatArray = DynamicFloatArray;
  45929. var SortInfo = (function () {
  45930. function SortInfo() {
  45931. this.compareData = this.offset = this.swapedOffset = null;
  45932. }
  45933. return SortInfo;
  45934. }());
  45935. })(BABYLON || (BABYLON = {}));
  45936. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  45937. var BABYLON;
  45938. (function (BABYLON) {
  45939. var Condition = (function () {
  45940. function Condition(actionManager) {
  45941. this._actionManager = actionManager;
  45942. }
  45943. Condition.prototype.isValid = function () {
  45944. return true;
  45945. };
  45946. Condition.prototype._getProperty = function (propertyPath) {
  45947. return this._actionManager._getProperty(propertyPath);
  45948. };
  45949. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  45950. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45951. };
  45952. Condition.prototype.serialize = function () {
  45953. };
  45954. Condition.prototype._serialize = function (serializedCondition) {
  45955. return {
  45956. type: 2,
  45957. children: [],
  45958. name: serializedCondition.name,
  45959. properties: serializedCondition.properties
  45960. };
  45961. };
  45962. return Condition;
  45963. }());
  45964. BABYLON.Condition = Condition;
  45965. var ValueCondition = (function (_super) {
  45966. __extends(ValueCondition, _super);
  45967. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  45968. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  45969. var _this = _super.call(this, actionManager) || this;
  45970. _this.propertyPath = propertyPath;
  45971. _this.value = value;
  45972. _this.operator = operator;
  45973. _this._target = target;
  45974. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  45975. _this._property = _this._getProperty(_this.propertyPath);
  45976. return _this;
  45977. }
  45978. Object.defineProperty(ValueCondition, "IsEqual", {
  45979. get: function () {
  45980. return ValueCondition._IsEqual;
  45981. },
  45982. enumerable: true,
  45983. configurable: true
  45984. });
  45985. Object.defineProperty(ValueCondition, "IsDifferent", {
  45986. get: function () {
  45987. return ValueCondition._IsDifferent;
  45988. },
  45989. enumerable: true,
  45990. configurable: true
  45991. });
  45992. Object.defineProperty(ValueCondition, "IsGreater", {
  45993. get: function () {
  45994. return ValueCondition._IsGreater;
  45995. },
  45996. enumerable: true,
  45997. configurable: true
  45998. });
  45999. Object.defineProperty(ValueCondition, "IsLesser", {
  46000. get: function () {
  46001. return ValueCondition._IsLesser;
  46002. },
  46003. enumerable: true,
  46004. configurable: true
  46005. });
  46006. // Methods
  46007. ValueCondition.prototype.isValid = function () {
  46008. switch (this.operator) {
  46009. case ValueCondition.IsGreater:
  46010. return this._effectiveTarget[this._property] > this.value;
  46011. case ValueCondition.IsLesser:
  46012. return this._effectiveTarget[this._property] < this.value;
  46013. case ValueCondition.IsEqual:
  46014. case ValueCondition.IsDifferent:
  46015. var check;
  46016. if (this.value.equals) {
  46017. check = this.value.equals(this._effectiveTarget[this._property]);
  46018. }
  46019. else {
  46020. check = this.value === this._effectiveTarget[this._property];
  46021. }
  46022. return this.operator === ValueCondition.IsEqual ? check : !check;
  46023. }
  46024. return false;
  46025. };
  46026. ValueCondition.prototype.serialize = function () {
  46027. return this._serialize({
  46028. name: "ValueCondition",
  46029. properties: [
  46030. BABYLON.Action._GetTargetProperty(this._target),
  46031. { name: "propertyPath", value: this.propertyPath },
  46032. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46033. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  46034. ]
  46035. });
  46036. };
  46037. ValueCondition.GetOperatorName = function (operator) {
  46038. switch (operator) {
  46039. case ValueCondition._IsEqual: return "IsEqual";
  46040. case ValueCondition._IsDifferent: return "IsDifferent";
  46041. case ValueCondition._IsGreater: return "IsGreater";
  46042. case ValueCondition._IsLesser: return "IsLesser";
  46043. default: return "";
  46044. }
  46045. };
  46046. // Statics
  46047. ValueCondition._IsEqual = 0;
  46048. ValueCondition._IsDifferent = 1;
  46049. ValueCondition._IsGreater = 2;
  46050. ValueCondition._IsLesser = 3;
  46051. return ValueCondition;
  46052. }(Condition));
  46053. BABYLON.ValueCondition = ValueCondition;
  46054. var PredicateCondition = (function (_super) {
  46055. __extends(PredicateCondition, _super);
  46056. function PredicateCondition(actionManager, predicate) {
  46057. var _this = _super.call(this, actionManager) || this;
  46058. _this.predicate = predicate;
  46059. return _this;
  46060. }
  46061. PredicateCondition.prototype.isValid = function () {
  46062. return this.predicate();
  46063. };
  46064. return PredicateCondition;
  46065. }(Condition));
  46066. BABYLON.PredicateCondition = PredicateCondition;
  46067. var StateCondition = (function (_super) {
  46068. __extends(StateCondition, _super);
  46069. function StateCondition(actionManager, target, value) {
  46070. var _this = _super.call(this, actionManager) || this;
  46071. _this.value = value;
  46072. _this._target = target;
  46073. return _this;
  46074. }
  46075. // Methods
  46076. StateCondition.prototype.isValid = function () {
  46077. return this._target.state === this.value;
  46078. };
  46079. StateCondition.prototype.serialize = function () {
  46080. return this._serialize({
  46081. name: "StateCondition",
  46082. properties: [
  46083. BABYLON.Action._GetTargetProperty(this._target),
  46084. { name: "value", value: this.value }
  46085. ]
  46086. });
  46087. };
  46088. return StateCondition;
  46089. }(Condition));
  46090. BABYLON.StateCondition = StateCondition;
  46091. })(BABYLON || (BABYLON = {}));
  46092. //# sourceMappingURL=babylon.condition.js.map
  46093. var BABYLON;
  46094. (function (BABYLON) {
  46095. var Action = (function () {
  46096. function Action(triggerOptions, condition) {
  46097. this.triggerOptions = triggerOptions;
  46098. if (triggerOptions.parameter) {
  46099. this.trigger = triggerOptions.trigger;
  46100. this._triggerParameter = triggerOptions.parameter;
  46101. }
  46102. else {
  46103. this.trigger = triggerOptions;
  46104. }
  46105. this._nextActiveAction = this;
  46106. this._condition = condition;
  46107. }
  46108. // Methods
  46109. Action.prototype._prepare = function () {
  46110. };
  46111. Action.prototype.getTriggerParameter = function () {
  46112. return this._triggerParameter;
  46113. };
  46114. Action.prototype._executeCurrent = function (evt) {
  46115. if (this._nextActiveAction._condition) {
  46116. var condition = this._nextActiveAction._condition;
  46117. var currentRenderId = this._actionManager.getScene().getRenderId();
  46118. // We cache the current evaluation for the current frame
  46119. if (condition._evaluationId === currentRenderId) {
  46120. if (!condition._currentResult) {
  46121. return;
  46122. }
  46123. }
  46124. else {
  46125. condition._evaluationId = currentRenderId;
  46126. if (!condition.isValid()) {
  46127. condition._currentResult = false;
  46128. return;
  46129. }
  46130. condition._currentResult = true;
  46131. }
  46132. }
  46133. this._nextActiveAction.execute(evt);
  46134. this.skipToNextActiveAction();
  46135. };
  46136. Action.prototype.execute = function (evt) {
  46137. };
  46138. Action.prototype.skipToNextActiveAction = function () {
  46139. if (this._nextActiveAction._child) {
  46140. if (!this._nextActiveAction._child._actionManager) {
  46141. this._nextActiveAction._child._actionManager = this._actionManager;
  46142. }
  46143. this._nextActiveAction = this._nextActiveAction._child;
  46144. }
  46145. else {
  46146. this._nextActiveAction = this;
  46147. }
  46148. };
  46149. Action.prototype.then = function (action) {
  46150. this._child = action;
  46151. action._actionManager = this._actionManager;
  46152. action._prepare();
  46153. return action;
  46154. };
  46155. Action.prototype._getProperty = function (propertyPath) {
  46156. return this._actionManager._getProperty(propertyPath);
  46157. };
  46158. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  46159. return this._actionManager._getEffectiveTarget(target, propertyPath);
  46160. };
  46161. Action.prototype.serialize = function (parent) {
  46162. };
  46163. // Called by BABYLON.Action objects in serialize(...). Internal use
  46164. Action.prototype._serialize = function (serializedAction, parent) {
  46165. var serializationObject = {
  46166. type: 1,
  46167. children: [],
  46168. name: serializedAction.name,
  46169. properties: serializedAction.properties || []
  46170. };
  46171. // Serialize child
  46172. if (this._child) {
  46173. this._child.serialize(serializationObject);
  46174. }
  46175. // Check if "this" has a condition
  46176. if (this._condition) {
  46177. var serializedCondition = this._condition.serialize();
  46178. serializedCondition.children.push(serializationObject);
  46179. if (parent) {
  46180. parent.children.push(serializedCondition);
  46181. }
  46182. return serializedCondition;
  46183. }
  46184. if (parent) {
  46185. parent.children.push(serializationObject);
  46186. }
  46187. return serializationObject;
  46188. };
  46189. Action._SerializeValueAsString = function (value) {
  46190. if (typeof value === "number") {
  46191. return value.toString();
  46192. }
  46193. if (typeof value === "boolean") {
  46194. return value ? "true" : "false";
  46195. }
  46196. if (value instanceof BABYLON.Vector2) {
  46197. return value.x + ", " + value.y;
  46198. }
  46199. if (value instanceof BABYLON.Vector3) {
  46200. return value.x + ", " + value.y + ", " + value.z;
  46201. }
  46202. if (value instanceof BABYLON.Color3) {
  46203. return value.r + ", " + value.g + ", " + value.b;
  46204. }
  46205. if (value instanceof BABYLON.Color4) {
  46206. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  46207. }
  46208. return value; // string
  46209. };
  46210. Action._GetTargetProperty = function (target) {
  46211. return {
  46212. name: "target",
  46213. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  46214. : target instanceof BABYLON.Light ? "LightProperties"
  46215. : target instanceof BABYLON.Camera ? "CameraProperties"
  46216. : "SceneProperties",
  46217. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  46218. };
  46219. };
  46220. return Action;
  46221. }());
  46222. BABYLON.Action = Action;
  46223. })(BABYLON || (BABYLON = {}));
  46224. //# sourceMappingURL=babylon.action.js.map
  46225. var BABYLON;
  46226. (function (BABYLON) {
  46227. /**
  46228. * ActionEvent is the event beint sent when an action is triggered.
  46229. */
  46230. var ActionEvent = (function () {
  46231. /**
  46232. * @param source The mesh or sprite that triggered the action.
  46233. * @param pointerX The X mouse cursor position at the time of the event
  46234. * @param pointerY The Y mouse cursor position at the time of the event
  46235. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  46236. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  46237. */
  46238. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  46239. this.source = source;
  46240. this.pointerX = pointerX;
  46241. this.pointerY = pointerY;
  46242. this.meshUnderPointer = meshUnderPointer;
  46243. this.sourceEvent = sourceEvent;
  46244. this.additionalData = additionalData;
  46245. }
  46246. /**
  46247. * Helper function to auto-create an ActionEvent from a source mesh.
  46248. * @param source The source mesh that triggered the event
  46249. * @param evt {Event} The original (browser) event
  46250. */
  46251. ActionEvent.CreateNew = function (source, evt, additionalData) {
  46252. var scene = source.getScene();
  46253. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  46254. };
  46255. /**
  46256. * Helper function to auto-create an ActionEvent from a source mesh.
  46257. * @param source The source sprite that triggered the event
  46258. * @param scene Scene associated with the sprite
  46259. * @param evt {Event} The original (browser) event
  46260. */
  46261. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  46262. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  46263. };
  46264. /**
  46265. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  46266. * @param scene the scene where the event occurred
  46267. * @param evt {Event} The original (browser) event
  46268. */
  46269. ActionEvent.CreateNewFromScene = function (scene, evt) {
  46270. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  46271. };
  46272. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  46273. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  46274. };
  46275. return ActionEvent;
  46276. }());
  46277. BABYLON.ActionEvent = ActionEvent;
  46278. /**
  46279. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  46280. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  46281. */
  46282. var ActionManager = (function () {
  46283. function ActionManager(scene) {
  46284. // Members
  46285. this.actions = new Array();
  46286. this.hoverCursor = '';
  46287. this._scene = scene;
  46288. scene._actionManagers.push(this);
  46289. }
  46290. Object.defineProperty(ActionManager, "NothingTrigger", {
  46291. get: function () {
  46292. return ActionManager._NothingTrigger;
  46293. },
  46294. enumerable: true,
  46295. configurable: true
  46296. });
  46297. Object.defineProperty(ActionManager, "OnPickTrigger", {
  46298. get: function () {
  46299. return ActionManager._OnPickTrigger;
  46300. },
  46301. enumerable: true,
  46302. configurable: true
  46303. });
  46304. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  46305. get: function () {
  46306. return ActionManager._OnLeftPickTrigger;
  46307. },
  46308. enumerable: true,
  46309. configurable: true
  46310. });
  46311. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  46312. get: function () {
  46313. return ActionManager._OnRightPickTrigger;
  46314. },
  46315. enumerable: true,
  46316. configurable: true
  46317. });
  46318. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  46319. get: function () {
  46320. return ActionManager._OnCenterPickTrigger;
  46321. },
  46322. enumerable: true,
  46323. configurable: true
  46324. });
  46325. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  46326. get: function () {
  46327. return ActionManager._OnPickDownTrigger;
  46328. },
  46329. enumerable: true,
  46330. configurable: true
  46331. });
  46332. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  46333. get: function () {
  46334. return ActionManager._OnDoublePickTrigger;
  46335. },
  46336. enumerable: true,
  46337. configurable: true
  46338. });
  46339. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  46340. get: function () {
  46341. return ActionManager._OnPickUpTrigger;
  46342. },
  46343. enumerable: true,
  46344. configurable: true
  46345. });
  46346. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  46347. /// This trigger will only be raised if you also declared a OnPickDown
  46348. get: function () {
  46349. return ActionManager._OnPickOutTrigger;
  46350. },
  46351. enumerable: true,
  46352. configurable: true
  46353. });
  46354. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  46355. get: function () {
  46356. return ActionManager._OnLongPressTrigger;
  46357. },
  46358. enumerable: true,
  46359. configurable: true
  46360. });
  46361. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  46362. get: function () {
  46363. return ActionManager._OnPointerOverTrigger;
  46364. },
  46365. enumerable: true,
  46366. configurable: true
  46367. });
  46368. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  46369. get: function () {
  46370. return ActionManager._OnPointerOutTrigger;
  46371. },
  46372. enumerable: true,
  46373. configurable: true
  46374. });
  46375. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  46376. get: function () {
  46377. return ActionManager._OnEveryFrameTrigger;
  46378. },
  46379. enumerable: true,
  46380. configurable: true
  46381. });
  46382. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  46383. get: function () {
  46384. return ActionManager._OnIntersectionEnterTrigger;
  46385. },
  46386. enumerable: true,
  46387. configurable: true
  46388. });
  46389. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  46390. get: function () {
  46391. return ActionManager._OnIntersectionExitTrigger;
  46392. },
  46393. enumerable: true,
  46394. configurable: true
  46395. });
  46396. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  46397. get: function () {
  46398. return ActionManager._OnKeyDownTrigger;
  46399. },
  46400. enumerable: true,
  46401. configurable: true
  46402. });
  46403. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  46404. get: function () {
  46405. return ActionManager._OnKeyUpTrigger;
  46406. },
  46407. enumerable: true,
  46408. configurable: true
  46409. });
  46410. // Methods
  46411. ActionManager.prototype.dispose = function () {
  46412. var index = this._scene._actionManagers.indexOf(this);
  46413. for (var i = 0; i < this.actions.length; i++) {
  46414. var action = this.actions[i];
  46415. ActionManager.Triggers[action.trigger]--;
  46416. if (ActionManager.Triggers[action.trigger] === 0) {
  46417. delete ActionManager.Triggers[action.trigger];
  46418. }
  46419. }
  46420. if (index > -1) {
  46421. this._scene._actionManagers.splice(index, 1);
  46422. }
  46423. };
  46424. ActionManager.prototype.getScene = function () {
  46425. return this._scene;
  46426. };
  46427. /**
  46428. * Does this action manager handles actions of any of the given triggers
  46429. * @param {number[]} triggers - the triggers to be tested
  46430. * @return {boolean} whether one (or more) of the triggers is handeled
  46431. */
  46432. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  46433. for (var index = 0; index < this.actions.length; index++) {
  46434. var action = this.actions[index];
  46435. if (triggers.indexOf(action.trigger) > -1) {
  46436. return true;
  46437. }
  46438. }
  46439. return false;
  46440. };
  46441. /**
  46442. * Does this action manager handles actions of a given trigger
  46443. * @param {number} trigger - the trigger to be tested
  46444. * @return {boolean} whether the trigger is handeled
  46445. */
  46446. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  46447. for (var index = 0; index < this.actions.length; index++) {
  46448. var action = this.actions[index];
  46449. if (action.trigger === trigger) {
  46450. return true;
  46451. }
  46452. }
  46453. return false;
  46454. };
  46455. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  46456. /**
  46457. * Does this action manager has pointer triggers
  46458. * @return {boolean} whether or not it has pointer triggers
  46459. */
  46460. get: function () {
  46461. for (var index = 0; index < this.actions.length; index++) {
  46462. var action = this.actions[index];
  46463. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  46464. return true;
  46465. }
  46466. }
  46467. return false;
  46468. },
  46469. enumerable: true,
  46470. configurable: true
  46471. });
  46472. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  46473. /**
  46474. * Does this action manager has pick triggers
  46475. * @return {boolean} whether or not it has pick triggers
  46476. */
  46477. get: function () {
  46478. for (var index = 0; index < this.actions.length; index++) {
  46479. var action = this.actions[index];
  46480. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  46481. return true;
  46482. }
  46483. }
  46484. return false;
  46485. },
  46486. enumerable: true,
  46487. configurable: true
  46488. });
  46489. Object.defineProperty(ActionManager, "HasTriggers", {
  46490. /**
  46491. * Does exist one action manager with at least one trigger
  46492. * @return {boolean} whether or not it exists one action manager with one trigger
  46493. **/
  46494. get: function () {
  46495. for (var t in ActionManager.Triggers) {
  46496. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46497. return true;
  46498. }
  46499. }
  46500. return false;
  46501. },
  46502. enumerable: true,
  46503. configurable: true
  46504. });
  46505. Object.defineProperty(ActionManager, "HasPickTriggers", {
  46506. /**
  46507. * Does exist one action manager with at least one pick trigger
  46508. * @return {boolean} whether or not it exists one action manager with one pick trigger
  46509. **/
  46510. get: function () {
  46511. for (var t in ActionManager.Triggers) {
  46512. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46513. var t_int = parseInt(t);
  46514. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  46515. return true;
  46516. }
  46517. }
  46518. }
  46519. return false;
  46520. },
  46521. enumerable: true,
  46522. configurable: true
  46523. });
  46524. /**
  46525. * Does exist one action manager that handles actions of a given trigger
  46526. * @param {number} trigger - the trigger to be tested
  46527. * @return {boolean} whether the trigger is handeled by at least one action manager
  46528. **/
  46529. ActionManager.HasSpecificTrigger = function (trigger) {
  46530. for (var t in ActionManager.Triggers) {
  46531. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46532. var t_int = parseInt(t);
  46533. if (t_int === trigger) {
  46534. return true;
  46535. }
  46536. }
  46537. }
  46538. return false;
  46539. };
  46540. /**
  46541. * Registers an action to this action manager
  46542. * @param {BABYLON.Action} action - the action to be registered
  46543. * @return {BABYLON.Action} the action amended (prepared) after registration
  46544. */
  46545. ActionManager.prototype.registerAction = function (action) {
  46546. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  46547. if (this.getScene().actionManager !== this) {
  46548. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  46549. return null;
  46550. }
  46551. }
  46552. this.actions.push(action);
  46553. if (ActionManager.Triggers[action.trigger]) {
  46554. ActionManager.Triggers[action.trigger]++;
  46555. }
  46556. else {
  46557. ActionManager.Triggers[action.trigger] = 1;
  46558. }
  46559. action._actionManager = this;
  46560. action._prepare();
  46561. return action;
  46562. };
  46563. /**
  46564. * Process a specific trigger
  46565. * @param {number} trigger - the trigger to process
  46566. * @param evt {BABYLON.ActionEvent} the event details to be processed
  46567. */
  46568. ActionManager.prototype.processTrigger = function (trigger, evt) {
  46569. for (var index = 0; index < this.actions.length; index++) {
  46570. var action = this.actions[index];
  46571. if (action.trigger === trigger) {
  46572. if (trigger === ActionManager.OnKeyUpTrigger
  46573. || trigger === ActionManager.OnKeyDownTrigger) {
  46574. var parameter = action.getTriggerParameter();
  46575. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  46576. if (!parameter.toLowerCase) {
  46577. continue;
  46578. }
  46579. var lowerCase = parameter.toLowerCase();
  46580. if (lowerCase !== evt.sourceEvent.key) {
  46581. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  46582. var actualkey = String.fromCharCode(unicode).toLowerCase();
  46583. if (actualkey !== lowerCase) {
  46584. continue;
  46585. }
  46586. }
  46587. }
  46588. }
  46589. action._executeCurrent(evt);
  46590. }
  46591. }
  46592. };
  46593. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  46594. var properties = propertyPath.split(".");
  46595. for (var index = 0; index < properties.length - 1; index++) {
  46596. target = target[properties[index]];
  46597. }
  46598. return target;
  46599. };
  46600. ActionManager.prototype._getProperty = function (propertyPath) {
  46601. var properties = propertyPath.split(".");
  46602. return properties[properties.length - 1];
  46603. };
  46604. ActionManager.prototype.serialize = function (name) {
  46605. var root = {
  46606. children: [],
  46607. name: name,
  46608. type: 3,
  46609. properties: [] // Empty for root but required
  46610. };
  46611. for (var i = 0; i < this.actions.length; i++) {
  46612. var triggerObject = {
  46613. type: 0,
  46614. children: [],
  46615. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  46616. properties: []
  46617. };
  46618. var triggerOptions = this.actions[i].triggerOptions;
  46619. if (triggerOptions && typeof triggerOptions !== "number") {
  46620. if (triggerOptions.parameter instanceof BABYLON.Node) {
  46621. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  46622. }
  46623. else {
  46624. var parameter = {};
  46625. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  46626. if (triggerOptions.parameter.mesh) {
  46627. parameter._meshId = triggerOptions.parameter.mesh.id;
  46628. }
  46629. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  46630. }
  46631. }
  46632. // Serialize child action, recursively
  46633. this.actions[i].serialize(triggerObject);
  46634. // Add serialized trigger
  46635. root.children.push(triggerObject);
  46636. }
  46637. return root;
  46638. };
  46639. ActionManager.Parse = function (parsedActions, object, scene) {
  46640. var actionManager = new BABYLON.ActionManager(scene);
  46641. if (object === null)
  46642. scene.actionManager = actionManager;
  46643. else
  46644. object.actionManager = actionManager;
  46645. // instanciate a new object
  46646. var instanciate = function (name, params) {
  46647. var newInstance = Object.create(BABYLON[name].prototype);
  46648. newInstance.constructor.apply(newInstance, params);
  46649. return newInstance;
  46650. };
  46651. var parseParameter = function (name, value, target, propertyPath) {
  46652. if (propertyPath === null) {
  46653. // String, boolean or float
  46654. var floatValue = parseFloat(value);
  46655. if (value === "true" || value === "false")
  46656. return value === "true";
  46657. else
  46658. return isNaN(floatValue) ? value : floatValue;
  46659. }
  46660. var effectiveTarget = propertyPath.split(".");
  46661. var values = value.split(",");
  46662. // Get effective Target
  46663. for (var i = 0; i < effectiveTarget.length; i++) {
  46664. target = target[effectiveTarget[i]];
  46665. }
  46666. // Return appropriate value with its type
  46667. if (typeof (target) === "boolean")
  46668. return values[0] === "true";
  46669. if (typeof (target) === "string")
  46670. return values[0];
  46671. // Parameters with multiple values such as Vector3 etc.
  46672. var split = new Array();
  46673. for (var i = 0; i < values.length; i++)
  46674. split.push(parseFloat(values[i]));
  46675. if (target instanceof BABYLON.Vector3)
  46676. return BABYLON.Vector3.FromArray(split);
  46677. if (target instanceof BABYLON.Vector4)
  46678. return BABYLON.Vector4.FromArray(split);
  46679. if (target instanceof BABYLON.Color3)
  46680. return BABYLON.Color3.FromArray(split);
  46681. if (target instanceof BABYLON.Color4)
  46682. return BABYLON.Color4.FromArray(split);
  46683. return parseFloat(values[0]);
  46684. };
  46685. // traverse graph per trigger
  46686. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  46687. if (combineArray === void 0) { combineArray = null; }
  46688. if (parsedAction.detached)
  46689. return;
  46690. var parameters = new Array();
  46691. var target = null;
  46692. var propertyPath = null;
  46693. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  46694. // Parameters
  46695. if (parsedAction.type === 2)
  46696. parameters.push(actionManager);
  46697. else
  46698. parameters.push(trigger);
  46699. if (combine) {
  46700. var actions = new Array();
  46701. for (var j = 0; j < parsedAction.combine.length; j++) {
  46702. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  46703. }
  46704. parameters.push(actions);
  46705. }
  46706. else {
  46707. for (var i = 0; i < parsedAction.properties.length; i++) {
  46708. var value = parsedAction.properties[i].value;
  46709. var name = parsedAction.properties[i].name;
  46710. var targetType = parsedAction.properties[i].targetType;
  46711. if (name === "target")
  46712. if (targetType !== null && targetType === "SceneProperties")
  46713. value = target = scene;
  46714. else
  46715. value = target = scene.getNodeByName(value);
  46716. else if (name === "parent")
  46717. value = scene.getNodeByName(value);
  46718. else if (name === "sound")
  46719. value = scene.getSoundByName(value);
  46720. else if (name !== "propertyPath") {
  46721. if (parsedAction.type === 2 && name === "operator")
  46722. value = BABYLON.ValueCondition[value];
  46723. else
  46724. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  46725. }
  46726. else {
  46727. propertyPath = value;
  46728. }
  46729. parameters.push(value);
  46730. }
  46731. }
  46732. if (combineArray === null) {
  46733. parameters.push(condition);
  46734. }
  46735. else {
  46736. parameters.push(null);
  46737. }
  46738. // If interpolate value action
  46739. if (parsedAction.name === "InterpolateValueAction") {
  46740. var param = parameters[parameters.length - 2];
  46741. parameters[parameters.length - 1] = param;
  46742. parameters[parameters.length - 2] = condition;
  46743. }
  46744. // Action or condition(s) and not CombineAction
  46745. var newAction = instanciate(parsedAction.name, parameters);
  46746. if (newAction instanceof BABYLON.Condition && condition !== null) {
  46747. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  46748. if (action)
  46749. action.then(nothing);
  46750. else
  46751. actionManager.registerAction(nothing);
  46752. action = nothing;
  46753. }
  46754. if (combineArray === null) {
  46755. if (newAction instanceof BABYLON.Condition) {
  46756. condition = newAction;
  46757. newAction = action;
  46758. }
  46759. else {
  46760. condition = null;
  46761. if (action)
  46762. action.then(newAction);
  46763. else
  46764. actionManager.registerAction(newAction);
  46765. }
  46766. }
  46767. else {
  46768. combineArray.push(newAction);
  46769. }
  46770. for (var i = 0; i < parsedAction.children.length; i++)
  46771. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  46772. };
  46773. // triggers
  46774. for (var i = 0; i < parsedActions.children.length; i++) {
  46775. var triggerParams;
  46776. var trigger = parsedActions.children[i];
  46777. if (trigger.properties.length > 0) {
  46778. var param = trigger.properties[0].value;
  46779. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  46780. if (value._meshId) {
  46781. value.mesh = scene.getMeshByID(value._meshId);
  46782. }
  46783. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  46784. }
  46785. else
  46786. triggerParams = BABYLON.ActionManager[trigger.name];
  46787. for (var j = 0; j < trigger.children.length; j++) {
  46788. if (!trigger.detached)
  46789. traverse(trigger.children[j], triggerParams, null, null);
  46790. }
  46791. }
  46792. };
  46793. ActionManager.GetTriggerName = function (trigger) {
  46794. switch (trigger) {
  46795. case 0: return "NothingTrigger";
  46796. case 1: return "OnPickTrigger";
  46797. case 2: return "OnLeftPickTrigger";
  46798. case 3: return "OnRightPickTrigger";
  46799. case 4: return "OnCenterPickTrigger";
  46800. case 5: return "OnPickDownTrigger";
  46801. case 6: return "OnPickUpTrigger";
  46802. case 7: return "OnLongPressTrigger";
  46803. case 8: return "OnPointerOverTrigger";
  46804. case 9: return "OnPointerOutTrigger";
  46805. case 10: return "OnEveryFrameTrigger";
  46806. case 11: return "OnIntersectionEnterTrigger";
  46807. case 12: return "OnIntersectionExitTrigger";
  46808. case 13: return "OnKeyDownTrigger";
  46809. case 14: return "OnKeyUpTrigger";
  46810. case 15: return "OnPickOutTrigger";
  46811. default: return "";
  46812. }
  46813. };
  46814. // Statics
  46815. ActionManager._NothingTrigger = 0;
  46816. ActionManager._OnPickTrigger = 1;
  46817. ActionManager._OnLeftPickTrigger = 2;
  46818. ActionManager._OnRightPickTrigger = 3;
  46819. ActionManager._OnCenterPickTrigger = 4;
  46820. ActionManager._OnPickDownTrigger = 5;
  46821. ActionManager._OnDoublePickTrigger = 6;
  46822. ActionManager._OnPickUpTrigger = 7;
  46823. ActionManager._OnLongPressTrigger = 8;
  46824. ActionManager._OnPointerOverTrigger = 9;
  46825. ActionManager._OnPointerOutTrigger = 10;
  46826. ActionManager._OnEveryFrameTrigger = 11;
  46827. ActionManager._OnIntersectionEnterTrigger = 12;
  46828. ActionManager._OnIntersectionExitTrigger = 13;
  46829. ActionManager._OnKeyDownTrigger = 14;
  46830. ActionManager._OnKeyUpTrigger = 15;
  46831. ActionManager._OnPickOutTrigger = 16;
  46832. ActionManager.Triggers = {};
  46833. return ActionManager;
  46834. }());
  46835. BABYLON.ActionManager = ActionManager;
  46836. })(BABYLON || (BABYLON = {}));
  46837. //# sourceMappingURL=babylon.actionManager.js.map
  46838. var BABYLON;
  46839. (function (BABYLON) {
  46840. var InterpolateValueAction = (function (_super) {
  46841. __extends(InterpolateValueAction, _super);
  46842. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  46843. if (duration === void 0) { duration = 1000; }
  46844. var _this = _super.call(this, triggerOptions, condition) || this;
  46845. _this.propertyPath = propertyPath;
  46846. _this.value = value;
  46847. _this.duration = duration;
  46848. _this.stopOtherAnimations = stopOtherAnimations;
  46849. _this.onInterpolationDone = onInterpolationDone;
  46850. _this._target = _this._effectiveTarget = target;
  46851. return _this;
  46852. }
  46853. InterpolateValueAction.prototype._prepare = function () {
  46854. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46855. this._property = this._getProperty(this.propertyPath);
  46856. };
  46857. InterpolateValueAction.prototype.execute = function () {
  46858. var scene = this._actionManager.getScene();
  46859. var keys = [
  46860. {
  46861. frame: 0,
  46862. value: this._effectiveTarget[this._property]
  46863. }, {
  46864. frame: 100,
  46865. value: this.value
  46866. }
  46867. ];
  46868. var dataType;
  46869. if (typeof this.value === "number") {
  46870. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  46871. }
  46872. else if (this.value instanceof BABYLON.Color3) {
  46873. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  46874. }
  46875. else if (this.value instanceof BABYLON.Vector3) {
  46876. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  46877. }
  46878. else if (this.value instanceof BABYLON.Matrix) {
  46879. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  46880. }
  46881. else if (this.value instanceof BABYLON.Quaternion) {
  46882. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  46883. }
  46884. else {
  46885. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  46886. return;
  46887. }
  46888. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  46889. animation.setKeys(keys);
  46890. if (this.stopOtherAnimations) {
  46891. scene.stopAnimation(this._effectiveTarget);
  46892. }
  46893. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  46894. };
  46895. InterpolateValueAction.prototype.serialize = function (parent) {
  46896. return _super.prototype._serialize.call(this, {
  46897. name: "InterpolateValueAction",
  46898. properties: [
  46899. BABYLON.Action._GetTargetProperty(this._target),
  46900. { name: "propertyPath", value: this.propertyPath },
  46901. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46902. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  46903. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  46904. ]
  46905. }, parent);
  46906. };
  46907. return InterpolateValueAction;
  46908. }(BABYLON.Action));
  46909. BABYLON.InterpolateValueAction = InterpolateValueAction;
  46910. })(BABYLON || (BABYLON = {}));
  46911. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  46912. var BABYLON;
  46913. (function (BABYLON) {
  46914. var SwitchBooleanAction = (function (_super) {
  46915. __extends(SwitchBooleanAction, _super);
  46916. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  46917. var _this = _super.call(this, triggerOptions, condition) || this;
  46918. _this.propertyPath = propertyPath;
  46919. _this._target = _this._effectiveTarget = target;
  46920. return _this;
  46921. }
  46922. SwitchBooleanAction.prototype._prepare = function () {
  46923. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46924. this._property = this._getProperty(this.propertyPath);
  46925. };
  46926. SwitchBooleanAction.prototype.execute = function () {
  46927. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  46928. };
  46929. SwitchBooleanAction.prototype.serialize = function (parent) {
  46930. return _super.prototype._serialize.call(this, {
  46931. name: "SwitchBooleanAction",
  46932. properties: [
  46933. BABYLON.Action._GetTargetProperty(this._target),
  46934. { name: "propertyPath", value: this.propertyPath }
  46935. ]
  46936. }, parent);
  46937. };
  46938. return SwitchBooleanAction;
  46939. }(BABYLON.Action));
  46940. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  46941. var SetStateAction = (function (_super) {
  46942. __extends(SetStateAction, _super);
  46943. function SetStateAction(triggerOptions, target, value, condition) {
  46944. var _this = _super.call(this, triggerOptions, condition) || this;
  46945. _this.value = value;
  46946. _this._target = target;
  46947. return _this;
  46948. }
  46949. SetStateAction.prototype.execute = function () {
  46950. this._target.state = this.value;
  46951. };
  46952. SetStateAction.prototype.serialize = function (parent) {
  46953. return _super.prototype._serialize.call(this, {
  46954. name: "SetStateAction",
  46955. properties: [
  46956. BABYLON.Action._GetTargetProperty(this._target),
  46957. { name: "value", value: this.value }
  46958. ]
  46959. }, parent);
  46960. };
  46961. return SetStateAction;
  46962. }(BABYLON.Action));
  46963. BABYLON.SetStateAction = SetStateAction;
  46964. var SetValueAction = (function (_super) {
  46965. __extends(SetValueAction, _super);
  46966. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  46967. var _this = _super.call(this, triggerOptions, condition) || this;
  46968. _this.propertyPath = propertyPath;
  46969. _this.value = value;
  46970. _this._target = _this._effectiveTarget = target;
  46971. return _this;
  46972. }
  46973. SetValueAction.prototype._prepare = function () {
  46974. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46975. this._property = this._getProperty(this.propertyPath);
  46976. };
  46977. SetValueAction.prototype.execute = function () {
  46978. this._effectiveTarget[this._property] = this.value;
  46979. if (this._target.markAsDirty) {
  46980. this._target.markAsDirty(this._property);
  46981. }
  46982. };
  46983. SetValueAction.prototype.serialize = function (parent) {
  46984. return _super.prototype._serialize.call(this, {
  46985. name: "SetValueAction",
  46986. properties: [
  46987. BABYLON.Action._GetTargetProperty(this._target),
  46988. { name: "propertyPath", value: this.propertyPath },
  46989. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46990. ]
  46991. }, parent);
  46992. };
  46993. return SetValueAction;
  46994. }(BABYLON.Action));
  46995. BABYLON.SetValueAction = SetValueAction;
  46996. var IncrementValueAction = (function (_super) {
  46997. __extends(IncrementValueAction, _super);
  46998. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  46999. var _this = _super.call(this, triggerOptions, condition) || this;
  47000. _this.propertyPath = propertyPath;
  47001. _this.value = value;
  47002. _this._target = _this._effectiveTarget = target;
  47003. return _this;
  47004. }
  47005. IncrementValueAction.prototype._prepare = function () {
  47006. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47007. this._property = this._getProperty(this.propertyPath);
  47008. if (typeof this._effectiveTarget[this._property] !== "number") {
  47009. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  47010. }
  47011. };
  47012. IncrementValueAction.prototype.execute = function () {
  47013. this._effectiveTarget[this._property] += this.value;
  47014. if (this._target.markAsDirty) {
  47015. this._target.markAsDirty(this._property);
  47016. }
  47017. };
  47018. IncrementValueAction.prototype.serialize = function (parent) {
  47019. return _super.prototype._serialize.call(this, {
  47020. name: "IncrementValueAction",
  47021. properties: [
  47022. BABYLON.Action._GetTargetProperty(this._target),
  47023. { name: "propertyPath", value: this.propertyPath },
  47024. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  47025. ]
  47026. }, parent);
  47027. };
  47028. return IncrementValueAction;
  47029. }(BABYLON.Action));
  47030. BABYLON.IncrementValueAction = IncrementValueAction;
  47031. var PlayAnimationAction = (function (_super) {
  47032. __extends(PlayAnimationAction, _super);
  47033. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  47034. var _this = _super.call(this, triggerOptions, condition) || this;
  47035. _this.from = from;
  47036. _this.to = to;
  47037. _this.loop = loop;
  47038. _this._target = target;
  47039. return _this;
  47040. }
  47041. PlayAnimationAction.prototype._prepare = function () {
  47042. };
  47043. PlayAnimationAction.prototype.execute = function () {
  47044. var scene = this._actionManager.getScene();
  47045. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  47046. };
  47047. PlayAnimationAction.prototype.serialize = function (parent) {
  47048. return _super.prototype._serialize.call(this, {
  47049. name: "PlayAnimationAction",
  47050. properties: [
  47051. BABYLON.Action._GetTargetProperty(this._target),
  47052. { name: "from", value: String(this.from) },
  47053. { name: "to", value: String(this.to) },
  47054. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  47055. ]
  47056. }, parent);
  47057. };
  47058. return PlayAnimationAction;
  47059. }(BABYLON.Action));
  47060. BABYLON.PlayAnimationAction = PlayAnimationAction;
  47061. var StopAnimationAction = (function (_super) {
  47062. __extends(StopAnimationAction, _super);
  47063. function StopAnimationAction(triggerOptions, target, condition) {
  47064. var _this = _super.call(this, triggerOptions, condition) || this;
  47065. _this._target = target;
  47066. return _this;
  47067. }
  47068. StopAnimationAction.prototype._prepare = function () {
  47069. };
  47070. StopAnimationAction.prototype.execute = function () {
  47071. var scene = this._actionManager.getScene();
  47072. scene.stopAnimation(this._target);
  47073. };
  47074. StopAnimationAction.prototype.serialize = function (parent) {
  47075. return _super.prototype._serialize.call(this, {
  47076. name: "StopAnimationAction",
  47077. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  47078. }, parent);
  47079. };
  47080. return StopAnimationAction;
  47081. }(BABYLON.Action));
  47082. BABYLON.StopAnimationAction = StopAnimationAction;
  47083. var DoNothingAction = (function (_super) {
  47084. __extends(DoNothingAction, _super);
  47085. function DoNothingAction(triggerOptions, condition) {
  47086. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  47087. return _super.call(this, triggerOptions, condition) || this;
  47088. }
  47089. DoNothingAction.prototype.execute = function () {
  47090. };
  47091. DoNothingAction.prototype.serialize = function (parent) {
  47092. return _super.prototype._serialize.call(this, {
  47093. name: "DoNothingAction",
  47094. properties: []
  47095. }, parent);
  47096. };
  47097. return DoNothingAction;
  47098. }(BABYLON.Action));
  47099. BABYLON.DoNothingAction = DoNothingAction;
  47100. var CombineAction = (function (_super) {
  47101. __extends(CombineAction, _super);
  47102. function CombineAction(triggerOptions, children, condition) {
  47103. var _this = _super.call(this, triggerOptions, condition) || this;
  47104. _this.children = children;
  47105. return _this;
  47106. }
  47107. CombineAction.prototype._prepare = function () {
  47108. for (var index = 0; index < this.children.length; index++) {
  47109. this.children[index]._actionManager = this._actionManager;
  47110. this.children[index]._prepare();
  47111. }
  47112. };
  47113. CombineAction.prototype.execute = function (evt) {
  47114. for (var index = 0; index < this.children.length; index++) {
  47115. this.children[index].execute(evt);
  47116. }
  47117. };
  47118. CombineAction.prototype.serialize = function (parent) {
  47119. var serializationObject = _super.prototype._serialize.call(this, {
  47120. name: "CombineAction",
  47121. properties: [],
  47122. combine: []
  47123. }, parent);
  47124. for (var i = 0; i < this.children.length; i++) {
  47125. serializationObject.combine.push(this.children[i].serialize(null));
  47126. }
  47127. return serializationObject;
  47128. };
  47129. return CombineAction;
  47130. }(BABYLON.Action));
  47131. BABYLON.CombineAction = CombineAction;
  47132. var ExecuteCodeAction = (function (_super) {
  47133. __extends(ExecuteCodeAction, _super);
  47134. function ExecuteCodeAction(triggerOptions, func, condition) {
  47135. var _this = _super.call(this, triggerOptions, condition) || this;
  47136. _this.func = func;
  47137. return _this;
  47138. }
  47139. ExecuteCodeAction.prototype.execute = function (evt) {
  47140. this.func(evt);
  47141. };
  47142. return ExecuteCodeAction;
  47143. }(BABYLON.Action));
  47144. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  47145. var SetParentAction = (function (_super) {
  47146. __extends(SetParentAction, _super);
  47147. function SetParentAction(triggerOptions, target, parent, condition) {
  47148. var _this = _super.call(this, triggerOptions, condition) || this;
  47149. _this._target = target;
  47150. _this._parent = parent;
  47151. return _this;
  47152. }
  47153. SetParentAction.prototype._prepare = function () {
  47154. };
  47155. SetParentAction.prototype.execute = function () {
  47156. if (this._target.parent === this._parent) {
  47157. return;
  47158. }
  47159. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  47160. invertParentWorldMatrix.invert();
  47161. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  47162. this._target.parent = this._parent;
  47163. };
  47164. SetParentAction.prototype.serialize = function (parent) {
  47165. return _super.prototype._serialize.call(this, {
  47166. name: "SetParentAction",
  47167. properties: [
  47168. BABYLON.Action._GetTargetProperty(this._target),
  47169. BABYLON.Action._GetTargetProperty(this._parent),
  47170. ]
  47171. }, parent);
  47172. };
  47173. return SetParentAction;
  47174. }(BABYLON.Action));
  47175. BABYLON.SetParentAction = SetParentAction;
  47176. var PlaySoundAction = (function (_super) {
  47177. __extends(PlaySoundAction, _super);
  47178. function PlaySoundAction(triggerOptions, sound, condition) {
  47179. var _this = _super.call(this, triggerOptions, condition) || this;
  47180. _this._sound = sound;
  47181. return _this;
  47182. }
  47183. PlaySoundAction.prototype._prepare = function () {
  47184. };
  47185. PlaySoundAction.prototype.execute = function () {
  47186. if (this._sound !== undefined)
  47187. this._sound.play();
  47188. };
  47189. PlaySoundAction.prototype.serialize = function (parent) {
  47190. return _super.prototype._serialize.call(this, {
  47191. name: "PlaySoundAction",
  47192. properties: [{ name: "sound", value: this._sound.name }]
  47193. }, parent);
  47194. };
  47195. return PlaySoundAction;
  47196. }(BABYLON.Action));
  47197. BABYLON.PlaySoundAction = PlaySoundAction;
  47198. var StopSoundAction = (function (_super) {
  47199. __extends(StopSoundAction, _super);
  47200. function StopSoundAction(triggerOptions, sound, condition) {
  47201. var _this = _super.call(this, triggerOptions, condition) || this;
  47202. _this._sound = sound;
  47203. return _this;
  47204. }
  47205. StopSoundAction.prototype._prepare = function () {
  47206. };
  47207. StopSoundAction.prototype.execute = function () {
  47208. if (this._sound !== undefined)
  47209. this._sound.stop();
  47210. };
  47211. StopSoundAction.prototype.serialize = function (parent) {
  47212. return _super.prototype._serialize.call(this, {
  47213. name: "StopSoundAction",
  47214. properties: [{ name: "sound", value: this._sound.name }]
  47215. }, parent);
  47216. };
  47217. return StopSoundAction;
  47218. }(BABYLON.Action));
  47219. BABYLON.StopSoundAction = StopSoundAction;
  47220. })(BABYLON || (BABYLON = {}));
  47221. //# sourceMappingURL=babylon.directActions.js.map
  47222. var BABYLON;
  47223. (function (BABYLON) {
  47224. var Debug;
  47225. (function (Debug) {
  47226. /**
  47227. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  47228. */
  47229. var SkeletonViewer = (function () {
  47230. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  47231. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  47232. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  47233. this.skeleton = skeleton;
  47234. this.mesh = mesh;
  47235. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  47236. this.renderingGroupId = renderingGroupId;
  47237. this.color = BABYLON.Color3.White();
  47238. this._debugLines = [];
  47239. this._isEnabled = false;
  47240. this._scene = scene;
  47241. this.update();
  47242. this._renderFunction = this.update.bind(this);
  47243. }
  47244. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  47245. get: function () {
  47246. return this._isEnabled;
  47247. },
  47248. set: function (value) {
  47249. if (this._isEnabled === value) {
  47250. return;
  47251. }
  47252. this._isEnabled = value;
  47253. if (value) {
  47254. this._scene.registerBeforeRender(this._renderFunction);
  47255. }
  47256. else {
  47257. this._scene.unregisterBeforeRender(this._renderFunction);
  47258. }
  47259. },
  47260. enumerable: true,
  47261. configurable: true
  47262. });
  47263. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  47264. if (x === void 0) { x = 0; }
  47265. if (y === void 0) { y = 0; }
  47266. if (z === void 0) { z = 0; }
  47267. var tmat = BABYLON.Tmp.Matrix[0];
  47268. var parentBone = bone.getParent();
  47269. tmat.copyFrom(bone.getLocalMatrix());
  47270. if (x !== 0 || y !== 0 || z !== 0) {
  47271. var tmat2 = BABYLON.Tmp.Matrix[1];
  47272. BABYLON.Matrix.IdentityToRef(tmat2);
  47273. tmat2.m[12] = x;
  47274. tmat2.m[13] = y;
  47275. tmat2.m[14] = z;
  47276. tmat2.multiplyToRef(tmat, tmat);
  47277. }
  47278. if (parentBone) {
  47279. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  47280. }
  47281. tmat.multiplyToRef(meshMat, tmat);
  47282. position.x = tmat.m[12];
  47283. position.y = tmat.m[13];
  47284. position.z = tmat.m[14];
  47285. };
  47286. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  47287. var len = bones.length;
  47288. var meshPos = this.mesh.position;
  47289. for (var i = 0; i < len; i++) {
  47290. var bone = bones[i];
  47291. var points = this._debugLines[i];
  47292. if (!points) {
  47293. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47294. this._debugLines[i] = points;
  47295. }
  47296. this._getBonePosition(points[0], bone, meshMat);
  47297. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  47298. points[0].subtractInPlace(meshPos);
  47299. points[1].subtractInPlace(meshPos);
  47300. }
  47301. };
  47302. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  47303. var len = bones.length;
  47304. var boneNum = 0;
  47305. var meshPos = this.mesh.position;
  47306. for (var i = len - 1; i >= 0; i--) {
  47307. var childBone = bones[i];
  47308. var parentBone = childBone.getParent();
  47309. if (!parentBone) {
  47310. continue;
  47311. }
  47312. var points = this._debugLines[boneNum];
  47313. if (!points) {
  47314. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47315. this._debugLines[boneNum] = points;
  47316. }
  47317. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  47318. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  47319. points[0].subtractInPlace(meshPos);
  47320. points[1].subtractInPlace(meshPos);
  47321. boneNum++;
  47322. }
  47323. };
  47324. SkeletonViewer.prototype.update = function () {
  47325. if (this.autoUpdateBonesMatrices) {
  47326. this.skeleton.computeAbsoluteTransforms();
  47327. }
  47328. if (this.skeleton.bones[0].length === undefined) {
  47329. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  47330. }
  47331. else {
  47332. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  47333. }
  47334. if (!this._debugMesh) {
  47335. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  47336. this._debugMesh.renderingGroupId = this.renderingGroupId;
  47337. }
  47338. else {
  47339. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  47340. }
  47341. this._debugMesh.position.copyFrom(this.mesh.position);
  47342. this._debugMesh.color = this.color;
  47343. };
  47344. SkeletonViewer.prototype.dispose = function () {
  47345. if (this._debugMesh) {
  47346. this.isEnabled = false;
  47347. this._debugMesh.dispose();
  47348. this._debugMesh = null;
  47349. }
  47350. };
  47351. return SkeletonViewer;
  47352. }());
  47353. Debug.SkeletonViewer = SkeletonViewer;
  47354. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47355. })(BABYLON || (BABYLON = {}));
  47356. //# sourceMappingURL=babylon.skeletonViewer.js.map
  47357. var BABYLON;
  47358. (function (BABYLON) {
  47359. var Debug;
  47360. (function (Debug) {
  47361. var AxesViewer = (function () {
  47362. function AxesViewer(scene, scaleLines) {
  47363. if (scaleLines === void 0) { scaleLines = 1; }
  47364. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47365. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47366. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47367. this.scaleLines = 1;
  47368. this.scaleLines = scaleLines;
  47369. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  47370. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  47371. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  47372. this._xmesh.renderingGroupId = 2;
  47373. this._ymesh.renderingGroupId = 2;
  47374. this._zmesh.renderingGroupId = 2;
  47375. this._xmesh.material.checkReadyOnlyOnce = true;
  47376. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  47377. this._ymesh.material.checkReadyOnlyOnce = true;
  47378. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  47379. this._zmesh.material.checkReadyOnlyOnce = true;
  47380. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  47381. this.scene = scene;
  47382. }
  47383. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  47384. var scaleLines = this.scaleLines;
  47385. this._xmesh.position.copyFrom(position);
  47386. this._ymesh.position.copyFrom(position);
  47387. this._zmesh.position.copyFrom(position);
  47388. var point2 = this._xline[1];
  47389. point2.x = xaxis.x * scaleLines;
  47390. point2.y = xaxis.y * scaleLines;
  47391. point2.z = xaxis.z * scaleLines;
  47392. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  47393. point2 = this._yline[1];
  47394. point2.x = yaxis.x * scaleLines;
  47395. point2.y = yaxis.y * scaleLines;
  47396. point2.z = yaxis.z * scaleLines;
  47397. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  47398. point2 = this._zline[1];
  47399. point2.x = zaxis.x * scaleLines;
  47400. point2.y = zaxis.y * scaleLines;
  47401. point2.z = zaxis.z * scaleLines;
  47402. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  47403. };
  47404. AxesViewer.prototype.dispose = function () {
  47405. if (this._xmesh) {
  47406. this._xmesh.dispose();
  47407. this._ymesh.dispose();
  47408. this._zmesh.dispose();
  47409. this._xmesh = null;
  47410. this._ymesh = null;
  47411. this._zmesh = null;
  47412. this._xline = null;
  47413. this._yline = null;
  47414. this._zline = null;
  47415. this.scene = null;
  47416. }
  47417. };
  47418. return AxesViewer;
  47419. }());
  47420. Debug.AxesViewer = AxesViewer;
  47421. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47422. })(BABYLON || (BABYLON = {}));
  47423. //# sourceMappingURL=babylon.axesViewer.js.map
  47424. var BABYLON;
  47425. (function (BABYLON) {
  47426. var Debug;
  47427. (function (Debug) {
  47428. var BoneAxesViewer = (function (_super) {
  47429. __extends(BoneAxesViewer, _super);
  47430. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  47431. if (scaleLines === void 0) { scaleLines = 1; }
  47432. var _this = _super.call(this, scene, scaleLines) || this;
  47433. _this.pos = BABYLON.Vector3.Zero();
  47434. _this.xaxis = BABYLON.Vector3.Zero();
  47435. _this.yaxis = BABYLON.Vector3.Zero();
  47436. _this.zaxis = BABYLON.Vector3.Zero();
  47437. _this.mesh = mesh;
  47438. _this.bone = bone;
  47439. return _this;
  47440. }
  47441. BoneAxesViewer.prototype.update = function () {
  47442. var bone = this.bone;
  47443. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  47444. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  47445. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  47446. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  47447. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  47448. };
  47449. BoneAxesViewer.prototype.dispose = function () {
  47450. if (this.pos) {
  47451. this.pos = null;
  47452. this.xaxis = null;
  47453. this.yaxis = null;
  47454. this.zaxis = null;
  47455. this.mesh = null;
  47456. this.bone = null;
  47457. _super.prototype.dispose.call(this);
  47458. }
  47459. };
  47460. return BoneAxesViewer;
  47461. }(Debug.AxesViewer));
  47462. Debug.BoneAxesViewer = BoneAxesViewer;
  47463. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47464. })(BABYLON || (BABYLON = {}));
  47465. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  47466. var BABYLON;
  47467. (function (BABYLON) {
  47468. var RayHelper = (function () {
  47469. function RayHelper(ray) {
  47470. this.ray = ray;
  47471. }
  47472. RayHelper.CreateAndShow = function (ray, scene, color) {
  47473. var helper = new RayHelper(ray);
  47474. helper.show(scene, color);
  47475. return helper;
  47476. };
  47477. RayHelper.prototype.show = function (scene, color) {
  47478. if (!this._renderFunction) {
  47479. var ray = this.ray;
  47480. this._renderFunction = this._render.bind(this);
  47481. this._scene = scene;
  47482. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  47483. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  47484. this._scene.registerBeforeRender(this._renderFunction);
  47485. }
  47486. if (color) {
  47487. this._renderLine.color.copyFrom(color);
  47488. }
  47489. };
  47490. RayHelper.prototype.hide = function () {
  47491. if (this._renderFunction) {
  47492. this._scene.unregisterBeforeRender(this._renderFunction);
  47493. this._scene = null;
  47494. this._renderFunction = null;
  47495. this._renderLine.dispose();
  47496. this._renderLine = null;
  47497. this._renderPoints = null;
  47498. }
  47499. };
  47500. RayHelper.prototype._render = function () {
  47501. var ray = this.ray;
  47502. var point = this._renderPoints[1];
  47503. var len = Math.min(ray.length, 1000000);
  47504. point.copyFrom(ray.direction);
  47505. point.scaleInPlace(len);
  47506. point.addInPlace(ray.origin);
  47507. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  47508. };
  47509. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  47510. this._attachedToMesh = mesh;
  47511. var ray = this.ray;
  47512. if (!ray.direction) {
  47513. ray.direction = BABYLON.Vector3.Zero();
  47514. }
  47515. if (!ray.origin) {
  47516. ray.origin = BABYLON.Vector3.Zero();
  47517. }
  47518. if (length) {
  47519. ray.length = length;
  47520. }
  47521. if (!meshSpaceOrigin) {
  47522. meshSpaceOrigin = BABYLON.Vector3.Zero();
  47523. }
  47524. if (!meshSpaceDirection) {
  47525. // -1 so that this will work with Mesh.lookAt
  47526. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  47527. }
  47528. if (!this._meshSpaceDirection) {
  47529. this._meshSpaceDirection = meshSpaceDirection.clone();
  47530. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  47531. }
  47532. else {
  47533. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  47534. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  47535. }
  47536. if (!this._updateToMeshFunction) {
  47537. this._updateToMeshFunction = this._updateToMesh.bind(this);
  47538. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  47539. }
  47540. this._updateToMesh();
  47541. };
  47542. RayHelper.prototype.detachFromMesh = function () {
  47543. if (this._attachedToMesh) {
  47544. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  47545. this._attachedToMesh = null;
  47546. this._updateToMeshFunction = null;
  47547. }
  47548. };
  47549. RayHelper.prototype._updateToMesh = function () {
  47550. var ray = this.ray;
  47551. if (this._attachedToMesh._isDisposed) {
  47552. this.detachFromMesh();
  47553. return;
  47554. }
  47555. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  47556. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  47557. };
  47558. RayHelper.prototype.dispose = function () {
  47559. this.hide();
  47560. this.detachFromMesh();
  47561. this.ray = null;
  47562. };
  47563. return RayHelper;
  47564. }());
  47565. BABYLON.RayHelper = RayHelper;
  47566. })(BABYLON || (BABYLON = {}));
  47567. //# sourceMappingURL=babylon.rayHelper.js.map
  47568. var BABYLON;
  47569. (function (BABYLON) {
  47570. var DebugLayer = (function () {
  47571. function DebugLayer(scene) {
  47572. this._scene = scene;
  47573. }
  47574. /** Creates the inspector window. */
  47575. DebugLayer.prototype._createInspector = function (config) {
  47576. if (config === void 0) { config = {}; }
  47577. var popup = config.popup || false;
  47578. var initialTab = config.initialTab || 0;
  47579. var parentElement = config.parentElement || null;
  47580. if (!this._inspector) {
  47581. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  47582. } // else nothing to do,; instance is already existing
  47583. };
  47584. DebugLayer.prototype.isVisible = function () {
  47585. if (!this._inspector) {
  47586. return false;
  47587. }
  47588. return true;
  47589. };
  47590. DebugLayer.prototype.hide = function () {
  47591. if (this._inspector) {
  47592. try {
  47593. this._inspector.dispose();
  47594. }
  47595. catch (e) {
  47596. // If the inspector has been removed directly from the inspector tool
  47597. }
  47598. this._inspector = null;
  47599. }
  47600. };
  47601. DebugLayer.prototype.show = function (config) {
  47602. if (config === void 0) { config = {}; }
  47603. if (typeof INSPECTOR == 'undefined') {
  47604. // Load inspector and add it to the DOM
  47605. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  47606. }
  47607. else {
  47608. // Otherwise creates the inspector
  47609. this._createInspector(config);
  47610. }
  47611. };
  47612. // Get protocol used - http or https
  47613. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  47614. return DebugLayer;
  47615. }());
  47616. BABYLON.DebugLayer = DebugLayer;
  47617. })(BABYLON || (BABYLON = {}));
  47618. //# sourceMappingURL=babylon.debugLayer.js.map
  47619. var BABYLON;
  47620. (function (BABYLON) {
  47621. var Debug;
  47622. (function (Debug) {
  47623. var PhysicsViewer = (function () {
  47624. function PhysicsViewer(scene) {
  47625. this._impostors = [];
  47626. this._meshes = [];
  47627. this._numMeshes = 0;
  47628. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47629. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  47630. }
  47631. PhysicsViewer.prototype._updateDebugMeshes = function () {
  47632. var plugin = this._physicsEnginePlugin;
  47633. for (var i = 0; i < this._numMeshes; i++) {
  47634. if (this._impostors[i].isDisposed) {
  47635. this.hideImpostor(this._impostors[i--]);
  47636. }
  47637. else {
  47638. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  47639. }
  47640. }
  47641. };
  47642. PhysicsViewer.prototype.showImpostor = function (impostor) {
  47643. for (var i = 0; i < this._numMeshes; i++) {
  47644. if (this._impostors[i] == impostor) {
  47645. return;
  47646. }
  47647. }
  47648. var debugMesh = this._getDebugMesh(impostor, this._scene);
  47649. if (debugMesh) {
  47650. this._impostors[this._numMeshes] = impostor;
  47651. this._meshes[this._numMeshes] = debugMesh;
  47652. if (this._numMeshes === 0) {
  47653. this._renderFunction = this._updateDebugMeshes.bind(this);
  47654. this._scene.registerBeforeRender(this._renderFunction);
  47655. }
  47656. this._numMeshes++;
  47657. }
  47658. };
  47659. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  47660. var removed = false;
  47661. for (var i = 0; i < this._numMeshes; i++) {
  47662. if (this._impostors[i] == impostor) {
  47663. this._scene.removeMesh(this._meshes[i]);
  47664. this._meshes[i].dispose();
  47665. this._numMeshes--;
  47666. if (this._numMeshes > 0) {
  47667. this._meshes[i] = this._meshes[this._numMeshes];
  47668. this._impostors[i] = this._impostors[this._numMeshes];
  47669. this._meshes[this._numMeshes] = null;
  47670. this._impostors[this._numMeshes] = null;
  47671. }
  47672. else {
  47673. this._meshes[0] = null;
  47674. this._impostors[0] = null;
  47675. }
  47676. removed = true;
  47677. break;
  47678. }
  47679. }
  47680. if (removed && this._numMeshes === 0) {
  47681. this._scene.unregisterBeforeRender(this._renderFunction);
  47682. }
  47683. };
  47684. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  47685. if (!this._debugMaterial) {
  47686. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  47687. this._debugMaterial.wireframe = true;
  47688. }
  47689. return this._debugMaterial;
  47690. };
  47691. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  47692. if (!this._debugBoxMesh) {
  47693. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  47694. this._debugBoxMesh.renderingGroupId = 1;
  47695. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  47696. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  47697. scene.removeMesh(this._debugBoxMesh);
  47698. }
  47699. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  47700. };
  47701. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  47702. if (!this._debugSphereMesh) {
  47703. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  47704. this._debugSphereMesh.renderingGroupId = 1;
  47705. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  47706. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  47707. scene.removeMesh(this._debugSphereMesh);
  47708. }
  47709. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  47710. };
  47711. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  47712. var body = impostor.physicsBody;
  47713. var shape = body.shapes[0];
  47714. var mesh;
  47715. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  47716. mesh = this._getDebugBoxMesh(scene);
  47717. impostor.getBoxSizeToRef(mesh.scaling);
  47718. }
  47719. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  47720. mesh = this._getDebugSphereMesh(scene);
  47721. var radius = impostor.getRadius();
  47722. mesh.scaling.x = radius * 2;
  47723. mesh.scaling.y = radius * 2;
  47724. mesh.scaling.z = radius * 2;
  47725. }
  47726. return mesh;
  47727. };
  47728. PhysicsViewer.prototype.dispose = function () {
  47729. for (var i = 0; i < this._numMeshes; i++) {
  47730. this.hideImpostor(this._impostors[i]);
  47731. }
  47732. if (this._debugBoxMesh) {
  47733. this._debugBoxMesh.dispose();
  47734. }
  47735. if (this._debugSphereMesh) {
  47736. this._debugSphereMesh.dispose();
  47737. }
  47738. if (this._debugMaterial) {
  47739. this._debugMaterial.dispose();
  47740. }
  47741. this._impostors.length = 0;
  47742. this._scene = null;
  47743. this._physicsEnginePlugin = null;
  47744. };
  47745. return PhysicsViewer;
  47746. }());
  47747. Debug.PhysicsViewer = PhysicsViewer;
  47748. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47749. })(BABYLON || (BABYLON = {}));
  47750. //# sourceMappingURL=babylon.physicsViewer.js.map
  47751. var BABYLON;
  47752. (function (BABYLON) {
  47753. var BoundingBoxRenderer = (function () {
  47754. function BoundingBoxRenderer(scene) {
  47755. this.frontColor = new BABYLON.Color3(1, 1, 1);
  47756. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  47757. this.showBackLines = true;
  47758. this.renderList = new BABYLON.SmartArray(32);
  47759. this._vertexBuffers = {};
  47760. this._scene = scene;
  47761. }
  47762. BoundingBoxRenderer.prototype._prepareRessources = function () {
  47763. if (this._colorShader) {
  47764. return;
  47765. }
  47766. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  47767. attributes: [BABYLON.VertexBuffer.PositionKind],
  47768. uniforms: ["world", "viewProjection", "color"]
  47769. });
  47770. var engine = this._scene.getEngine();
  47771. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  47772. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  47773. this._createIndexBuffer();
  47774. };
  47775. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  47776. var engine = this._scene.getEngine();
  47777. 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]);
  47778. };
  47779. BoundingBoxRenderer.prototype._rebuild = function () {
  47780. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  47781. this._createIndexBuffer();
  47782. };
  47783. BoundingBoxRenderer.prototype.reset = function () {
  47784. this.renderList.reset();
  47785. };
  47786. BoundingBoxRenderer.prototype.render = function () {
  47787. if (this.renderList.length === 0) {
  47788. return;
  47789. }
  47790. this._prepareRessources();
  47791. if (!this._colorShader.isReady()) {
  47792. return;
  47793. }
  47794. var engine = this._scene.getEngine();
  47795. engine.setDepthWrite(false);
  47796. this._colorShader._preBind();
  47797. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  47798. var boundingBox = this.renderList.data[boundingBoxIndex];
  47799. var min = boundingBox.minimum;
  47800. var max = boundingBox.maximum;
  47801. var diff = max.subtract(min);
  47802. var median = min.add(diff.scale(0.5));
  47803. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  47804. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  47805. .multiply(boundingBox.getWorldMatrix());
  47806. // VBOs
  47807. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  47808. if (this.showBackLines) {
  47809. // Back
  47810. engine.setDepthFunctionToGreaterOrEqual();
  47811. this._scene.resetCachedMaterial();
  47812. this._colorShader.setColor4("color", this.backColor.toColor4());
  47813. this._colorShader.bind(worldMatrix);
  47814. // Draw order
  47815. engine.draw(false, 0, 24);
  47816. }
  47817. // Front
  47818. engine.setDepthFunctionToLess();
  47819. this._scene.resetCachedMaterial();
  47820. this._colorShader.setColor4("color", this.frontColor.toColor4());
  47821. this._colorShader.bind(worldMatrix);
  47822. // Draw order
  47823. engine.draw(false, 0, 24);
  47824. }
  47825. this._colorShader.unbind();
  47826. engine.setDepthFunctionToLessOrEqual();
  47827. engine.setDepthWrite(true);
  47828. };
  47829. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  47830. this._prepareRessources();
  47831. if (!this._colorShader.isReady()) {
  47832. return;
  47833. }
  47834. var engine = this._scene.getEngine();
  47835. engine.setDepthWrite(false);
  47836. engine.setColorWrite(false);
  47837. this._colorShader._preBind();
  47838. var boundingBox = mesh._boundingInfo.boundingBox;
  47839. var min = boundingBox.minimum;
  47840. var max = boundingBox.maximum;
  47841. var diff = max.subtract(min);
  47842. var median = min.add(diff.scale(0.5));
  47843. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  47844. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  47845. .multiply(boundingBox.getWorldMatrix());
  47846. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  47847. engine.setDepthFunctionToLess();
  47848. this._scene.resetCachedMaterial();
  47849. this._colorShader.bind(worldMatrix);
  47850. engine.draw(false, 0, 24);
  47851. this._colorShader.unbind();
  47852. engine.setDepthFunctionToLessOrEqual();
  47853. engine.setDepthWrite(true);
  47854. engine.setColorWrite(true);
  47855. };
  47856. BoundingBoxRenderer.prototype.dispose = function () {
  47857. if (!this._colorShader) {
  47858. return;
  47859. }
  47860. this.renderList.dispose();
  47861. this._colorShader.dispose();
  47862. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  47863. if (buffer) {
  47864. buffer.dispose();
  47865. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  47866. }
  47867. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47868. };
  47869. return BoundingBoxRenderer;
  47870. }());
  47871. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  47872. })(BABYLON || (BABYLON = {}));
  47873. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  47874. var BABYLON;
  47875. (function (BABYLON) {
  47876. var TextureTools = (function () {
  47877. function TextureTools() {
  47878. }
  47879. /**
  47880. * Uses the GPU to create a copy texture rescaled at a given size
  47881. * @param texture Texture to copy from
  47882. * @param width Desired width
  47883. * @param height Desired height
  47884. * @return Generated texture
  47885. */
  47886. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  47887. if (useBilinearMode === void 0) { useBilinearMode = true; }
  47888. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  47889. var scene = texture.getScene();
  47890. var engine = scene.getEngine();
  47891. rtt.wrapU = texture.wrapU;
  47892. rtt.wrapV = texture.wrapV;
  47893. rtt.uOffset = texture.uOffset;
  47894. rtt.vOffset = texture.vOffset;
  47895. rtt.uScale = texture.uScale;
  47896. rtt.vScale = texture.vScale;
  47897. rtt.uAng = texture.uAng;
  47898. rtt.vAng = texture.vAng;
  47899. rtt.wAng = texture.wAng;
  47900. rtt.coordinatesIndex = texture.coordinatesIndex;
  47901. rtt.level = texture.level;
  47902. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  47903. rtt._texture.isReady = false;
  47904. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47905. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47906. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47907. passPostProcess.getEffect().executeWhenCompiled(function () {
  47908. passPostProcess.onApply = function (effect) {
  47909. effect.setTexture("textureSampler", texture);
  47910. };
  47911. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  47912. engine.unBindFramebuffer(rtt.getInternalTexture());
  47913. rtt.disposeFramebufferObjects();
  47914. passPostProcess.dispose();
  47915. rtt._texture.isReady = true;
  47916. });
  47917. return rtt;
  47918. };
  47919. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  47920. if (!scene._environmentBRDFTexture) {
  47921. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47922. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47923. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47924. scene._environmentBRDFTexture = texture;
  47925. }
  47926. return scene._environmentBRDFTexture;
  47927. };
  47928. 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=";
  47929. return TextureTools;
  47930. }());
  47931. BABYLON.TextureTools = TextureTools;
  47932. })(BABYLON || (BABYLON = {}));
  47933. //# sourceMappingURL=babylon.textureTools.js.map
  47934. var BABYLON;
  47935. (function (BABYLON) {
  47936. var SphericalPolynomial = (function () {
  47937. function SphericalPolynomial() {
  47938. this.x = BABYLON.Vector3.Zero();
  47939. this.y = BABYLON.Vector3.Zero();
  47940. this.z = BABYLON.Vector3.Zero();
  47941. this.xx = BABYLON.Vector3.Zero();
  47942. this.yy = BABYLON.Vector3.Zero();
  47943. this.zz = BABYLON.Vector3.Zero();
  47944. this.xy = BABYLON.Vector3.Zero();
  47945. this.yz = BABYLON.Vector3.Zero();
  47946. this.zx = BABYLON.Vector3.Zero();
  47947. }
  47948. SphericalPolynomial.prototype.addAmbient = function (color) {
  47949. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  47950. this.xx = this.xx.add(colorVector);
  47951. this.yy = this.yy.add(colorVector);
  47952. this.zz = this.zz.add(colorVector);
  47953. };
  47954. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  47955. var result = new SphericalPolynomial();
  47956. result.x = harmonics.L11.scale(1.02333);
  47957. result.y = harmonics.L1_1.scale(1.02333);
  47958. result.z = harmonics.L10.scale(1.02333);
  47959. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  47960. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  47961. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  47962. result.yz = harmonics.L2_1.scale(0.858086);
  47963. result.zx = harmonics.L21.scale(0.858086);
  47964. result.xy = harmonics.L2_2.scale(0.858086);
  47965. result.scale(1.0 / Math.PI);
  47966. return result;
  47967. };
  47968. SphericalPolynomial.prototype.scale = function (scale) {
  47969. this.x = this.x.scale(scale);
  47970. this.y = this.y.scale(scale);
  47971. this.z = this.z.scale(scale);
  47972. this.xx = this.xx.scale(scale);
  47973. this.yy = this.yy.scale(scale);
  47974. this.zz = this.zz.scale(scale);
  47975. this.yz = this.yz.scale(scale);
  47976. this.zx = this.zx.scale(scale);
  47977. this.xy = this.xy.scale(scale);
  47978. };
  47979. return SphericalPolynomial;
  47980. }());
  47981. BABYLON.SphericalPolynomial = SphericalPolynomial;
  47982. var SphericalHarmonics = (function () {
  47983. function SphericalHarmonics() {
  47984. this.L00 = BABYLON.Vector3.Zero();
  47985. this.L1_1 = BABYLON.Vector3.Zero();
  47986. this.L10 = BABYLON.Vector3.Zero();
  47987. this.L11 = BABYLON.Vector3.Zero();
  47988. this.L2_2 = BABYLON.Vector3.Zero();
  47989. this.L2_1 = BABYLON.Vector3.Zero();
  47990. this.L20 = BABYLON.Vector3.Zero();
  47991. this.L21 = BABYLON.Vector3.Zero();
  47992. this.L22 = BABYLON.Vector3.Zero();
  47993. }
  47994. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  47995. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  47996. var c = colorVector.scale(deltaSolidAngle);
  47997. this.L00 = this.L00.add(c.scale(0.282095));
  47998. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  47999. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  48000. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  48001. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  48002. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  48003. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  48004. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  48005. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  48006. };
  48007. SphericalHarmonics.prototype.scale = function (scale) {
  48008. this.L00 = this.L00.scale(scale);
  48009. this.L1_1 = this.L1_1.scale(scale);
  48010. this.L10 = this.L10.scale(scale);
  48011. this.L11 = this.L11.scale(scale);
  48012. this.L2_2 = this.L2_2.scale(scale);
  48013. this.L2_1 = this.L2_1.scale(scale);
  48014. this.L20 = this.L20.scale(scale);
  48015. this.L21 = this.L21.scale(scale);
  48016. this.L22 = this.L22.scale(scale);
  48017. };
  48018. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  48019. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  48020. //
  48021. // E_lm = A_l * L_lm
  48022. //
  48023. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  48024. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  48025. // the scaling factors are given in equation 9.
  48026. // Constant (Band 0)
  48027. this.L00 = this.L00.scale(3.141593);
  48028. // Linear (Band 1)
  48029. this.L1_1 = this.L1_1.scale(2.094395);
  48030. this.L10 = this.L10.scale(2.094395);
  48031. this.L11 = this.L11.scale(2.094395);
  48032. // Quadratic (Band 2)
  48033. this.L2_2 = this.L2_2.scale(0.785398);
  48034. this.L2_1 = this.L2_1.scale(0.785398);
  48035. this.L20 = this.L20.scale(0.785398);
  48036. this.L21 = this.L21.scale(0.785398);
  48037. this.L22 = this.L22.scale(0.785398);
  48038. };
  48039. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  48040. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  48041. // L = (1/pi) * E * rho
  48042. //
  48043. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  48044. this.scale(1.0 / Math.PI);
  48045. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  48046. // (The pixel shader must apply albedo after texture fetches, etc).
  48047. };
  48048. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  48049. var result = new SphericalHarmonics();
  48050. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  48051. result.L1_1 = polynomial.y.scale(0.977204);
  48052. result.L10 = polynomial.z.scale(0.977204);
  48053. result.L11 = polynomial.x.scale(0.977204);
  48054. result.L2_2 = polynomial.xy.scale(1.16538);
  48055. result.L2_1 = polynomial.yz.scale(1.16538);
  48056. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  48057. result.L21 = polynomial.zx.scale(1.16538);
  48058. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  48059. result.scale(Math.PI);
  48060. return result;
  48061. };
  48062. return SphericalHarmonics;
  48063. }());
  48064. BABYLON.SphericalHarmonics = SphericalHarmonics;
  48065. })(BABYLON || (BABYLON = {}));
  48066. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  48067. var BABYLON;
  48068. (function (BABYLON) {
  48069. var Internals;
  48070. (function (Internals) {
  48071. var FileFaceOrientation = (function () {
  48072. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  48073. this.name = name;
  48074. this.worldAxisForNormal = worldAxisForNormal;
  48075. this.worldAxisForFileX = worldAxisForFileX;
  48076. this.worldAxisForFileY = worldAxisForFileY;
  48077. }
  48078. return FileFaceOrientation;
  48079. }());
  48080. ;
  48081. /**
  48082. * Helper class dealing with the extraction of spherical polynomial dataArray
  48083. * from a cube map.
  48084. */
  48085. var CubeMapToSphericalPolynomialTools = (function () {
  48086. function CubeMapToSphericalPolynomialTools() {
  48087. }
  48088. /**
  48089. * Converts a texture to the according Spherical Polynomial data.
  48090. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48091. *
  48092. * @param texture The texture to extract the information from.
  48093. * @return The Spherical Polynomial data.
  48094. */
  48095. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  48096. if (!texture.isCube) {
  48097. // Only supports cube Textures currently.
  48098. return null;
  48099. }
  48100. var size = texture.getSize().width;
  48101. var right = texture.readPixels(0);
  48102. var left = texture.readPixels(1);
  48103. var up;
  48104. var down;
  48105. if (texture.isRenderTarget) {
  48106. up = texture.readPixels(3);
  48107. down = texture.readPixels(2);
  48108. }
  48109. else {
  48110. up = texture.readPixels(2);
  48111. down = texture.readPixels(3);
  48112. }
  48113. var front = texture.readPixels(4);
  48114. var back = texture.readPixels(5);
  48115. var gammaSpace = texture.gammaSpace;
  48116. // Always read as RGBA.
  48117. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  48118. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  48119. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  48120. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  48121. }
  48122. var cubeInfo = {
  48123. size: size,
  48124. right: right,
  48125. left: left,
  48126. up: up,
  48127. down: down,
  48128. front: front,
  48129. back: back,
  48130. format: format,
  48131. type: type,
  48132. gammaSpace: gammaSpace,
  48133. };
  48134. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  48135. };
  48136. /**
  48137. * Converts a cubemap to the according Spherical Polynomial data.
  48138. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48139. *
  48140. * @param cubeInfo The Cube map to extract the information from.
  48141. * @return The Spherical Polynomial data.
  48142. */
  48143. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  48144. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  48145. var totalSolidAngle = 0.0;
  48146. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  48147. var du = 2.0 / cubeInfo.size;
  48148. var dv = du;
  48149. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  48150. var minUV = du * 0.5 - 1.0;
  48151. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48152. var fileFace = this.FileFaces[faceIndex];
  48153. var dataArray = cubeInfo[fileFace.name];
  48154. var v = minUV;
  48155. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  48156. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  48157. // Because SP is still linear, so summation is fine in that basis.
  48158. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  48159. for (var y = 0; y < cubeInfo.size; y++) {
  48160. var u = minUV;
  48161. for (var x = 0; x < cubeInfo.size; x++) {
  48162. // World direction (not normalised)
  48163. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  48164. worldDirection.normalize();
  48165. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  48166. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  48167. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  48168. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  48169. // Handle Integer types.
  48170. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  48171. r /= 255;
  48172. g /= 255;
  48173. b /= 255;
  48174. }
  48175. // Handle Gamma space textures.
  48176. if (cubeInfo.gammaSpace) {
  48177. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  48178. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  48179. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  48180. }
  48181. var color = new BABYLON.Color3(r, g, b);
  48182. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48183. totalSolidAngle += deltaSolidAngle;
  48184. u += du;
  48185. }
  48186. v += dv;
  48187. }
  48188. }
  48189. // Solid angle for entire sphere is 4*pi
  48190. var sphereSolidAngle = 4.0 * Math.PI;
  48191. // Adjust the solid angle to allow for how many faces we processed.
  48192. var facesProcessed = 6.0;
  48193. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  48194. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  48195. // This is needed because the numerical integration over the cube uses a
  48196. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  48197. // and also to compensate for accumulative error due to float precision in the summation.
  48198. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  48199. sphericalHarmonics.scale(correctionFactor);
  48200. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  48201. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  48202. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  48203. };
  48204. CubeMapToSphericalPolynomialTools.FileFaces = [
  48205. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  48206. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  48207. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  48208. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  48209. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  48210. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  48211. ];
  48212. return CubeMapToSphericalPolynomialTools;
  48213. }());
  48214. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  48215. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48216. })(BABYLON || (BABYLON = {}));
  48217. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  48218. var BABYLON;
  48219. (function (BABYLON) {
  48220. var Internals;
  48221. (function (Internals) {
  48222. /**
  48223. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  48224. */
  48225. var PanoramaToCubeMapTools = (function () {
  48226. function PanoramaToCubeMapTools() {
  48227. }
  48228. /**
  48229. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  48230. *
  48231. * @param float32Array The source data.
  48232. * @param inputWidth The width of the input panorama.
  48233. * @param inputhHeight The height of the input panorama.
  48234. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  48235. * @return The cubemap data
  48236. */
  48237. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  48238. if (!float32Array) {
  48239. throw "ConvertPanoramaToCubemap: input cannot be null";
  48240. }
  48241. if (float32Array.length != inputWidth * inputHeight * 3) {
  48242. throw "ConvertPanoramaToCubemap: input size is wrong";
  48243. }
  48244. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  48245. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  48246. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  48247. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  48248. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  48249. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  48250. return {
  48251. front: textureFront,
  48252. back: textureBack,
  48253. left: textureLeft,
  48254. right: textureRight,
  48255. up: textureUp,
  48256. down: textureDown,
  48257. size: size,
  48258. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  48259. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  48260. gammaSpace: false,
  48261. };
  48262. };
  48263. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  48264. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  48265. var textureArray = new Float32Array(buffer);
  48266. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  48267. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  48268. var dy = 1 / texSize;
  48269. var fy = 0;
  48270. for (var y = 0; y < texSize; y++) {
  48271. var xv1 = faceData[0];
  48272. var xv2 = faceData[2];
  48273. for (var x = 0; x < texSize; x++) {
  48274. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  48275. v.normalize();
  48276. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  48277. // 3 channels per pixels
  48278. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  48279. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  48280. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  48281. xv1 = xv1.add(rotDX1);
  48282. xv2 = xv2.add(rotDX2);
  48283. }
  48284. fy += dy;
  48285. }
  48286. return textureArray;
  48287. };
  48288. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  48289. var theta = Math.atan2(vDir.z, vDir.x);
  48290. var phi = Math.acos(vDir.y);
  48291. while (theta < -Math.PI)
  48292. theta += 2 * Math.PI;
  48293. while (theta > Math.PI)
  48294. theta -= 2 * Math.PI;
  48295. var dx = theta / Math.PI;
  48296. var dy = phi / Math.PI;
  48297. // recenter.
  48298. dx = dx * 0.5 + 0.5;
  48299. var px = Math.round(dx * inputWidth);
  48300. if (px < 0)
  48301. px = 0;
  48302. else if (px >= inputWidth)
  48303. px = inputWidth - 1;
  48304. var py = Math.round(dy * inputHeight);
  48305. if (py < 0)
  48306. py = 0;
  48307. else if (py >= inputHeight)
  48308. py = inputHeight - 1;
  48309. var inputY = (inputHeight - py - 1);
  48310. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  48311. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  48312. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  48313. return {
  48314. r: r,
  48315. g: g,
  48316. b: b
  48317. };
  48318. };
  48319. PanoramaToCubeMapTools.FACE_FRONT = [
  48320. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48321. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48322. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48323. new BABYLON.Vector3(1.0, 1.0, -1.0)
  48324. ];
  48325. PanoramaToCubeMapTools.FACE_BACK = [
  48326. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48327. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48328. new BABYLON.Vector3(1.0, 1.0, 1.0),
  48329. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  48330. ];
  48331. PanoramaToCubeMapTools.FACE_RIGHT = [
  48332. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48333. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48334. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48335. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48336. ];
  48337. PanoramaToCubeMapTools.FACE_LEFT = [
  48338. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48339. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48340. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48341. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  48342. ];
  48343. PanoramaToCubeMapTools.FACE_DOWN = [
  48344. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48345. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48346. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48347. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48348. ];
  48349. PanoramaToCubeMapTools.FACE_UP = [
  48350. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48351. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48352. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48353. new BABYLON.Vector3(1.0, -1.0, -1.0)
  48354. ];
  48355. return PanoramaToCubeMapTools;
  48356. }());
  48357. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  48358. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48359. })(BABYLON || (BABYLON = {}));
  48360. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  48361. var BABYLON;
  48362. (function (BABYLON) {
  48363. var Internals;
  48364. (function (Internals) {
  48365. ;
  48366. /**
  48367. * This groups tools to convert HDR texture to native colors array.
  48368. */
  48369. var HDRTools = (function () {
  48370. function HDRTools() {
  48371. }
  48372. HDRTools.Ldexp = function (mantissa, exponent) {
  48373. if (exponent > 1023) {
  48374. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  48375. }
  48376. if (exponent < -1074) {
  48377. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  48378. }
  48379. return mantissa * Math.pow(2, exponent);
  48380. };
  48381. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  48382. if (exponent > 0) {
  48383. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  48384. float32array[index + 0] = red * exponent;
  48385. float32array[index + 1] = green * exponent;
  48386. float32array[index + 2] = blue * exponent;
  48387. }
  48388. else {
  48389. float32array[index + 0] = 0;
  48390. float32array[index + 1] = 0;
  48391. float32array[index + 2] = 0;
  48392. }
  48393. };
  48394. HDRTools.readStringLine = function (uint8array, startIndex) {
  48395. var line = "";
  48396. var character = "";
  48397. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  48398. character = String.fromCharCode(uint8array[i]);
  48399. if (character == "\n") {
  48400. break;
  48401. }
  48402. line += character;
  48403. }
  48404. return line;
  48405. };
  48406. /**
  48407. * Reads header information from an RGBE texture stored in a native array.
  48408. * More information on this format are available here:
  48409. * https://en.wikipedia.org/wiki/RGBE_image_format
  48410. *
  48411. * @param uint8array The binary file stored in native array.
  48412. * @return The header information.
  48413. */
  48414. HDRTools.RGBE_ReadHeader = function (uint8array) {
  48415. var height = 0;
  48416. var width = 0;
  48417. var line = this.readStringLine(uint8array, 0);
  48418. if (line[0] != '#' || line[1] != '?') {
  48419. throw "Bad HDR Format.";
  48420. }
  48421. var endOfHeader = false;
  48422. var findFormat = false;
  48423. var lineIndex = 0;
  48424. do {
  48425. lineIndex += (line.length + 1);
  48426. line = this.readStringLine(uint8array, lineIndex);
  48427. if (line == "FORMAT=32-bit_rle_rgbe") {
  48428. findFormat = true;
  48429. }
  48430. else if (line.length == 0) {
  48431. endOfHeader = true;
  48432. }
  48433. } while (!endOfHeader);
  48434. if (!findFormat) {
  48435. throw "HDR Bad header format, unsupported FORMAT";
  48436. }
  48437. lineIndex += (line.length + 1);
  48438. line = this.readStringLine(uint8array, lineIndex);
  48439. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  48440. var match = sizeRegexp.exec(line);
  48441. // TODO. Support +Y and -X if needed.
  48442. if (match.length < 3) {
  48443. throw "HDR Bad header format, no size";
  48444. }
  48445. width = parseInt(match[2]);
  48446. height = parseInt(match[1]);
  48447. if (width < 8 || width > 0x7fff) {
  48448. throw "HDR Bad header format, unsupported size";
  48449. }
  48450. lineIndex += (line.length + 1);
  48451. return {
  48452. height: height,
  48453. width: width,
  48454. dataPosition: lineIndex
  48455. };
  48456. };
  48457. /**
  48458. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  48459. * This RGBE texture needs to store the information as a panorama.
  48460. *
  48461. * More information on this format are available here:
  48462. * https://en.wikipedia.org/wiki/RGBE_image_format
  48463. *
  48464. * @param buffer The binary file stored in an array buffer.
  48465. * @param size The expected size of the extracted cubemap.
  48466. * @return The Cube Map information.
  48467. */
  48468. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  48469. var uint8array = new Uint8Array(buffer);
  48470. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  48471. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48472. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  48473. return cubeMapData;
  48474. };
  48475. /**
  48476. * Returns the pixels data extracted from an RGBE texture.
  48477. * This pixels will be stored left to right up to down in the R G B order in one array.
  48478. *
  48479. * More information on this format are available here:
  48480. * https://en.wikipedia.org/wiki/RGBE_image_format
  48481. *
  48482. * @param uint8array The binary file stored in an array buffer.
  48483. * @param hdrInfo The header information of the file.
  48484. * @return The pixels data in RGB right to left up to down order.
  48485. */
  48486. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  48487. // Keep for multi format supports.
  48488. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48489. };
  48490. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  48491. var num_scanlines = hdrInfo.height;
  48492. var scanline_width = hdrInfo.width;
  48493. var a, b, c, d, count;
  48494. var dataIndex = hdrInfo.dataPosition;
  48495. var index = 0, endIndex = 0, i = 0;
  48496. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  48497. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  48498. // 3 channels of 4 bytes per pixel in float.
  48499. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  48500. var resultArray = new Float32Array(resultBuffer);
  48501. // read in each successive scanline
  48502. while (num_scanlines > 0) {
  48503. a = uint8array[dataIndex++];
  48504. b = uint8array[dataIndex++];
  48505. c = uint8array[dataIndex++];
  48506. d = uint8array[dataIndex++];
  48507. if (a != 2 || b != 2 || (c & 0x80)) {
  48508. // this file is not run length encoded
  48509. throw "HDR Bad header format, not RLE";
  48510. }
  48511. if (((c << 8) | d) != scanline_width) {
  48512. throw "HDR Bad header format, wrong scan line width";
  48513. }
  48514. index = 0;
  48515. // read each of the four channels for the scanline into the buffer
  48516. for (i = 0; i < 4; i++) {
  48517. endIndex = (i + 1) * scanline_width;
  48518. while (index < endIndex) {
  48519. a = uint8array[dataIndex++];
  48520. b = uint8array[dataIndex++];
  48521. if (a > 128) {
  48522. // a run of the same value
  48523. count = a - 128;
  48524. if ((count == 0) || (count > endIndex - index)) {
  48525. throw "HDR Bad Format, bad scanline data (run)";
  48526. }
  48527. while (count-- > 0) {
  48528. scanLineArray[index++] = b;
  48529. }
  48530. }
  48531. else {
  48532. // a non-run
  48533. count = a;
  48534. if ((count == 0) || (count > endIndex - index)) {
  48535. throw "HDR Bad Format, bad scanline data (non-run)";
  48536. }
  48537. scanLineArray[index++] = b;
  48538. if (--count > 0) {
  48539. for (var j = 0; j < count; j++) {
  48540. scanLineArray[index++] = uint8array[dataIndex++];
  48541. }
  48542. }
  48543. }
  48544. }
  48545. }
  48546. // now convert data from buffer into floats
  48547. for (i = 0; i < scanline_width; i++) {
  48548. a = scanLineArray[i];
  48549. b = scanLineArray[i + scanline_width];
  48550. c = scanLineArray[i + 2 * scanline_width];
  48551. d = scanLineArray[i + 3 * scanline_width];
  48552. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  48553. }
  48554. num_scanlines--;
  48555. }
  48556. return resultArray;
  48557. };
  48558. return HDRTools;
  48559. }());
  48560. Internals.HDRTools = HDRTools;
  48561. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48562. })(BABYLON || (BABYLON = {}));
  48563. //# sourceMappingURL=babylon.hdr.js.map
  48564. var BABYLON;
  48565. (function (BABYLON) {
  48566. /**
  48567. * This represents a texture coming from an HDR input.
  48568. *
  48569. * The only supported format is currently panorama picture stored in RGBE format.
  48570. * Example of such files can be found on HDRLib: http://hdrlib.com/
  48571. */
  48572. var HDRCubeTexture = (function (_super) {
  48573. __extends(HDRCubeTexture, _super);
  48574. /**
  48575. * Instantiates an HDRTexture from the following parameters.
  48576. *
  48577. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  48578. * @param scene The scene the texture will be used in
  48579. * @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.
  48580. * @param noMipmap Forces to not generate the mipmap if true
  48581. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  48582. * @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)
  48583. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  48584. */
  48585. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  48586. if (noMipmap === void 0) { noMipmap = false; }
  48587. if (generateHarmonics === void 0) { generateHarmonics = true; }
  48588. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  48589. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  48590. if (onLoad === void 0) { onLoad = null; }
  48591. if (onError === void 0) { onError = null; }
  48592. var _this = _super.call(this, scene) || this;
  48593. _this._useInGammaSpace = false;
  48594. _this._generateHarmonics = true;
  48595. _this._isBABYLONPreprocessed = false;
  48596. _this._onLoad = null;
  48597. _this._onError = null;
  48598. /**
  48599. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  48600. */
  48601. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  48602. /**
  48603. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  48604. * This is usefull at run time to apply the good shader.
  48605. */
  48606. _this.isPMREM = false;
  48607. _this._isBlocking = true;
  48608. if (!url) {
  48609. return _this;
  48610. }
  48611. _this.name = url;
  48612. _this.url = url;
  48613. _this.hasAlpha = false;
  48614. _this.isCube = true;
  48615. _this._textureMatrix = BABYLON.Matrix.Identity();
  48616. _this._onLoad = onLoad;
  48617. _this._onError = onError;
  48618. _this.gammaSpace = false;
  48619. if (size) {
  48620. _this._isBABYLONPreprocessed = false;
  48621. _this._noMipmap = noMipmap;
  48622. _this._size = size;
  48623. _this._useInGammaSpace = useInGammaSpace;
  48624. _this._usePMREMGenerator = usePMREMGenerator &&
  48625. scene.getEngine().getCaps().textureLOD &&
  48626. _this.getScene().getEngine().getCaps().textureFloat &&
  48627. !_this._useInGammaSpace;
  48628. }
  48629. else {
  48630. _this._isBABYLONPreprocessed = true;
  48631. _this._noMipmap = false;
  48632. _this._useInGammaSpace = false;
  48633. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  48634. _this.getScene().getEngine().getCaps().textureFloat &&
  48635. !_this._useInGammaSpace;
  48636. }
  48637. _this.isPMREM = _this._usePMREMGenerator;
  48638. _this._texture = _this._getFromCache(url, _this._noMipmap);
  48639. if (!_this._texture) {
  48640. if (!scene.useDelayedTextureLoading) {
  48641. _this.loadTexture();
  48642. }
  48643. else {
  48644. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  48645. }
  48646. }
  48647. return _this;
  48648. }
  48649. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  48650. /**
  48651. * Gets wether or not the texture is blocking during loading.
  48652. */
  48653. get: function () {
  48654. return this._isBlocking;
  48655. },
  48656. /**
  48657. * Sets wether or not the texture is blocking during loading.
  48658. */
  48659. set: function (value) {
  48660. this._isBlocking = value;
  48661. },
  48662. enumerable: true,
  48663. configurable: true
  48664. });
  48665. /**
  48666. * Occurs when the file is a preprocessed .babylon.hdr file.
  48667. */
  48668. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  48669. var _this = this;
  48670. var mipLevels = 0;
  48671. var floatArrayView = null;
  48672. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  48673. var mips = [];
  48674. var startIndex = 30;
  48675. for (var level = 0; level < mipLevels; level++) {
  48676. mips.push([]);
  48677. // Fill each pixel of the mip level.
  48678. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  48679. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48680. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  48681. mips[level].push(faceData);
  48682. startIndex += faceSize;
  48683. }
  48684. }
  48685. return mips;
  48686. } : null;
  48687. var callback = function (buffer) {
  48688. // Create Native Array Views
  48689. var intArrayView = new Int32Array(buffer);
  48690. floatArrayView = new Float32Array(buffer);
  48691. // Fill header.
  48692. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  48693. _this._size = intArrayView[1]; // CubeMap max mip face size.
  48694. // Update Texture Information.
  48695. _this._texture.updateSize(_this._size, _this._size);
  48696. // Fill polynomial information.
  48697. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  48698. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  48699. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  48700. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  48701. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  48702. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  48703. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  48704. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  48705. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  48706. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  48707. _this.sphericalPolynomial = sphericalPolynomial;
  48708. // Fill pixel data.
  48709. mipLevels = intArrayView[29]; // Number of mip levels.
  48710. var startIndex = 30;
  48711. var data = [];
  48712. var faceSize = Math.pow(_this._size, 2) * 3;
  48713. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48714. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  48715. startIndex += faceSize;
  48716. }
  48717. var results = [];
  48718. var byteArray = null;
  48719. // Push each faces.
  48720. for (var k = 0; k < 6; k++) {
  48721. var dataFace = null;
  48722. // To be deprecated.
  48723. if (version === 1) {
  48724. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  48725. dataFace = data[j];
  48726. }
  48727. // If special cases.
  48728. if (!mipmapGenerator) {
  48729. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  48730. // 3 channels of 1 bytes per pixel in bytes.
  48731. var byteBuffer = new ArrayBuffer(faceSize);
  48732. byteArray = new Uint8Array(byteBuffer);
  48733. }
  48734. for (var i = 0; i < _this._size * _this._size; i++) {
  48735. // Put in gamma space if requested.
  48736. if (_this._useInGammaSpace) {
  48737. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48738. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48739. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48740. }
  48741. // Convert to int texture for fallback.
  48742. if (byteArray) {
  48743. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48744. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48745. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48746. // May use luminance instead if the result is not accurate.
  48747. var max = Math.max(Math.max(r, g), b);
  48748. if (max > 255) {
  48749. var scale = 255 / max;
  48750. r *= scale;
  48751. g *= scale;
  48752. b *= scale;
  48753. }
  48754. byteArray[(i * 3) + 0] = r;
  48755. byteArray[(i * 3) + 1] = g;
  48756. byteArray[(i * 3) + 2] = b;
  48757. }
  48758. }
  48759. }
  48760. // Fill the array accordingly.
  48761. if (byteArray) {
  48762. results.push(byteArray);
  48763. }
  48764. else {
  48765. results.push(dataFace);
  48766. }
  48767. }
  48768. return results;
  48769. };
  48770. 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);
  48771. };
  48772. /**
  48773. * Occurs when the file is raw .hdr file.
  48774. */
  48775. HDRCubeTexture.prototype.loadHDRTexture = function () {
  48776. var _this = this;
  48777. var callback = function (buffer) {
  48778. // Extract the raw linear data.
  48779. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  48780. // Generate harmonics if needed.
  48781. if (_this._generateHarmonics) {
  48782. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  48783. _this.sphericalPolynomial = sphericalPolynomial;
  48784. }
  48785. var results = [];
  48786. var byteArray = null;
  48787. // Push each faces.
  48788. for (var j = 0; j < 6; j++) {
  48789. // Create uintarray fallback.
  48790. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  48791. // 3 channels of 1 bytes per pixel in bytes.
  48792. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  48793. byteArray = new Uint8Array(byteBuffer);
  48794. }
  48795. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  48796. // If special cases.
  48797. if (_this._useInGammaSpace || byteArray) {
  48798. for (var i = 0; i < _this._size * _this._size; i++) {
  48799. // Put in gamma space if requested.
  48800. if (_this._useInGammaSpace) {
  48801. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48802. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48803. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48804. }
  48805. // Convert to int texture for fallback.
  48806. if (byteArray) {
  48807. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48808. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48809. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48810. // May use luminance instead if the result is not accurate.
  48811. var max = Math.max(Math.max(r, g), b);
  48812. if (max > 255) {
  48813. var scale = 255 / max;
  48814. r *= scale;
  48815. g *= scale;
  48816. b *= scale;
  48817. }
  48818. byteArray[(i * 3) + 0] = r;
  48819. byteArray[(i * 3) + 1] = g;
  48820. byteArray[(i * 3) + 2] = b;
  48821. }
  48822. }
  48823. }
  48824. if (byteArray) {
  48825. results.push(byteArray);
  48826. }
  48827. else {
  48828. results.push(dataFace);
  48829. }
  48830. }
  48831. return results;
  48832. };
  48833. var mipmapGenerator = null;
  48834. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  48835. // if (!this._noMipmap &&
  48836. // this._usePMREMGenerator) {
  48837. // mipmapGenerator = (data: ArrayBufferView[]) => {
  48838. // // Custom setup of the generator matching with the PBR shader values.
  48839. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  48840. // this._size,
  48841. // this._size,
  48842. // 0,
  48843. // 3,
  48844. // this.getScene().getEngine().getCaps().textureFloat,
  48845. // 2048,
  48846. // 0.25,
  48847. // false,
  48848. // true);
  48849. // return generator.filterCubeMap();
  48850. // };
  48851. // }
  48852. 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);
  48853. };
  48854. /**
  48855. * Starts the loading process of the texture.
  48856. */
  48857. HDRCubeTexture.prototype.loadTexture = function () {
  48858. if (this._isBABYLONPreprocessed) {
  48859. this.loadBabylonTexture();
  48860. }
  48861. else {
  48862. this.loadHDRTexture();
  48863. }
  48864. };
  48865. HDRCubeTexture.prototype.clone = function () {
  48866. var size = this._isBABYLONPreprocessed ? null : this._size;
  48867. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  48868. // Base texture
  48869. newTexture.level = this.level;
  48870. newTexture.wrapU = this.wrapU;
  48871. newTexture.wrapV = this.wrapV;
  48872. newTexture.coordinatesIndex = this.coordinatesIndex;
  48873. newTexture.coordinatesMode = this.coordinatesMode;
  48874. return newTexture;
  48875. };
  48876. // Methods
  48877. HDRCubeTexture.prototype.delayLoad = function () {
  48878. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  48879. return;
  48880. }
  48881. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  48882. this._texture = this._getFromCache(this.url, this._noMipmap);
  48883. if (!this._texture) {
  48884. this.loadTexture();
  48885. }
  48886. };
  48887. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  48888. return this._textureMatrix;
  48889. };
  48890. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  48891. this._textureMatrix = value;
  48892. };
  48893. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  48894. var texture = null;
  48895. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  48896. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  48897. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  48898. texture.name = parsedTexture.name;
  48899. texture.hasAlpha = parsedTexture.hasAlpha;
  48900. texture.level = parsedTexture.level;
  48901. texture.coordinatesMode = parsedTexture.coordinatesMode;
  48902. texture.isBlocking = parsedTexture.isBlocking;
  48903. }
  48904. return texture;
  48905. };
  48906. HDRCubeTexture.prototype.serialize = function () {
  48907. if (!this.name) {
  48908. return null;
  48909. }
  48910. var serializationObject = {};
  48911. serializationObject.name = this.name;
  48912. serializationObject.hasAlpha = this.hasAlpha;
  48913. serializationObject.isCube = true;
  48914. serializationObject.level = this.level;
  48915. serializationObject.size = this._size;
  48916. serializationObject.coordinatesMode = this.coordinatesMode;
  48917. serializationObject.useInGammaSpace = this._useInGammaSpace;
  48918. serializationObject.generateHarmonics = this._generateHarmonics;
  48919. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  48920. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  48921. serializationObject.customType = "BABYLON.HDRCubeTexture";
  48922. serializationObject.noMipmap = this._noMipmap;
  48923. serializationObject.isBlocking = this._isBlocking;
  48924. return serializationObject;
  48925. };
  48926. /**
  48927. * Saves as a file the data contained in the texture in a binary format.
  48928. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  48929. * as the spherical used in the lighting.
  48930. * @param url The HDR file url.
  48931. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  48932. * @param onError Method called if any error happens during download.
  48933. * @return The packed binary data.
  48934. */
  48935. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  48936. if (onError === void 0) { onError = null; }
  48937. var callback = function (buffer) {
  48938. var data = new Blob([buffer], { type: 'application/octet-stream' });
  48939. // Returns a URL you can use as a href.
  48940. var objUrl = window.URL.createObjectURL(data);
  48941. // Simulates a link to it and click to dowload.
  48942. var a = document.createElement("a");
  48943. document.body.appendChild(a);
  48944. a.style.display = "none";
  48945. a.href = objUrl;
  48946. a.download = "envmap.babylon.hdr";
  48947. a.click();
  48948. };
  48949. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  48950. };
  48951. /**
  48952. * Serializes the data contained in the texture in a binary format.
  48953. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  48954. * as the spherical used in the lighting.
  48955. * @param url The HDR file url.
  48956. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  48957. * @param onError Method called if any error happens during download.
  48958. * @return The packed binary data.
  48959. */
  48960. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  48961. if (onError === void 0) { onError = null; }
  48962. // Needs the url tho create the texture.
  48963. if (!url) {
  48964. return null;
  48965. }
  48966. // Check Power of two size.
  48967. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  48968. return null;
  48969. }
  48970. // Coming Back in 3.1.
  48971. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  48972. return null;
  48973. };
  48974. HDRCubeTexture._facesMapping = [
  48975. "right",
  48976. "left",
  48977. "up",
  48978. "down",
  48979. "front",
  48980. "back"
  48981. ];
  48982. return HDRCubeTexture;
  48983. }(BABYLON.BaseTexture));
  48984. BABYLON.HDRCubeTexture = HDRCubeTexture;
  48985. })(BABYLON || (BABYLON = {}));
  48986. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  48987. var BABYLON;
  48988. (function (BABYLON) {
  48989. var DefaultLoadingScreen = (function () {
  48990. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  48991. if (_loadingText === void 0) { _loadingText = ""; }
  48992. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  48993. var _this = this;
  48994. this._renderingCanvas = _renderingCanvas;
  48995. this._loadingText = _loadingText;
  48996. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  48997. // Resize
  48998. this._resizeLoadingUI = function () {
  48999. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  49000. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  49001. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  49002. _this._loadingDiv.style.left = canvasRect.left + "px";
  49003. _this._loadingDiv.style.top = canvasRect.top + "px";
  49004. _this._loadingDiv.style.width = canvasRect.width + "px";
  49005. _this._loadingDiv.style.height = canvasRect.height + "px";
  49006. };
  49007. }
  49008. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  49009. if (this._loadingDiv) {
  49010. // Do not add a loading screen if there is already one
  49011. return;
  49012. }
  49013. this._loadingDiv = document.createElement("div");
  49014. this._loadingDiv.id = "babylonjsLoadingDiv";
  49015. this._loadingDiv.style.opacity = "0";
  49016. this._loadingDiv.style.transition = "opacity 1.5s ease";
  49017. // Loading text
  49018. this._loadingTextDiv = document.createElement("div");
  49019. this._loadingTextDiv.style.position = "absolute";
  49020. this._loadingTextDiv.style.left = "0";
  49021. this._loadingTextDiv.style.top = "50%";
  49022. this._loadingTextDiv.style.marginTop = "80px";
  49023. this._loadingTextDiv.style.width = "100%";
  49024. this._loadingTextDiv.style.height = "20px";
  49025. this._loadingTextDiv.style.fontFamily = "Arial";
  49026. this._loadingTextDiv.style.fontSize = "14px";
  49027. this._loadingTextDiv.style.color = "white";
  49028. this._loadingTextDiv.style.textAlign = "center";
  49029. this._loadingTextDiv.innerHTML = "Loading";
  49030. this._loadingDiv.appendChild(this._loadingTextDiv);
  49031. //set the predefined text
  49032. this._loadingTextDiv.innerHTML = this._loadingText;
  49033. // Generating keyframes
  49034. var style = document.createElement('style');
  49035. style.type = 'text/css';
  49036. 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 }";
  49037. style.innerHTML = keyFrames;
  49038. document.getElementsByTagName('head')[0].appendChild(style);
  49039. // Loading img
  49040. var imgBack = new Image();
  49041. 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";
  49042. imgBack.style.position = "absolute";
  49043. imgBack.style.left = "50%";
  49044. imgBack.style.top = "50%";
  49045. imgBack.style.marginLeft = "-60px";
  49046. imgBack.style.marginTop = "-60px";
  49047. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  49048. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  49049. imgBack.style.transformOrigin = "50% 50%";
  49050. imgBack.style.webkitTransformOrigin = "50% 50%";
  49051. this._loadingDiv.appendChild(imgBack);
  49052. this._resizeLoadingUI();
  49053. window.addEventListener("resize", this._resizeLoadingUI);
  49054. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  49055. document.body.appendChild(this._loadingDiv);
  49056. this._loadingDiv.style.opacity = "1";
  49057. };
  49058. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  49059. var _this = this;
  49060. if (!this._loadingDiv) {
  49061. return;
  49062. }
  49063. var onTransitionEnd = function () {
  49064. if (!_this._loadingDiv) {
  49065. return;
  49066. }
  49067. document.body.removeChild(_this._loadingDiv);
  49068. window.removeEventListener("resize", _this._resizeLoadingUI);
  49069. _this._loadingDiv = null;
  49070. };
  49071. this._loadingDiv.style.opacity = "0";
  49072. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  49073. };
  49074. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  49075. set: function (text) {
  49076. this._loadingText = text;
  49077. if (this._loadingTextDiv) {
  49078. this._loadingTextDiv.innerHTML = this._loadingText;
  49079. }
  49080. },
  49081. enumerable: true,
  49082. configurable: true
  49083. });
  49084. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  49085. get: function () {
  49086. return this._loadingDivBackgroundColor;
  49087. },
  49088. set: function (color) {
  49089. this._loadingDivBackgroundColor = color;
  49090. if (!this._loadingDiv) {
  49091. return;
  49092. }
  49093. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  49094. },
  49095. enumerable: true,
  49096. configurable: true
  49097. });
  49098. return DefaultLoadingScreen;
  49099. }());
  49100. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  49101. })(BABYLON || (BABYLON = {}));
  49102. //# sourceMappingURL=babylon.loadingScreen.js.map
  49103. var BABYLON;
  49104. (function (BABYLON) {
  49105. var SceneLoader = (function () {
  49106. function SceneLoader() {
  49107. }
  49108. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  49109. get: function () {
  49110. return 0;
  49111. },
  49112. enumerable: true,
  49113. configurable: true
  49114. });
  49115. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  49116. get: function () {
  49117. return 1;
  49118. },
  49119. enumerable: true,
  49120. configurable: true
  49121. });
  49122. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  49123. get: function () {
  49124. return 2;
  49125. },
  49126. enumerable: true,
  49127. configurable: true
  49128. });
  49129. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  49130. get: function () {
  49131. return 3;
  49132. },
  49133. enumerable: true,
  49134. configurable: true
  49135. });
  49136. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  49137. get: function () {
  49138. return SceneLoader._ForceFullSceneLoadingForIncremental;
  49139. },
  49140. set: function (value) {
  49141. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  49142. },
  49143. enumerable: true,
  49144. configurable: true
  49145. });
  49146. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  49147. get: function () {
  49148. return SceneLoader._ShowLoadingScreen;
  49149. },
  49150. set: function (value) {
  49151. SceneLoader._ShowLoadingScreen = value;
  49152. },
  49153. enumerable: true,
  49154. configurable: true
  49155. });
  49156. Object.defineProperty(SceneLoader, "loggingLevel", {
  49157. get: function () {
  49158. return SceneLoader._loggingLevel;
  49159. },
  49160. set: function (value) {
  49161. SceneLoader._loggingLevel = value;
  49162. },
  49163. enumerable: true,
  49164. configurable: true
  49165. });
  49166. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  49167. get: function () {
  49168. return SceneLoader._CleanBoneMatrixWeights;
  49169. },
  49170. set: function (value) {
  49171. SceneLoader._CleanBoneMatrixWeights = value;
  49172. },
  49173. enumerable: true,
  49174. configurable: true
  49175. });
  49176. SceneLoader._getDefaultPlugin = function () {
  49177. return SceneLoader._registeredPlugins[".babylon"];
  49178. };
  49179. SceneLoader._getPluginForExtension = function (extension) {
  49180. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  49181. if (registeredPlugin) {
  49182. return registeredPlugin;
  49183. }
  49184. return SceneLoader._getDefaultPlugin();
  49185. };
  49186. SceneLoader._getPluginForDirectLoad = function (data) {
  49187. for (var extension in SceneLoader._registeredPlugins) {
  49188. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  49189. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  49190. return SceneLoader._registeredPlugins[extension];
  49191. }
  49192. }
  49193. return SceneLoader._getDefaultPlugin();
  49194. };
  49195. SceneLoader._getPluginForFilename = function (sceneFilename) {
  49196. if (sceneFilename.name) {
  49197. sceneFilename = sceneFilename.name;
  49198. }
  49199. var dotPosition = sceneFilename.lastIndexOf(".");
  49200. var queryStringPosition = sceneFilename.indexOf("?");
  49201. if (queryStringPosition === -1) {
  49202. queryStringPosition = sceneFilename.length;
  49203. }
  49204. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  49205. return SceneLoader._getPluginForExtension(extension);
  49206. };
  49207. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  49208. SceneLoader._getDirectLoad = function (sceneFilename) {
  49209. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  49210. return sceneFilename.substr(5);
  49211. }
  49212. return null;
  49213. };
  49214. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49215. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  49216. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  49217. var plugin = registeredPlugin.plugin;
  49218. var useArrayBuffer = registeredPlugin.isBinary;
  49219. var database;
  49220. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  49221. var dataCallback = function (data) {
  49222. if (scene.isDisposed) {
  49223. onError("Scene has been disposed");
  49224. return;
  49225. }
  49226. scene.database = database;
  49227. try {
  49228. onSuccess(plugin, data);
  49229. }
  49230. catch (e) {
  49231. onError(null, e);
  49232. }
  49233. };
  49234. var manifestChecked = function (success) {
  49235. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  49236. onError(request.status + " " + request.statusText);
  49237. });
  49238. };
  49239. if (directLoad) {
  49240. dataCallback(directLoad);
  49241. return;
  49242. }
  49243. if (rootUrl.indexOf("file:") === -1) {
  49244. if (scene.getEngine().enableOfflineSupport) {
  49245. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  49246. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  49247. }
  49248. else {
  49249. manifestChecked(true);
  49250. }
  49251. }
  49252. else {
  49253. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  49254. }
  49255. };
  49256. // Public functions
  49257. SceneLoader.GetPluginForExtension = function (extension) {
  49258. return SceneLoader._getPluginForExtension(extension).plugin;
  49259. };
  49260. SceneLoader.RegisterPlugin = function (plugin) {
  49261. if (typeof plugin.extensions === "string") {
  49262. var extension = plugin.extensions;
  49263. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  49264. plugin: plugin,
  49265. isBinary: false
  49266. };
  49267. }
  49268. else {
  49269. var extensions = plugin.extensions;
  49270. Object.keys(extensions).forEach(function (extension) {
  49271. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  49272. plugin: plugin,
  49273. isBinary: extensions[extension].isBinary
  49274. };
  49275. });
  49276. }
  49277. };
  49278. /**
  49279. * Import meshes into a scene
  49280. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  49281. * @param rootUrl a string that defines the root url for scene and resources
  49282. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49283. * @param scene the instance of BABYLON.Scene to append to
  49284. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  49285. * @param onProgress a callback with a progress event for each file being loaded
  49286. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49287. */
  49288. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49289. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  49290. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  49291. return;
  49292. }
  49293. var loadingToken = {};
  49294. scene._addPendingData(loadingToken);
  49295. var errorHandler = function (message, exception) {
  49296. if (onError) {
  49297. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  49298. }
  49299. scene._removePendingData(loadingToken);
  49300. };
  49301. var progressHandler = function (event) {
  49302. if (onProgress) {
  49303. onProgress(event);
  49304. }
  49305. };
  49306. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  49307. if (plugin.importMesh) {
  49308. var syncedPlugin = plugin;
  49309. var meshes = [];
  49310. var particleSystems = [];
  49311. var skeletons = [];
  49312. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  49313. return;
  49314. }
  49315. if (onSuccess) {
  49316. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  49317. onSuccess(meshes, particleSystems, skeletons);
  49318. scene._removePendingData(loadingToken);
  49319. }
  49320. }
  49321. else {
  49322. var asyncedPlugin = plugin;
  49323. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  49324. if (onSuccess) {
  49325. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  49326. onSuccess(meshes, particleSystems, skeletons);
  49327. scene._removePendingData(loadingToken);
  49328. }
  49329. }, progressHandler, errorHandler);
  49330. }
  49331. }, progressHandler, errorHandler);
  49332. };
  49333. /**
  49334. * Load a scene
  49335. * @param rootUrl a string that defines the root url for scene and resources
  49336. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49337. * @param engine is the instance of BABYLON.Engine to use to create the scene
  49338. * @param onSuccess a callback with the scene when import succeeds
  49339. * @param onProgress a callback with a progress event for each file being loaded
  49340. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49341. */
  49342. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  49343. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  49344. };
  49345. /**
  49346. * Append a scene
  49347. * @param rootUrl a string that defines the root url for scene and resources
  49348. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49349. * @param scene is the instance of BABYLON.Scene to append to
  49350. * @param onSuccess a callback with the scene when import succeeds
  49351. * @param onProgress a callback with a progress event for each file being loaded
  49352. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49353. */
  49354. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49355. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  49356. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  49357. return;
  49358. }
  49359. if (SceneLoader.ShowLoadingScreen) {
  49360. scene.getEngine().displayLoadingUI();
  49361. }
  49362. var loadingToken = {};
  49363. scene._addPendingData(loadingToken);
  49364. var errorHandler = function (message, exception) {
  49365. if (onError) {
  49366. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  49367. }
  49368. scene._removePendingData(loadingToken);
  49369. scene.getEngine().hideLoadingUI();
  49370. };
  49371. var progressHandler = function (event) {
  49372. if (onProgress) {
  49373. onProgress(event);
  49374. }
  49375. };
  49376. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  49377. if (plugin.load) {
  49378. var syncedPlugin = plugin;
  49379. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  49380. return;
  49381. }
  49382. if (onSuccess) {
  49383. onSuccess(scene);
  49384. }
  49385. scene.loadingPluginName = plugin.name;
  49386. scene._removePendingData(loadingToken);
  49387. }
  49388. else {
  49389. var asyncedPlugin = plugin;
  49390. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  49391. if (onSuccess) {
  49392. onSuccess(scene);
  49393. }
  49394. scene.loadingPluginName = plugin.name;
  49395. scene._removePendingData(loadingToken);
  49396. }, progressHandler, errorHandler);
  49397. }
  49398. if (SceneLoader.ShowLoadingScreen) {
  49399. scene.executeWhenReady(function () {
  49400. scene.getEngine().hideLoadingUI();
  49401. });
  49402. }
  49403. }, progressHandler, errorHandler);
  49404. };
  49405. // Flags
  49406. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  49407. SceneLoader._ShowLoadingScreen = true;
  49408. SceneLoader._CleanBoneMatrixWeights = false;
  49409. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  49410. // Members
  49411. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  49412. SceneLoader._registeredPlugins = {};
  49413. return SceneLoader;
  49414. }());
  49415. BABYLON.SceneLoader = SceneLoader;
  49416. ;
  49417. })(BABYLON || (BABYLON = {}));
  49418. //# sourceMappingURL=babylon.sceneLoader.js.map
  49419. var BABYLON;
  49420. (function (BABYLON) {
  49421. var Internals;
  49422. (function (Internals) {
  49423. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  49424. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49425. var parsedMaterial = parsedData.materials[index];
  49426. if (parsedMaterial.id === id) {
  49427. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49428. }
  49429. }
  49430. return null;
  49431. };
  49432. var isDescendantOf = function (mesh, names, hierarchyIds) {
  49433. for (var i in names) {
  49434. if (mesh.name === names[i]) {
  49435. hierarchyIds.push(mesh.id);
  49436. return true;
  49437. }
  49438. }
  49439. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  49440. hierarchyIds.push(mesh.id);
  49441. return true;
  49442. }
  49443. return false;
  49444. };
  49445. var logOperation = function (operation, producer) {
  49446. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  49447. };
  49448. BABYLON.SceneLoader.RegisterPlugin({
  49449. name: "babylon.js",
  49450. extensions: ".babylon",
  49451. canDirectLoad: function (data) {
  49452. if (data.indexOf("babylon") !== -1) {
  49453. return true;
  49454. }
  49455. return false;
  49456. },
  49457. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  49458. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49459. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49460. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49461. // and avoid problems with multiple concurrent .babylon loads.
  49462. var log = "importMesh has failed JSON parse";
  49463. try {
  49464. var parsedData = JSON.parse(data);
  49465. log = "";
  49466. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49467. if (!meshesNames) {
  49468. meshesNames = null;
  49469. }
  49470. else if (!Array.isArray(meshesNames)) {
  49471. meshesNames = [meshesNames];
  49472. }
  49473. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49474. var loadedSkeletonsIds = [];
  49475. var loadedMaterialsIds = [];
  49476. var hierarchyIds = [];
  49477. var index;
  49478. var cache;
  49479. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49480. var parsedMesh = parsedData.meshes[index];
  49481. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  49482. if (meshesNames !== null) {
  49483. // Remove found mesh name from list.
  49484. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  49485. }
  49486. //Geometry?
  49487. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  49488. //does the file contain geometries?
  49489. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  49490. //find the correct geometry and add it to the scene
  49491. var found = false;
  49492. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  49493. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  49494. return;
  49495. }
  49496. else {
  49497. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  49498. if (parsedGeometryData.id === parsedMesh.geometryId) {
  49499. switch (geometryType) {
  49500. case "boxes":
  49501. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  49502. break;
  49503. case "spheres":
  49504. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  49505. break;
  49506. case "cylinders":
  49507. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  49508. break;
  49509. case "toruses":
  49510. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  49511. break;
  49512. case "grounds":
  49513. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  49514. break;
  49515. case "planes":
  49516. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  49517. break;
  49518. case "torusKnots":
  49519. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  49520. break;
  49521. case "vertexData":
  49522. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  49523. break;
  49524. }
  49525. found = true;
  49526. }
  49527. });
  49528. }
  49529. });
  49530. if (found === false) {
  49531. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  49532. }
  49533. }
  49534. }
  49535. // Material ?
  49536. if (parsedMesh.materialId) {
  49537. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  49538. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49539. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  49540. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  49541. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  49542. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  49543. var subMatId = parsedMultiMaterial.materials[matIndex];
  49544. loadedMaterialsIds.push(subMatId);
  49545. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  49546. log += "\n\tMaterial " + mat.toString(fullDetails);
  49547. }
  49548. loadedMaterialsIds.push(parsedMultiMaterial.id);
  49549. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49550. materialFound = true;
  49551. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  49552. break;
  49553. }
  49554. }
  49555. }
  49556. if (materialFound === false) {
  49557. loadedMaterialsIds.push(parsedMesh.materialId);
  49558. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  49559. if (!mat) {
  49560. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  49561. }
  49562. else {
  49563. log += "\n\tMaterial " + mat.toString(fullDetails);
  49564. }
  49565. }
  49566. }
  49567. // Skeleton ?
  49568. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49569. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  49570. if (skeletonAlreadyLoaded === false) {
  49571. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  49572. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  49573. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  49574. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49575. skeletons.push(skeleton);
  49576. loadedSkeletonsIds.push(parsedSkeleton.id);
  49577. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  49578. }
  49579. }
  49580. }
  49581. }
  49582. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49583. meshes.push(mesh);
  49584. log += "\n\tMesh " + mesh.toString(fullDetails);
  49585. }
  49586. }
  49587. // Connecting parents
  49588. var currentMesh;
  49589. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49590. currentMesh = scene.meshes[index];
  49591. if (currentMesh._waitingParentId) {
  49592. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  49593. currentMesh._waitingParentId = undefined;
  49594. }
  49595. }
  49596. // freeze and compute world matrix application
  49597. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49598. currentMesh = scene.meshes[index];
  49599. if (currentMesh._waitingFreezeWorldMatrix) {
  49600. currentMesh.freezeWorldMatrix();
  49601. currentMesh._waitingFreezeWorldMatrix = undefined;
  49602. }
  49603. else {
  49604. currentMesh.computeWorldMatrix(true);
  49605. }
  49606. }
  49607. }
  49608. // Particles
  49609. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49610. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49611. var parsedParticleSystem = parsedData.particleSystems[index];
  49612. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  49613. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  49614. }
  49615. }
  49616. }
  49617. return true;
  49618. }
  49619. catch (err) {
  49620. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  49621. log = null;
  49622. throw err;
  49623. }
  49624. finally {
  49625. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49626. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49627. }
  49628. }
  49629. },
  49630. load: function (scene, data, rootUrl) {
  49631. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49632. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49633. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49634. // and avoid problems with multiple concurrent .babylon loads.
  49635. var log = "importScene has failed JSON parse";
  49636. try {
  49637. var parsedData = JSON.parse(data);
  49638. log = "";
  49639. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49640. // Scene
  49641. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  49642. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  49643. }
  49644. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  49645. scene.autoClear = parsedData.autoClear;
  49646. }
  49647. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  49648. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  49649. }
  49650. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  49651. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  49652. }
  49653. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  49654. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  49655. }
  49656. // Fog
  49657. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  49658. scene.fogMode = parsedData.fogMode;
  49659. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  49660. scene.fogStart = parsedData.fogStart;
  49661. scene.fogEnd = parsedData.fogEnd;
  49662. scene.fogDensity = parsedData.fogDensity;
  49663. log += "\tFog mode for scene: ";
  49664. switch (scene.fogMode) {
  49665. // getters not compiling, so using hardcoded
  49666. case 1:
  49667. log += "exp\n";
  49668. break;
  49669. case 2:
  49670. log += "exp2\n";
  49671. break;
  49672. case 3:
  49673. log += "linear\n";
  49674. break;
  49675. }
  49676. }
  49677. //Physics
  49678. if (parsedData.physicsEnabled) {
  49679. var physicsPlugin;
  49680. if (parsedData.physicsEngine === "cannon") {
  49681. physicsPlugin = new BABYLON.CannonJSPlugin();
  49682. }
  49683. else if (parsedData.physicsEngine === "oimo") {
  49684. physicsPlugin = new BABYLON.OimoJSPlugin();
  49685. }
  49686. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  49687. //else - default engine, which is currently oimo
  49688. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  49689. scene.enablePhysics(physicsGravity, physicsPlugin);
  49690. }
  49691. // Metadata
  49692. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  49693. scene.metadata = parsedData.metadata;
  49694. }
  49695. //collisions, if defined. otherwise, default is true
  49696. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  49697. scene.collisionsEnabled = parsedData.collisionsEnabled;
  49698. }
  49699. scene.workerCollisions = !!parsedData.workerCollisions;
  49700. var index;
  49701. var cache;
  49702. // Lights
  49703. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  49704. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  49705. var parsedLight = parsedData.lights[index];
  49706. var light = BABYLON.Light.Parse(parsedLight, scene);
  49707. log += (index === 0 ? "\n\tLights:" : "");
  49708. log += "\n\t\t" + light.toString(fullDetails);
  49709. }
  49710. }
  49711. // Animations
  49712. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  49713. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  49714. var parsedAnimation = parsedData.animations[index];
  49715. var animation = BABYLON.Animation.Parse(parsedAnimation);
  49716. scene.animations.push(animation);
  49717. log += (index === 0 ? "\n\tAnimations:" : "");
  49718. log += "\n\t\t" + animation.toString(fullDetails);
  49719. }
  49720. }
  49721. if (parsedData.autoAnimate) {
  49722. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  49723. }
  49724. // Materials
  49725. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  49726. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49727. var parsedMaterial = parsedData.materials[index];
  49728. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49729. log += (index === 0 ? "\n\tMaterials:" : "");
  49730. log += "\n\t\t" + mat.toString(fullDetails);
  49731. }
  49732. }
  49733. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49734. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  49735. var parsedMultiMaterial = parsedData.multiMaterials[index];
  49736. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49737. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  49738. log += "\n\t\t" + mmat.toString(fullDetails);
  49739. }
  49740. }
  49741. // Morph targets
  49742. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  49743. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  49744. var managerData = _a[_i];
  49745. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  49746. }
  49747. }
  49748. // Skeletons
  49749. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49750. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  49751. var parsedSkeleton = parsedData.skeletons[index];
  49752. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49753. log += (index === 0 ? "\n\tSkeletons:" : "");
  49754. log += "\n\t\t" + skeleton.toString(fullDetails);
  49755. }
  49756. }
  49757. // Geometries
  49758. var geometries = parsedData.geometries;
  49759. if (geometries !== undefined && geometries !== null) {
  49760. // Boxes
  49761. var boxes = geometries.boxes;
  49762. if (boxes !== undefined && boxes !== null) {
  49763. for (index = 0, cache = boxes.length; index < cache; index++) {
  49764. var parsedBox = boxes[index];
  49765. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  49766. }
  49767. }
  49768. // Spheres
  49769. var spheres = geometries.spheres;
  49770. if (spheres !== undefined && spheres !== null) {
  49771. for (index = 0, cache = spheres.length; index < cache; index++) {
  49772. var parsedSphere = spheres[index];
  49773. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  49774. }
  49775. }
  49776. // Cylinders
  49777. var cylinders = geometries.cylinders;
  49778. if (cylinders !== undefined && cylinders !== null) {
  49779. for (index = 0, cache = cylinders.length; index < cache; index++) {
  49780. var parsedCylinder = cylinders[index];
  49781. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  49782. }
  49783. }
  49784. // Toruses
  49785. var toruses = geometries.toruses;
  49786. if (toruses !== undefined && toruses !== null) {
  49787. for (index = 0, cache = toruses.length; index < cache; index++) {
  49788. var parsedTorus = toruses[index];
  49789. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  49790. }
  49791. }
  49792. // Grounds
  49793. var grounds = geometries.grounds;
  49794. if (grounds !== undefined && grounds !== null) {
  49795. for (index = 0, cache = grounds.length; index < cache; index++) {
  49796. var parsedGround = grounds[index];
  49797. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  49798. }
  49799. }
  49800. // Planes
  49801. var planes = geometries.planes;
  49802. if (planes !== undefined && planes !== null) {
  49803. for (index = 0, cache = planes.length; index < cache; index++) {
  49804. var parsedPlane = planes[index];
  49805. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  49806. }
  49807. }
  49808. // TorusKnots
  49809. var torusKnots = geometries.torusKnots;
  49810. if (torusKnots !== undefined && torusKnots !== null) {
  49811. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  49812. var parsedTorusKnot = torusKnots[index];
  49813. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  49814. }
  49815. }
  49816. // VertexData
  49817. var vertexData = geometries.vertexData;
  49818. if (vertexData !== undefined && vertexData !== null) {
  49819. for (index = 0, cache = vertexData.length; index < cache; index++) {
  49820. var parsedVertexData = vertexData[index];
  49821. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  49822. }
  49823. }
  49824. }
  49825. // Meshes
  49826. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49827. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49828. var parsedMesh = parsedData.meshes[index];
  49829. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49830. log += (index === 0 ? "\n\tMeshes:" : "");
  49831. log += "\n\t\t" + mesh.toString(fullDetails);
  49832. }
  49833. }
  49834. // Cameras
  49835. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  49836. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  49837. var parsedCamera = parsedData.cameras[index];
  49838. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  49839. log += (index === 0 ? "\n\tCameras:" : "");
  49840. log += "\n\t\t" + camera.toString(fullDetails);
  49841. }
  49842. }
  49843. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  49844. scene.setActiveCameraByID(parsedData.activeCameraID);
  49845. }
  49846. // Browsing all the graph to connect the dots
  49847. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  49848. var camera = scene.cameras[index];
  49849. if (camera._waitingParentId) {
  49850. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  49851. camera._waitingParentId = undefined;
  49852. }
  49853. }
  49854. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49855. var light = scene.lights[index];
  49856. if (light._waitingParentId) {
  49857. light.parent = scene.getLastEntryByID(light._waitingParentId);
  49858. light._waitingParentId = undefined;
  49859. }
  49860. }
  49861. // Sounds
  49862. var loadedSounds = [];
  49863. var loadedSound;
  49864. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  49865. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  49866. var parsedSound = parsedData.sounds[index];
  49867. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49868. if (!parsedSound.url)
  49869. parsedSound.url = parsedSound.name;
  49870. if (!loadedSounds[parsedSound.url]) {
  49871. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  49872. loadedSounds[parsedSound.url] = loadedSound;
  49873. }
  49874. else {
  49875. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  49876. }
  49877. }
  49878. else {
  49879. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  49880. }
  49881. }
  49882. }
  49883. loadedSounds = [];
  49884. // Connect parents & children and parse actions
  49885. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49886. var mesh = scene.meshes[index];
  49887. if (mesh._waitingParentId) {
  49888. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  49889. mesh._waitingParentId = undefined;
  49890. }
  49891. if (mesh._waitingActions) {
  49892. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  49893. mesh._waitingActions = undefined;
  49894. }
  49895. }
  49896. // freeze world matrix application
  49897. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49898. var currentMesh = scene.meshes[index];
  49899. if (currentMesh._waitingFreezeWorldMatrix) {
  49900. currentMesh.freezeWorldMatrix();
  49901. currentMesh._waitingFreezeWorldMatrix = undefined;
  49902. }
  49903. else {
  49904. currentMesh.computeWorldMatrix(true);
  49905. }
  49906. }
  49907. // Particles Systems
  49908. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49909. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49910. var parsedParticleSystem = parsedData.particleSystems[index];
  49911. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  49912. }
  49913. }
  49914. // Lens flares
  49915. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  49916. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  49917. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  49918. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  49919. }
  49920. }
  49921. // Shadows
  49922. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  49923. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  49924. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  49925. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  49926. }
  49927. }
  49928. // Lights exclusions / inclusions
  49929. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49930. var light = scene.lights[index];
  49931. // Excluded check
  49932. if (light._excludedMeshesIds.length > 0) {
  49933. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  49934. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  49935. if (excludedMesh) {
  49936. light.excludedMeshes.push(excludedMesh);
  49937. }
  49938. }
  49939. light._excludedMeshesIds = [];
  49940. }
  49941. // Included check
  49942. if (light._includedOnlyMeshesIds.length > 0) {
  49943. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  49944. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  49945. if (includedOnlyMesh) {
  49946. light.includedOnlyMeshes.push(includedOnlyMesh);
  49947. }
  49948. }
  49949. light._includedOnlyMeshesIds = [];
  49950. }
  49951. }
  49952. // Actions (scene)
  49953. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  49954. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  49955. }
  49956. // Finish
  49957. return true;
  49958. }
  49959. catch (err) {
  49960. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  49961. log = null;
  49962. throw err;
  49963. }
  49964. finally {
  49965. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49966. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49967. }
  49968. }
  49969. }
  49970. });
  49971. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49972. })(BABYLON || (BABYLON = {}));
  49973. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  49974. var BABYLON;
  49975. (function (BABYLON) {
  49976. var FilesInput = (function () {
  49977. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  49978. this._engine = engine;
  49979. this._currentScene = scene;
  49980. this._sceneLoadedCallback = sceneLoadedCallback;
  49981. this._progressCallback = progressCallback;
  49982. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  49983. this._textureLoadingCallback = textureLoadingCallback;
  49984. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  49985. this._onReloadCallback = onReloadCallback;
  49986. }
  49987. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  49988. var _this = this;
  49989. if (elementToMonitor) {
  49990. this._elementToMonitor = elementToMonitor;
  49991. this._dragEnterHandler = function (e) { _this.drag(e); };
  49992. this._dragOverHandler = function (e) { _this.drag(e); };
  49993. this._dropHandler = function (e) { _this.drop(e); };
  49994. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  49995. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  49996. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  49997. }
  49998. };
  49999. FilesInput.prototype.dispose = function () {
  50000. if (!this._elementToMonitor) {
  50001. return;
  50002. }
  50003. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  50004. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  50005. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  50006. };
  50007. FilesInput.prototype.renderFunction = function () {
  50008. if (this._additionalRenderLoopLogicCallback) {
  50009. this._additionalRenderLoopLogicCallback();
  50010. }
  50011. if (this._currentScene) {
  50012. if (this._textureLoadingCallback) {
  50013. var remaining = this._currentScene.getWaitingItemsCount();
  50014. if (remaining > 0) {
  50015. this._textureLoadingCallback(remaining);
  50016. }
  50017. }
  50018. this._currentScene.render();
  50019. }
  50020. };
  50021. FilesInput.prototype.drag = function (e) {
  50022. e.stopPropagation();
  50023. e.preventDefault();
  50024. };
  50025. FilesInput.prototype.drop = function (eventDrop) {
  50026. eventDrop.stopPropagation();
  50027. eventDrop.preventDefault();
  50028. this.loadFiles(eventDrop);
  50029. };
  50030. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  50031. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  50032. reader.readEntries(function (fileEntries) {
  50033. var remaining = fileEntries.length;
  50034. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  50035. var fileEntry = fileEntries_1[_i];
  50036. if (fileEntry.isFile) {
  50037. fileEntry.file(function (file) {
  50038. file.correctName = relativePath + file.name;
  50039. files.push(file);
  50040. remaining--;
  50041. if (remaining === 0) {
  50042. callback();
  50043. }
  50044. });
  50045. }
  50046. else {
  50047. remaining--;
  50048. if (remaining === 0) {
  50049. callback();
  50050. }
  50051. }
  50052. }
  50053. });
  50054. };
  50055. FilesInput.prototype._processFiles = function (files) {
  50056. for (var i = 0; i < files.length; i++) {
  50057. var name = files[i].correctName.toLowerCase();
  50058. var extension = name.split('.').pop();
  50059. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  50060. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  50061. this._sceneFileToLoad = files[i];
  50062. }
  50063. else {
  50064. FilesInput.FilesToLoad[name] = files[i];
  50065. }
  50066. }
  50067. if (this._onReloadCallback) {
  50068. this._onReloadCallback(this._sceneFileToLoad);
  50069. }
  50070. else {
  50071. this.reload();
  50072. }
  50073. };
  50074. FilesInput.prototype.loadFiles = function (event) {
  50075. var _this = this;
  50076. if (this._startingProcessingFilesCallback)
  50077. this._startingProcessingFilesCallback();
  50078. // Handling data transfer via drag'n'drop
  50079. if (event && event.dataTransfer && event.dataTransfer.files) {
  50080. this._filesToLoad = event.dataTransfer.files;
  50081. }
  50082. // Handling files from input files
  50083. if (event && event.target && event.target.files) {
  50084. this._filesToLoad = event.target.files;
  50085. }
  50086. if (this._filesToLoad && this._filesToLoad.length > 0) {
  50087. var files_1 = [];
  50088. var folders = [];
  50089. var items = event.dataTransfer ? event.dataTransfer.items : null;
  50090. for (var i = 0; i < this._filesToLoad.length; i++) {
  50091. var fileToLoad = this._filesToLoad[i];
  50092. var name_1 = fileToLoad.name.toLowerCase();
  50093. var type = fileToLoad.type;
  50094. var entry = void 0;
  50095. fileToLoad.correctName = name_1;
  50096. if (items) {
  50097. var item = items[i];
  50098. if (item.getAsEntry) {
  50099. entry = item.getAsEntry();
  50100. }
  50101. else if (item.webkitGetAsEntry) {
  50102. entry = item.webkitGetAsEntry();
  50103. }
  50104. }
  50105. if (!entry) {
  50106. files_1.push(fileToLoad);
  50107. }
  50108. else {
  50109. if (entry.isDirectory) {
  50110. folders.push(entry);
  50111. }
  50112. else {
  50113. files_1.push(fileToLoad);
  50114. }
  50115. }
  50116. }
  50117. if (folders.length === 0) {
  50118. this._processFiles(files_1);
  50119. }
  50120. else {
  50121. var remaining = folders.length;
  50122. // Extract folder content
  50123. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  50124. var folder = folders_1[_i];
  50125. this._handleFolderDrop(folder, files_1, function () {
  50126. remaining--;
  50127. if (remaining === 0) {
  50128. _this._processFiles(files_1);
  50129. }
  50130. });
  50131. }
  50132. }
  50133. }
  50134. };
  50135. FilesInput.prototype.reload = function () {
  50136. var _this = this;
  50137. // If a ".babylon" file has been provided
  50138. if (this._sceneFileToLoad) {
  50139. if (this._currentScene) {
  50140. if (BABYLON.Tools.errorsCount > 0) {
  50141. BABYLON.Tools.ClearLogCache();
  50142. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  50143. }
  50144. this._engine.stopRenderLoop();
  50145. this._currentScene.dispose();
  50146. }
  50147. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  50148. _this._currentScene = newScene;
  50149. if (_this._sceneLoadedCallback) {
  50150. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  50151. }
  50152. // Wait for textures and shaders to be ready
  50153. _this._currentScene.executeWhenReady(function () {
  50154. _this._engine.runRenderLoop(function () {
  50155. _this.renderFunction();
  50156. });
  50157. });
  50158. }, function (progress) {
  50159. if (_this._progressCallback) {
  50160. _this._progressCallback(progress);
  50161. }
  50162. });
  50163. }
  50164. else {
  50165. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  50166. }
  50167. };
  50168. FilesInput.FilesToLoad = new Array();
  50169. return FilesInput;
  50170. }());
  50171. BABYLON.FilesInput = FilesInput;
  50172. })(BABYLON || (BABYLON = {}));
  50173. //# sourceMappingURL=babylon.filesInput.js.map
  50174. var BABYLON;
  50175. (function (BABYLON) {
  50176. var FramingBehavior = (function () {
  50177. function FramingBehavior() {
  50178. this._mode = FramingBehavior.FitFrustumSidesMode;
  50179. this._radiusScale = 1.0;
  50180. this._positionScale = 0.5;
  50181. this._defaultElevation = 0.3;
  50182. this._elevationReturnTime = 1500;
  50183. this._elevationReturnWaitTime = 1000;
  50184. this._zoomStopsAnimation = false;
  50185. this._framingTime = 1500;
  50186. this._isPointerDown = false;
  50187. this._lastFrameTime = null;
  50188. this._lastInteractionTime = -Infinity;
  50189. // Framing control
  50190. this._animatables = new Array();
  50191. this._betaIsAnimating = false;
  50192. this._lastFrameRadius = 0;
  50193. }
  50194. Object.defineProperty(FramingBehavior.prototype, "name", {
  50195. get: function () {
  50196. return "Framing";
  50197. },
  50198. enumerable: true,
  50199. configurable: true
  50200. });
  50201. Object.defineProperty(FramingBehavior.prototype, "mode", {
  50202. /**
  50203. * Gets current mode used by the behavior.
  50204. */
  50205. get: function () {
  50206. return this._mode;
  50207. },
  50208. /**
  50209. * Sets the current mode used by the behavior
  50210. */
  50211. set: function (mode) {
  50212. this._mode = mode;
  50213. },
  50214. enumerable: true,
  50215. configurable: true
  50216. });
  50217. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  50218. /**
  50219. * Gets the scale applied to the radius
  50220. */
  50221. get: function () {
  50222. return this._radiusScale;
  50223. },
  50224. /**
  50225. * Sets the scale applied to the radius (1 by default)
  50226. */
  50227. set: function (radius) {
  50228. this._radiusScale = radius;
  50229. },
  50230. enumerable: true,
  50231. configurable: true
  50232. });
  50233. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  50234. /**
  50235. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  50236. */
  50237. get: function () {
  50238. return this._positionScale;
  50239. },
  50240. /**
  50241. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  50242. */
  50243. set: function (scale) {
  50244. this._positionScale = scale;
  50245. },
  50246. enumerable: true,
  50247. configurable: true
  50248. });
  50249. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  50250. /**
  50251. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  50252. * behaviour is triggered, in radians.
  50253. */
  50254. get: function () {
  50255. return this._defaultElevation;
  50256. },
  50257. /**
  50258. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  50259. * behaviour is triggered, in radians.
  50260. */
  50261. set: function (elevation) {
  50262. this._defaultElevation = elevation;
  50263. },
  50264. enumerable: true,
  50265. configurable: true
  50266. });
  50267. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  50268. /**
  50269. * Gets the time (in milliseconds) taken to return to the default beta position.
  50270. * Negative value indicates camera should not return to default.
  50271. */
  50272. get: function () {
  50273. return this._elevationReturnTime;
  50274. },
  50275. /**
  50276. * Sets the time (in milliseconds) taken to return to the default beta position.
  50277. * Negative value indicates camera should not return to default.
  50278. */
  50279. set: function (speed) {
  50280. this._elevationReturnTime = speed;
  50281. },
  50282. enumerable: true,
  50283. configurable: true
  50284. });
  50285. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  50286. /**
  50287. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  50288. */
  50289. get: function () {
  50290. return this._elevationReturnWaitTime;
  50291. },
  50292. /**
  50293. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  50294. */
  50295. set: function (time) {
  50296. this._elevationReturnWaitTime = time;
  50297. },
  50298. enumerable: true,
  50299. configurable: true
  50300. });
  50301. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  50302. /**
  50303. * Gets the flag that indicates if user zooming should stop animation.
  50304. */
  50305. get: function () {
  50306. return this._zoomStopsAnimation;
  50307. },
  50308. /**
  50309. * Sets the flag that indicates if user zooming should stop animation.
  50310. */
  50311. set: function (flag) {
  50312. this._zoomStopsAnimation = flag;
  50313. },
  50314. enumerable: true,
  50315. configurable: true
  50316. });
  50317. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  50318. /**
  50319. * Gets the transition time when framing the mesh, in milliseconds
  50320. */
  50321. get: function () {
  50322. return this._framingTime;
  50323. },
  50324. /**
  50325. * Sets the transition time when framing the mesh, in milliseconds
  50326. */
  50327. set: function (time) {
  50328. this._framingTime = time;
  50329. },
  50330. enumerable: true,
  50331. configurable: true
  50332. });
  50333. FramingBehavior.prototype.attach = function (camera) {
  50334. var _this = this;
  50335. this._attachedCamera = camera;
  50336. var scene = this._attachedCamera.getScene();
  50337. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  50338. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  50339. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50340. _this._isPointerDown = true;
  50341. return;
  50342. }
  50343. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  50344. _this._isPointerDown = false;
  50345. }
  50346. });
  50347. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  50348. if (mesh) {
  50349. _this.zoomOnMesh(mesh);
  50350. }
  50351. });
  50352. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50353. // Stop the animation if there is user interaction and the animation should stop for this interaction
  50354. _this._applyUserInteraction();
  50355. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  50356. // back to the default position after a given timeout
  50357. _this._maintainCameraAboveGround();
  50358. });
  50359. };
  50360. FramingBehavior.prototype.detach = function () {
  50361. var scene = this._attachedCamera.getScene();
  50362. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  50363. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50364. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50365. this._attachedCamera = null;
  50366. };
  50367. /**
  50368. * Targets the given mesh and updates zoom level accordingly.
  50369. * @param mesh The mesh to target.
  50370. * @param radius Optional. If a cached radius position already exists, overrides default.
  50371. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  50372. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  50373. */
  50374. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ) {
  50375. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  50376. mesh.computeWorldMatrix(true);
  50377. var boundingBox = mesh.getBoundingInfo().boundingBox;
  50378. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ);
  50379. };
  50380. /**
  50381. * Targets the given mesh and updates zoom level accordingly.
  50382. * @param mesh The mesh to target.
  50383. * @param radius Optional. If a cached radius position already exists, overrides default.
  50384. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  50385. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  50386. */
  50387. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ) {
  50388. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  50389. var zoomTarget;
  50390. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  50391. var bottom = minimumWorld.y;
  50392. var top = maximumWorld.y;
  50393. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  50394. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  50395. if (focusOnOriginXZ) {
  50396. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  50397. }
  50398. else {
  50399. var centerWorld = minimumWorld.add(radiusWorld);
  50400. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  50401. }
  50402. if (!this._vectorTransition) {
  50403. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  50404. }
  50405. this._betaIsAnimating = true;
  50406. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  50407. // sets the radius and lower radius bounds
  50408. // Small delta ensures camera is not always at lower zoom limit.
  50409. var delta = 0.1;
  50410. var radius = 0;
  50411. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  50412. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  50413. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  50414. radius = position;
  50415. }
  50416. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  50417. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  50418. if (this._attachedCamera.lowerRadiusLimit === null) {
  50419. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  50420. }
  50421. }
  50422. // transition to new radius
  50423. if (!this._radiusTransition) {
  50424. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  50425. }
  50426. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime));
  50427. };
  50428. /**
  50429. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  50430. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  50431. * frustum width.
  50432. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  50433. * to fully enclose the mesh in the viewing frustum.
  50434. */
  50435. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  50436. var size = maximumWorld.subtract(minimumWorld);
  50437. var boxVectorGlobalDiagonal = size.length();
  50438. var frustumSlope = this._getFrustumSlope();
  50439. // Formula for setting distance
  50440. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  50441. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  50442. // Horizon distance
  50443. var radius = radiusWithoutFraming * this._radiusScale;
  50444. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  50445. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  50446. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  50447. var camera = this._attachedCamera;
  50448. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  50449. // Don't exceed the requested limit
  50450. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  50451. }
  50452. // Don't exceed the upper radius limit
  50453. if (camera.upperRadiusLimit) {
  50454. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  50455. }
  50456. return distance;
  50457. };
  50458. /**
  50459. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  50460. * is automatically returned to its default position (expected to be above ground plane).
  50461. */
  50462. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  50463. var _this = this;
  50464. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  50465. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  50466. var limitBeta = Math.PI * 0.5;
  50467. // Bring the camera back up if below the ground plane
  50468. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  50469. this._betaIsAnimating = true;
  50470. //Transition to new position
  50471. this.stopAllAnimations();
  50472. if (!this._betaTransition) {
  50473. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  50474. }
  50475. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  50476. _this._clearAnimationLocks();
  50477. _this.stopAllAnimations();
  50478. }));
  50479. }
  50480. };
  50481. /**
  50482. * Returns the frustum slope based on the canvas ratio and camera FOV
  50483. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  50484. */
  50485. FramingBehavior.prototype._getFrustumSlope = function () {
  50486. // Calculate the viewport ratio
  50487. // Aspect Ratio is Height/Width.
  50488. var camera = this._attachedCamera;
  50489. var engine = camera.getScene().getEngine();
  50490. var aspectRatio = engine.getAspectRatio(camera);
  50491. // Camera FOV is the vertical field of view (top-bottom) in radians.
  50492. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  50493. var frustumSlopeY = Math.tan(camera.fov / 2);
  50494. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  50495. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  50496. // along the forward vector.
  50497. var frustumSlopeX = frustumSlopeY * aspectRatio;
  50498. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  50499. };
  50500. /**
  50501. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  50502. */
  50503. FramingBehavior.prototype._clearAnimationLocks = function () {
  50504. this._betaIsAnimating = false;
  50505. };
  50506. /**
  50507. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  50508. */
  50509. FramingBehavior.prototype._applyUserInteraction = function () {
  50510. if (this.isUserIsMoving) {
  50511. this._lastInteractionTime = BABYLON.Tools.Now;
  50512. this.stopAllAnimations();
  50513. this._clearAnimationLocks();
  50514. }
  50515. };
  50516. /**
  50517. * Stops and removes all animations that have been applied to the camera
  50518. */
  50519. FramingBehavior.prototype.stopAllAnimations = function () {
  50520. this._attachedCamera.animations = [];
  50521. while (this._animatables.length) {
  50522. if (this._animatables[0]) {
  50523. this._animatables[0].onAnimationEnd = null;
  50524. this._animatables[0].stop();
  50525. }
  50526. this._animatables.shift();
  50527. }
  50528. };
  50529. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  50530. /**
  50531. * Gets a value indicating if the user is moving the camera
  50532. */
  50533. get: function () {
  50534. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  50535. this._attachedCamera.inertialBetaOffset !== 0 ||
  50536. this._attachedCamera.inertialRadiusOffset !== 0 ||
  50537. this._attachedCamera.inertialPanningX !== 0 ||
  50538. this._attachedCamera.inertialPanningY !== 0 ||
  50539. this._isPointerDown;
  50540. },
  50541. enumerable: true,
  50542. configurable: true
  50543. });
  50544. /**
  50545. * The easing function used by animations
  50546. */
  50547. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  50548. /**
  50549. * The easing mode used by animations
  50550. */
  50551. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  50552. // Statics
  50553. /**
  50554. * The camera can move all the way towards the mesh.
  50555. */
  50556. FramingBehavior.IgnoreBoundsSizeMode = 0;
  50557. /**
  50558. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  50559. */
  50560. FramingBehavior.FitFrustumSidesMode = 1;
  50561. return FramingBehavior;
  50562. }());
  50563. BABYLON.FramingBehavior = FramingBehavior;
  50564. })(BABYLON || (BABYLON = {}));
  50565. //# sourceMappingURL=babylon.framingBehavior.js.map
  50566. var BABYLON;
  50567. (function (BABYLON) {
  50568. /**
  50569. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  50570. */
  50571. var BouncingBehavior = (function () {
  50572. function BouncingBehavior() {
  50573. /**
  50574. * The duration of the animation, in milliseconds
  50575. */
  50576. this.transitionDuration = 450;
  50577. /**
  50578. * Length of the distance animated by the transition when lower radius is reached
  50579. */
  50580. this.lowerRadiusTransitionRange = 2;
  50581. /**
  50582. * Length of the distance animated by the transition when upper radius is reached
  50583. */
  50584. this.upperRadiusTransitionRange = -2;
  50585. this._autoTransitionRange = false;
  50586. // Animations
  50587. this._radiusIsAnimating = false;
  50588. this._radiusBounceTransition = null;
  50589. this._animatables = new Array();
  50590. }
  50591. Object.defineProperty(BouncingBehavior.prototype, "name", {
  50592. get: function () {
  50593. return "Bouncing";
  50594. },
  50595. enumerable: true,
  50596. configurable: true
  50597. });
  50598. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  50599. /**
  50600. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  50601. */
  50602. get: function () {
  50603. return this._autoTransitionRange;
  50604. },
  50605. /**
  50606. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  50607. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  50608. */
  50609. set: function (value) {
  50610. var _this = this;
  50611. if (this._autoTransitionRange === value) {
  50612. return;
  50613. }
  50614. this._autoTransitionRange = value;
  50615. var camera = this._attachedCamera;
  50616. if (value) {
  50617. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  50618. if (!mesh) {
  50619. return;
  50620. }
  50621. mesh.computeWorldMatrix(true);
  50622. var diagonal = mesh.getBoundingInfo().diagonalLength;
  50623. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  50624. _this.upperRadiusTransitionRange = diagonal * 0.05;
  50625. });
  50626. }
  50627. else if (this._onMeshTargetChangedObserver) {
  50628. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50629. }
  50630. },
  50631. enumerable: true,
  50632. configurable: true
  50633. });
  50634. BouncingBehavior.prototype.attach = function (camera) {
  50635. var _this = this;
  50636. this._attachedCamera = camera;
  50637. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50638. // Add the bounce animation to the lower radius limit
  50639. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  50640. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  50641. }
  50642. // Add the bounce animation to the upper radius limit
  50643. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  50644. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  50645. }
  50646. });
  50647. };
  50648. BouncingBehavior.prototype.detach = function () {
  50649. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50650. if (this._onMeshTargetChangedObserver) {
  50651. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50652. }
  50653. this._attachedCamera = null;
  50654. };
  50655. /**
  50656. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  50657. * @param radiusLimit The limit to check against.
  50658. * @return Bool to indicate if at limit.
  50659. */
  50660. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  50661. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  50662. return true;
  50663. }
  50664. return false;
  50665. };
  50666. /**
  50667. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  50668. * @param radiusDelta The delta by which to animate to. Can be negative.
  50669. */
  50670. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  50671. var _this = this;
  50672. if (!this._radiusBounceTransition) {
  50673. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  50674. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  50675. }
  50676. // Prevent zoom until bounce has completed
  50677. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  50678. this._attachedCamera.wheelPrecision = Infinity;
  50679. this._attachedCamera.inertialRadiusOffset = 0;
  50680. // Animate to the radius limit
  50681. this.stopAllAnimations();
  50682. this._radiusIsAnimating = true;
  50683. 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(); }));
  50684. };
  50685. /**
  50686. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  50687. */
  50688. BouncingBehavior.prototype._clearAnimationLocks = function () {
  50689. this._radiusIsAnimating = false;
  50690. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  50691. };
  50692. /**
  50693. * Stops and removes all animations that have been applied to the camera
  50694. */
  50695. BouncingBehavior.prototype.stopAllAnimations = function () {
  50696. this._attachedCamera.animations = [];
  50697. while (this._animatables.length) {
  50698. this._animatables[0].onAnimationEnd = null;
  50699. this._animatables[0].stop();
  50700. this._animatables.shift();
  50701. }
  50702. };
  50703. /**
  50704. * The easing function used by animations
  50705. */
  50706. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  50707. /**
  50708. * The easing mode used by animations
  50709. */
  50710. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  50711. return BouncingBehavior;
  50712. }());
  50713. BABYLON.BouncingBehavior = BouncingBehavior;
  50714. })(BABYLON || (BABYLON = {}));
  50715. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  50716. var BABYLON;
  50717. (function (BABYLON) {
  50718. var AutoRotationBehavior = (function () {
  50719. function AutoRotationBehavior() {
  50720. this._zoomStopsAnimation = false;
  50721. this._idleRotationSpeed = 0.05;
  50722. this._idleRotationWaitTime = 2000;
  50723. this._idleRotationSpinupTime = 2000;
  50724. this._isPointerDown = false;
  50725. this._lastFrameTime = null;
  50726. this._lastInteractionTime = -Infinity;
  50727. this._cameraRotationSpeed = 0;
  50728. this._lastFrameRadius = 0;
  50729. }
  50730. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  50731. get: function () {
  50732. return "AutoRotation";
  50733. },
  50734. enumerable: true,
  50735. configurable: true
  50736. });
  50737. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  50738. /**
  50739. * Gets the flag that indicates if user zooming should stop animation.
  50740. */
  50741. get: function () {
  50742. return this._zoomStopsAnimation;
  50743. },
  50744. /**
  50745. * Sets the flag that indicates if user zooming should stop animation.
  50746. */
  50747. set: function (flag) {
  50748. this._zoomStopsAnimation = flag;
  50749. },
  50750. enumerable: true,
  50751. configurable: true
  50752. });
  50753. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  50754. /**
  50755. * Gets the default speed at which the camera rotates around the model.
  50756. */
  50757. get: function () {
  50758. return this._idleRotationSpeed;
  50759. },
  50760. /**
  50761. * Sets the default speed at which the camera rotates around the model.
  50762. */
  50763. set: function (speed) {
  50764. this._idleRotationSpeed = speed;
  50765. },
  50766. enumerable: true,
  50767. configurable: true
  50768. });
  50769. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  50770. /**
  50771. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  50772. */
  50773. get: function () {
  50774. return this._idleRotationWaitTime;
  50775. },
  50776. /**
  50777. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  50778. */
  50779. set: function (time) {
  50780. this._idleRotationWaitTime = time;
  50781. },
  50782. enumerable: true,
  50783. configurable: true
  50784. });
  50785. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  50786. /**
  50787. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50788. */
  50789. get: function () {
  50790. return this._idleRotationSpinupTime;
  50791. },
  50792. /**
  50793. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50794. */
  50795. set: function (time) {
  50796. this._idleRotationSpinupTime = time;
  50797. },
  50798. enumerable: true,
  50799. configurable: true
  50800. });
  50801. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  50802. /**
  50803. * Gets a value indicating if the camera is currently rotating because of this behavior
  50804. */
  50805. get: function () {
  50806. return Math.abs(this._cameraRotationSpeed) > 0;
  50807. },
  50808. enumerable: true,
  50809. configurable: true
  50810. });
  50811. AutoRotationBehavior.prototype.attach = function (camera) {
  50812. var _this = this;
  50813. this._attachedCamera = camera;
  50814. var scene = this._attachedCamera.getScene();
  50815. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  50816. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50817. _this._isPointerDown = true;
  50818. return;
  50819. }
  50820. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  50821. _this._isPointerDown = false;
  50822. }
  50823. });
  50824. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50825. var now = BABYLON.Tools.Now;
  50826. var dt = 0;
  50827. if (_this._lastFrameTime != null) {
  50828. dt = now - _this._lastFrameTime;
  50829. }
  50830. _this._lastFrameTime = now;
  50831. // Stop the animation if there is user interaction and the animation should stop for this interaction
  50832. _this._applyUserInteraction();
  50833. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  50834. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  50835. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  50836. // Step camera rotation by rotation speed
  50837. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  50838. });
  50839. };
  50840. AutoRotationBehavior.prototype.detach = function () {
  50841. var scene = this._attachedCamera.getScene();
  50842. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  50843. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50844. this._attachedCamera = null;
  50845. };
  50846. /**
  50847. * Returns true if user is scrolling.
  50848. * @return true if user is scrolling.
  50849. */
  50850. AutoRotationBehavior.prototype._userIsZooming = function () {
  50851. return this._attachedCamera.inertialRadiusOffset !== 0;
  50852. };
  50853. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  50854. var zoomHasHitLimit = false;
  50855. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  50856. zoomHasHitLimit = true;
  50857. }
  50858. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  50859. this._lastFrameRadius = this._attachedCamera.radius;
  50860. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  50861. };
  50862. /**
  50863. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  50864. */
  50865. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  50866. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  50867. this._lastInteractionTime = BABYLON.Tools.Now;
  50868. }
  50869. };
  50870. // Tools
  50871. AutoRotationBehavior.prototype._userIsMoving = function () {
  50872. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  50873. this._attachedCamera.inertialBetaOffset !== 0 ||
  50874. this._attachedCamera.inertialRadiusOffset !== 0 ||
  50875. this._attachedCamera.inertialPanningX !== 0 ||
  50876. this._attachedCamera.inertialPanningY !== 0 ||
  50877. this._isPointerDown;
  50878. };
  50879. return AutoRotationBehavior;
  50880. }());
  50881. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  50882. })(BABYLON || (BABYLON = {}));
  50883. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  50884. var BABYLON;
  50885. (function (BABYLON) {
  50886. var MorphTarget = (function () {
  50887. function MorphTarget(name, influence) {
  50888. if (influence === void 0) { influence = 0; }
  50889. this.name = name;
  50890. this.animations = new Array();
  50891. this.onInfluenceChanged = new BABYLON.Observable();
  50892. this.influence = influence;
  50893. }
  50894. Object.defineProperty(MorphTarget.prototype, "influence", {
  50895. get: function () {
  50896. return this._influence;
  50897. },
  50898. set: function (influence) {
  50899. if (this._influence === influence) {
  50900. return;
  50901. }
  50902. var previous = this._influence;
  50903. this._influence = influence;
  50904. if (this.onInfluenceChanged.hasObservers) {
  50905. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  50906. }
  50907. },
  50908. enumerable: true,
  50909. configurable: true
  50910. });
  50911. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  50912. get: function () {
  50913. return this._normals !== undefined;
  50914. },
  50915. enumerable: true,
  50916. configurable: true
  50917. });
  50918. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  50919. get: function () {
  50920. return this._tangents !== undefined;
  50921. },
  50922. enumerable: true,
  50923. configurable: true
  50924. });
  50925. MorphTarget.prototype.setPositions = function (data) {
  50926. this._positions = new Float32Array(data);
  50927. };
  50928. MorphTarget.prototype.getPositions = function () {
  50929. return this._positions;
  50930. };
  50931. MorphTarget.prototype.setNormals = function (data) {
  50932. this._normals = new Float32Array(data);
  50933. };
  50934. MorphTarget.prototype.getNormals = function () {
  50935. return this._normals;
  50936. };
  50937. MorphTarget.prototype.setTangents = function (data) {
  50938. this._tangents = new Float32Array(data);
  50939. };
  50940. MorphTarget.prototype.getTangents = function () {
  50941. return this._tangents;
  50942. };
  50943. /**
  50944. * Serializes the current target into a Serialization object.
  50945. * Returns the serialized object.
  50946. */
  50947. MorphTarget.prototype.serialize = function () {
  50948. var serializationObject = {};
  50949. serializationObject.name = this.name;
  50950. serializationObject.influence = this.influence;
  50951. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  50952. if (this.hasNormals) {
  50953. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  50954. }
  50955. if (this.hasTangents) {
  50956. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  50957. }
  50958. return serializationObject;
  50959. };
  50960. // Statics
  50961. MorphTarget.Parse = function (serializationObject) {
  50962. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  50963. result.setPositions(serializationObject.positions);
  50964. if (serializationObject.normals) {
  50965. result.setNormals(serializationObject.normals);
  50966. }
  50967. if (serializationObject.tangents) {
  50968. result.setTangents(serializationObject.tangents);
  50969. }
  50970. return result;
  50971. };
  50972. MorphTarget.FromMesh = function (mesh, name, influence) {
  50973. if (!name) {
  50974. name = mesh.name;
  50975. }
  50976. var result = new MorphTarget(name, influence);
  50977. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  50978. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50979. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  50980. }
  50981. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  50982. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  50983. }
  50984. return result;
  50985. };
  50986. return MorphTarget;
  50987. }());
  50988. BABYLON.MorphTarget = MorphTarget;
  50989. })(BABYLON || (BABYLON = {}));
  50990. //# sourceMappingURL=babylon.morphTarget.js.map
  50991. var BABYLON;
  50992. (function (BABYLON) {
  50993. var MorphTargetManager = (function () {
  50994. function MorphTargetManager(scene) {
  50995. this._targets = new Array();
  50996. this._targetObservable = new Array();
  50997. this._activeTargets = new BABYLON.SmartArray(16);
  50998. this._supportsNormals = false;
  50999. this._supportsTangents = false;
  51000. this._vertexCount = 0;
  51001. this._uniqueId = 0;
  51002. this._tempInfluences = new Array();
  51003. if (!scene) {
  51004. scene = BABYLON.Engine.LastCreatedScene;
  51005. }
  51006. this._scene = scene;
  51007. this._scene.morphTargetManagers.push(this);
  51008. this._uniqueId = scene.getUniqueId();
  51009. }
  51010. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  51011. get: function () {
  51012. return this._uniqueId;
  51013. },
  51014. enumerable: true,
  51015. configurable: true
  51016. });
  51017. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  51018. get: function () {
  51019. return this._vertexCount;
  51020. },
  51021. enumerable: true,
  51022. configurable: true
  51023. });
  51024. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  51025. get: function () {
  51026. return this._supportsNormals;
  51027. },
  51028. enumerable: true,
  51029. configurable: true
  51030. });
  51031. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  51032. get: function () {
  51033. return this._supportsTangents;
  51034. },
  51035. enumerable: true,
  51036. configurable: true
  51037. });
  51038. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  51039. get: function () {
  51040. return this._targets.length;
  51041. },
  51042. enumerable: true,
  51043. configurable: true
  51044. });
  51045. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  51046. get: function () {
  51047. return this._activeTargets.length;
  51048. },
  51049. enumerable: true,
  51050. configurable: true
  51051. });
  51052. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  51053. get: function () {
  51054. return this._influences;
  51055. },
  51056. enumerable: true,
  51057. configurable: true
  51058. });
  51059. MorphTargetManager.prototype.getActiveTarget = function (index) {
  51060. return this._activeTargets.data[index];
  51061. };
  51062. MorphTargetManager.prototype.getTarget = function (index) {
  51063. return this._targets[index];
  51064. };
  51065. MorphTargetManager.prototype.addTarget = function (target) {
  51066. var _this = this;
  51067. if (this._vertexCount) {
  51068. if (this._vertexCount !== target.getPositions().length / 3) {
  51069. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  51070. return;
  51071. }
  51072. }
  51073. this._targets.push(target);
  51074. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  51075. _this._syncActiveTargets(needUpdate);
  51076. }));
  51077. this._syncActiveTargets(true);
  51078. };
  51079. MorphTargetManager.prototype.removeTarget = function (target) {
  51080. var index = this._targets.indexOf(target);
  51081. if (index >= 0) {
  51082. this._targets.splice(index, 1);
  51083. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  51084. this._vertexCount = 0;
  51085. this._syncActiveTargets(true);
  51086. }
  51087. };
  51088. /**
  51089. * Serializes the current manager into a Serialization object.
  51090. * Returns the serialized object.
  51091. */
  51092. MorphTargetManager.prototype.serialize = function () {
  51093. var serializationObject = {};
  51094. serializationObject.id = this.uniqueId;
  51095. serializationObject.targets = [];
  51096. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  51097. var target = _a[_i];
  51098. serializationObject.targets.push(target.serialize());
  51099. }
  51100. return serializationObject;
  51101. };
  51102. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  51103. this._syncActiveTargets(needUpdate);
  51104. };
  51105. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  51106. var influenceCount = 0;
  51107. this._activeTargets.reset();
  51108. this._supportsNormals = true;
  51109. this._supportsTangents = true;
  51110. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  51111. var target = _a[_i];
  51112. if (target.influence > 0) {
  51113. this._activeTargets.push(target);
  51114. this._tempInfluences[influenceCount++] = target.influence;
  51115. this._supportsNormals = this._supportsNormals && target.hasNormals;
  51116. this._supportsTangents = this._supportsTangents && target.hasTangents;
  51117. if (this._vertexCount === 0) {
  51118. this._vertexCount = target.getPositions().length / 3;
  51119. }
  51120. }
  51121. }
  51122. if (!this._influences || this._influences.length !== influenceCount) {
  51123. this._influences = new Float32Array(influenceCount);
  51124. }
  51125. for (var index = 0; index < influenceCount; index++) {
  51126. this._influences[index] = this._tempInfluences[index];
  51127. }
  51128. if (needUpdate) {
  51129. // Flag meshes as dirty to resync with the active targets
  51130. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  51131. var mesh = _c[_b];
  51132. if (mesh.morphTargetManager === this) {
  51133. mesh._syncGeometryWithMorphTargetManager();
  51134. }
  51135. }
  51136. }
  51137. };
  51138. // Statics
  51139. MorphTargetManager.Parse = function (serializationObject, scene) {
  51140. var result = new MorphTargetManager(scene);
  51141. result._uniqueId = serializationObject.id;
  51142. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  51143. var targetData = _a[_i];
  51144. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  51145. }
  51146. return result;
  51147. };
  51148. return MorphTargetManager;
  51149. }());
  51150. BABYLON.MorphTargetManager = MorphTargetManager;
  51151. })(BABYLON || (BABYLON = {}));
  51152. //# sourceMappingURL=babylon.morphTargetManager.js.map
  51153. 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}"};
  51154. 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};"};
  51155. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  51156. var BABYLON;
  51157. (function (BABYLON) {
  51158. var GridMaterialDefines = (function (_super) {
  51159. __extends(GridMaterialDefines, _super);
  51160. function GridMaterialDefines() {
  51161. var _this = _super.call(this) || this;
  51162. _this.TRANSPARENT = false;
  51163. _this.FOG = false;
  51164. _this.PREMULTIPLYALPHA = false;
  51165. _this.rebuild();
  51166. return _this;
  51167. }
  51168. return GridMaterialDefines;
  51169. }(BABYLON.MaterialDefines));
  51170. /**
  51171. * The grid materials allows you to wrap any shape with a grid.
  51172. * Colors are customizable.
  51173. */
  51174. var GridMaterial = (function (_super) {
  51175. __extends(GridMaterial, _super);
  51176. /**
  51177. * constructor
  51178. * @param name The name given to the material in order to identify it afterwards.
  51179. * @param scene The scene the material is used in.
  51180. */
  51181. function GridMaterial(name, scene) {
  51182. var _this = _super.call(this, name, scene) || this;
  51183. /**
  51184. * Main color of the grid (e.g. between lines)
  51185. */
  51186. _this.mainColor = BABYLON.Color3.Black();
  51187. /**
  51188. * Color of the grid lines.
  51189. */
  51190. _this.lineColor = BABYLON.Color3.Teal();
  51191. /**
  51192. * The scale of the grid compared to unit.
  51193. */
  51194. _this.gridRatio = 1.0;
  51195. /**
  51196. * The frequency of thicker lines.
  51197. */
  51198. _this.majorUnitFrequency = 10;
  51199. /**
  51200. * The visibility of minor units in the grid.
  51201. */
  51202. _this.minorUnitVisibility = 0.33;
  51203. /**
  51204. * The grid opacity outside of the lines.
  51205. */
  51206. _this.opacity = 1.0;
  51207. /**
  51208. * Determine RBG output is premultiplied by alpha value.
  51209. */
  51210. _this.preMultiplyAlpha = false;
  51211. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  51212. return _this;
  51213. }
  51214. /**
  51215. * Returns wehter or not the grid requires alpha blending.
  51216. */
  51217. GridMaterial.prototype.needAlphaBlending = function () {
  51218. return this.opacity < 1.0;
  51219. };
  51220. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  51221. if (this.isFrozen) {
  51222. if (this._wasPreviouslyReady && subMesh.effect) {
  51223. return true;
  51224. }
  51225. }
  51226. if (!subMesh._materialDefines) {
  51227. subMesh._materialDefines = new GridMaterialDefines();
  51228. }
  51229. var defines = subMesh._materialDefines;
  51230. var scene = this.getScene();
  51231. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  51232. if (this._renderId === scene.getRenderId()) {
  51233. return true;
  51234. }
  51235. }
  51236. var engine = scene.getEngine();
  51237. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  51238. defines.TRANSPARENT = !defines.TRANSPARENT;
  51239. defines.markAsUnprocessed();
  51240. }
  51241. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  51242. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  51243. defines.markAsUnprocessed();
  51244. }
  51245. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  51246. // Get correct effect
  51247. if (defines.isDirty) {
  51248. defines.markAsProcessed();
  51249. scene.resetCachedMaterial();
  51250. // Attributes
  51251. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  51252. // Defines
  51253. var join = defines.toString();
  51254. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  51255. }
  51256. if (!subMesh.effect.isReady()) {
  51257. return false;
  51258. }
  51259. this._renderId = scene.getRenderId();
  51260. this._wasPreviouslyReady = true;
  51261. return true;
  51262. };
  51263. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  51264. var scene = this.getScene();
  51265. var defines = subMesh._materialDefines;
  51266. if (!defines) {
  51267. return;
  51268. }
  51269. var effect = subMesh.effect;
  51270. this._activeEffect = effect;
  51271. // Matrices
  51272. this.bindOnlyWorldMatrix(world);
  51273. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  51274. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  51275. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  51276. // Uniforms
  51277. if (this._mustRebind(scene, effect)) {
  51278. this._activeEffect.setColor3("mainColor", this.mainColor);
  51279. this._activeEffect.setColor3("lineColor", this.lineColor);
  51280. this._gridControl.x = this.gridRatio;
  51281. this._gridControl.y = Math.round(this.majorUnitFrequency);
  51282. this._gridControl.z = this.minorUnitVisibility;
  51283. this._gridControl.w = this.opacity;
  51284. this._activeEffect.setVector4("gridControl", this._gridControl);
  51285. }
  51286. // Fog
  51287. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  51288. this._afterBind(mesh, this._activeEffect);
  51289. };
  51290. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  51291. _super.prototype.dispose.call(this, forceDisposeEffect);
  51292. };
  51293. GridMaterial.prototype.clone = function (name) {
  51294. var _this = this;
  51295. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  51296. };
  51297. GridMaterial.prototype.serialize = function () {
  51298. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51299. serializationObject.customType = "BABYLON.GridMaterial";
  51300. return serializationObject;
  51301. };
  51302. GridMaterial.prototype.getClassName = function () {
  51303. return "GridMaterial";
  51304. };
  51305. GridMaterial.Parse = function (source, scene, rootUrl) {
  51306. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  51307. };
  51308. __decorate([
  51309. BABYLON.serializeAsColor3()
  51310. ], GridMaterial.prototype, "mainColor", void 0);
  51311. __decorate([
  51312. BABYLON.serializeAsColor3()
  51313. ], GridMaterial.prototype, "lineColor", void 0);
  51314. __decorate([
  51315. BABYLON.serialize()
  51316. ], GridMaterial.prototype, "gridRatio", void 0);
  51317. __decorate([
  51318. BABYLON.serialize()
  51319. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  51320. __decorate([
  51321. BABYLON.serialize()
  51322. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  51323. __decorate([
  51324. BABYLON.serialize()
  51325. ], GridMaterial.prototype, "opacity", void 0);
  51326. __decorate([
  51327. BABYLON.serialize()
  51328. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  51329. return GridMaterial;
  51330. }(BABYLON.PushMaterial));
  51331. BABYLON.GridMaterial = GridMaterial;
  51332. })(BABYLON || (BABYLON = {}));
  51333. //# sourceMappingURL=babylon.gridmaterial.js.map
  51334. 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}";
  51335. 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}";
  51336. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  51337. var BABYLON;
  51338. (function (BABYLON) {
  51339. var GLTFLoaderCoordinateSystemMode;
  51340. (function (GLTFLoaderCoordinateSystemMode) {
  51341. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  51342. // 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.
  51343. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  51344. // The glTF right-handed data is not transformed in any form and is loaded directly.
  51345. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  51346. // Sets the useRightHandedSystem flag on the scene.
  51347. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  51348. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  51349. var GLTFFileLoader = (function () {
  51350. function GLTFFileLoader() {
  51351. // V2 options
  51352. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  51353. this.name = "gltf";
  51354. this.extensions = {
  51355. ".gltf": { isBinary: false },
  51356. ".glb": { isBinary: true }
  51357. };
  51358. }
  51359. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  51360. var loaderData = GLTFFileLoader._parse(data, onError);
  51361. if (!loaderData) {
  51362. return;
  51363. }
  51364. var loader = this._getLoader(loaderData, onError);
  51365. if (!loader) {
  51366. return;
  51367. }
  51368. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51369. };
  51370. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  51371. var loaderData = GLTFFileLoader._parse(data, onError);
  51372. if (!loaderData) {
  51373. return;
  51374. }
  51375. var loader = this._getLoader(loaderData, onError);
  51376. if (!loader) {
  51377. return;
  51378. }
  51379. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51380. };
  51381. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  51382. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  51383. };
  51384. GLTFFileLoader._parse = function (data, onError) {
  51385. if (data instanceof ArrayBuffer) {
  51386. return GLTFFileLoader._parseBinary(data, onError);
  51387. }
  51388. try {
  51389. return {
  51390. json: JSON.parse(data),
  51391. bin: null
  51392. };
  51393. }
  51394. catch (e) {
  51395. onError(e.message);
  51396. return null;
  51397. }
  51398. };
  51399. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  51400. var loaderVersion = { major: 2, minor: 0 };
  51401. var asset = loaderData.json.asset || {};
  51402. var version = GLTFFileLoader._parseVersion(asset.version);
  51403. if (!version) {
  51404. onError("Invalid version: " + asset.version);
  51405. return null;
  51406. }
  51407. if (asset.minVersion !== undefined) {
  51408. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  51409. if (!minVersion) {
  51410. onError("Invalid minimum version: " + asset.minVersion);
  51411. return null;
  51412. }
  51413. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  51414. onError("Incompatible minimum version: " + asset.minVersion);
  51415. return null;
  51416. }
  51417. }
  51418. var createLoaders = {
  51419. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  51420. 2: GLTFFileLoader.CreateGLTFLoaderV2
  51421. };
  51422. var createLoader = createLoaders[version.major];
  51423. if (!createLoader) {
  51424. onError("Unsupported version: " + asset.version);
  51425. return null;
  51426. }
  51427. return createLoader(this);
  51428. };
  51429. GLTFFileLoader._parseBinary = function (data, onError) {
  51430. var Binary = {
  51431. Magic: 0x46546C67
  51432. };
  51433. var binaryReader = new BinaryReader(data);
  51434. var magic = binaryReader.readUint32();
  51435. if (magic !== Binary.Magic) {
  51436. onError("Unexpected magic: " + magic);
  51437. return null;
  51438. }
  51439. var version = binaryReader.readUint32();
  51440. switch (version) {
  51441. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  51442. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  51443. }
  51444. onError("Unsupported version: " + version);
  51445. return null;
  51446. };
  51447. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  51448. var ContentFormat = {
  51449. JSON: 0
  51450. };
  51451. var length = binaryReader.readUint32();
  51452. if (length != binaryReader.getLength()) {
  51453. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  51454. return null;
  51455. }
  51456. var contentLength = binaryReader.readUint32();
  51457. var contentFormat = binaryReader.readUint32();
  51458. var content;
  51459. switch (contentFormat) {
  51460. case ContentFormat.JSON:
  51461. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  51462. break;
  51463. default:
  51464. onError("Unexpected content format: " + contentFormat);
  51465. return null;
  51466. }
  51467. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  51468. var body = binaryReader.readUint8Array(bytesRemaining);
  51469. return {
  51470. json: content,
  51471. bin: body
  51472. };
  51473. };
  51474. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  51475. var ChunkFormat = {
  51476. JSON: 0x4E4F534A,
  51477. BIN: 0x004E4942
  51478. };
  51479. var length = binaryReader.readUint32();
  51480. if (length !== binaryReader.getLength()) {
  51481. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  51482. return null;
  51483. }
  51484. // JSON chunk
  51485. var chunkLength = binaryReader.readUint32();
  51486. var chunkFormat = binaryReader.readUint32();
  51487. if (chunkFormat !== ChunkFormat.JSON) {
  51488. onError("First chunk format is not JSON");
  51489. return null;
  51490. }
  51491. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  51492. // Look for BIN chunk
  51493. var bin = null;
  51494. while (binaryReader.getPosition() < binaryReader.getLength()) {
  51495. chunkLength = binaryReader.readUint32();
  51496. chunkFormat = binaryReader.readUint32();
  51497. switch (chunkFormat) {
  51498. case ChunkFormat.JSON:
  51499. onError("Unexpected JSON chunk");
  51500. return null;
  51501. case ChunkFormat.BIN:
  51502. bin = binaryReader.readUint8Array(chunkLength);
  51503. break;
  51504. default:
  51505. // ignore unrecognized chunkFormat
  51506. binaryReader.skipBytes(chunkLength);
  51507. break;
  51508. }
  51509. }
  51510. return {
  51511. json: json,
  51512. bin: bin
  51513. };
  51514. };
  51515. GLTFFileLoader._parseVersion = function (version) {
  51516. if (!version) {
  51517. return null;
  51518. }
  51519. var parts = version.split(".");
  51520. if (parts.length != 2) {
  51521. return null;
  51522. }
  51523. var major = +parts[0];
  51524. if (isNaN(major)) {
  51525. return null;
  51526. }
  51527. var minor = +parts[1];
  51528. if (isNaN(minor)) {
  51529. return null;
  51530. }
  51531. return {
  51532. major: major,
  51533. minor: minor
  51534. };
  51535. };
  51536. GLTFFileLoader._compareVersion = function (a, b) {
  51537. if (a.major > b.major)
  51538. return 1;
  51539. if (a.major < b.major)
  51540. return -1;
  51541. if (a.minor > b.minor)
  51542. return 1;
  51543. if (a.minor < b.minor)
  51544. return -1;
  51545. return 0;
  51546. };
  51547. GLTFFileLoader._decodeBufferToText = function (view) {
  51548. var result = "";
  51549. var length = view.byteLength;
  51550. for (var i = 0; i < length; ++i) {
  51551. result += String.fromCharCode(view[i]);
  51552. }
  51553. return result;
  51554. };
  51555. // V1 options
  51556. GLTFFileLoader.HomogeneousCoordinates = false;
  51557. GLTFFileLoader.IncrementalLoading = true;
  51558. return GLTFFileLoader;
  51559. }());
  51560. BABYLON.GLTFFileLoader = GLTFFileLoader;
  51561. var BinaryReader = (function () {
  51562. function BinaryReader(arrayBuffer) {
  51563. this._arrayBuffer = arrayBuffer;
  51564. this._dataView = new DataView(arrayBuffer);
  51565. this._byteOffset = 0;
  51566. }
  51567. BinaryReader.prototype.getPosition = function () {
  51568. return this._byteOffset;
  51569. };
  51570. BinaryReader.prototype.getLength = function () {
  51571. return this._arrayBuffer.byteLength;
  51572. };
  51573. BinaryReader.prototype.readUint32 = function () {
  51574. var value = this._dataView.getUint32(this._byteOffset, true);
  51575. this._byteOffset += 4;
  51576. return value;
  51577. };
  51578. BinaryReader.prototype.readUint8Array = function (length) {
  51579. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  51580. this._byteOffset += length;
  51581. return value;
  51582. };
  51583. BinaryReader.prototype.skipBytes = function (length) {
  51584. this._byteOffset += length;
  51585. };
  51586. return BinaryReader;
  51587. }());
  51588. if (BABYLON.SceneLoader) {
  51589. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  51590. }
  51591. })(BABYLON || (BABYLON = {}));
  51592. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  51593. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  51594. var BABYLON;
  51595. (function (BABYLON) {
  51596. var GLTF1;
  51597. (function (GLTF1) {
  51598. /**
  51599. * Enums
  51600. */
  51601. var EComponentType;
  51602. (function (EComponentType) {
  51603. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  51604. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  51605. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  51606. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  51607. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  51608. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  51609. var EShaderType;
  51610. (function (EShaderType) {
  51611. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  51612. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  51613. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  51614. var EParameterType;
  51615. (function (EParameterType) {
  51616. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  51617. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  51618. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  51619. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  51620. EParameterType[EParameterType["INT"] = 5124] = "INT";
  51621. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  51622. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  51623. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  51624. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  51625. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  51626. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  51627. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  51628. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  51629. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  51630. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  51631. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  51632. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  51633. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  51634. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  51635. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  51636. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  51637. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  51638. var ETextureWrapMode;
  51639. (function (ETextureWrapMode) {
  51640. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  51641. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  51642. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  51643. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  51644. var ETextureFilterType;
  51645. (function (ETextureFilterType) {
  51646. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  51647. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  51648. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  51649. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  51650. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  51651. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  51652. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  51653. var ETextureFormat;
  51654. (function (ETextureFormat) {
  51655. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  51656. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  51657. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  51658. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  51659. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  51660. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  51661. var ECullingType;
  51662. (function (ECullingType) {
  51663. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  51664. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  51665. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  51666. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  51667. var EBlendingFunction;
  51668. (function (EBlendingFunction) {
  51669. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  51670. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  51671. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  51672. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  51673. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  51674. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  51675. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  51676. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  51677. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  51678. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  51679. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  51680. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  51681. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  51682. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  51683. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  51684. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  51685. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  51686. })(BABYLON || (BABYLON = {}));
  51687. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  51688. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  51689. var BABYLON;
  51690. (function (BABYLON) {
  51691. var GLTF1;
  51692. (function (GLTF1) {
  51693. /**
  51694. * Tokenizer. Used for shaders compatibility
  51695. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  51696. */
  51697. var ETokenType;
  51698. (function (ETokenType) {
  51699. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  51700. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  51701. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  51702. })(ETokenType || (ETokenType = {}));
  51703. var Tokenizer = (function () {
  51704. function Tokenizer(toParse) {
  51705. this._pos = 0;
  51706. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  51707. this._toParse = toParse;
  51708. this._maxPos = toParse.length;
  51709. }
  51710. Tokenizer.prototype.getNextToken = function () {
  51711. if (this.isEnd())
  51712. return ETokenType.END_OF_INPUT;
  51713. this.currentString = this.read();
  51714. this.currentToken = ETokenType.UNKNOWN;
  51715. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  51716. this.currentToken = ETokenType.IDENTIFIER;
  51717. this.currentIdentifier = this.currentString;
  51718. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  51719. this.currentIdentifier += this.currentString;
  51720. this.forward();
  51721. }
  51722. }
  51723. return this.currentToken;
  51724. };
  51725. Tokenizer.prototype.peek = function () {
  51726. return this._toParse[this._pos];
  51727. };
  51728. Tokenizer.prototype.read = function () {
  51729. return this._toParse[this._pos++];
  51730. };
  51731. Tokenizer.prototype.forward = function () {
  51732. this._pos++;
  51733. };
  51734. Tokenizer.prototype.isEnd = function () {
  51735. return this._pos >= this._maxPos;
  51736. };
  51737. return Tokenizer;
  51738. }());
  51739. /**
  51740. * Values
  51741. */
  51742. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  51743. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  51744. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  51745. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  51746. /**
  51747. * Parse
  51748. */
  51749. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  51750. for (var buf in parsedBuffers) {
  51751. var parsedBuffer = parsedBuffers[buf];
  51752. gltfRuntime.buffers[buf] = parsedBuffer;
  51753. gltfRuntime.buffersCount++;
  51754. }
  51755. };
  51756. var parseShaders = function (parsedShaders, gltfRuntime) {
  51757. for (var sha in parsedShaders) {
  51758. var parsedShader = parsedShaders[sha];
  51759. gltfRuntime.shaders[sha] = parsedShader;
  51760. gltfRuntime.shaderscount++;
  51761. }
  51762. };
  51763. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  51764. for (var object in parsedObjects) {
  51765. var parsedObject = parsedObjects[object];
  51766. gltfRuntime[runtimeProperty][object] = parsedObject;
  51767. }
  51768. };
  51769. /**
  51770. * Utils
  51771. */
  51772. var normalizeUVs = function (buffer) {
  51773. if (!buffer) {
  51774. return;
  51775. }
  51776. for (var i = 0; i < buffer.length / 2; i++) {
  51777. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  51778. }
  51779. };
  51780. var replaceInString = function (str, searchValue, replaceValue) {
  51781. while (str.indexOf(searchValue) !== -1) {
  51782. str = str.replace(searchValue, replaceValue);
  51783. }
  51784. return str;
  51785. };
  51786. var getAttribute = function (attributeParameter) {
  51787. if (attributeParameter.semantic === "NORMAL") {
  51788. return "normal";
  51789. }
  51790. else if (attributeParameter.semantic === "POSITION") {
  51791. return "position";
  51792. }
  51793. else if (attributeParameter.semantic === "JOINT") {
  51794. return "matricesIndices";
  51795. }
  51796. else if (attributeParameter.semantic === "WEIGHT") {
  51797. return "matricesWeights";
  51798. }
  51799. else if (attributeParameter.semantic === "COLOR") {
  51800. return "color";
  51801. }
  51802. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  51803. var channel = Number(attributeParameter.semantic.split("_")[1]);
  51804. return "uv" + (channel === 0 ? "" : channel + 1);
  51805. }
  51806. };
  51807. /**
  51808. * Returns the animation path (glTF -> Babylon)
  51809. */
  51810. var getAnimationPath = function (path) {
  51811. var index = glTFAnimationPaths.indexOf(path);
  51812. if (index !== -1) {
  51813. return babylonAnimationPaths[index];
  51814. }
  51815. return path;
  51816. };
  51817. /**
  51818. * Loads and creates animations
  51819. */
  51820. var loadAnimations = function (gltfRuntime) {
  51821. for (var anim in gltfRuntime.animations) {
  51822. var animation = gltfRuntime.animations[anim];
  51823. var lastAnimation = null;
  51824. for (var i = 0; i < animation.channels.length; i++) {
  51825. // Get parameters and load buffers
  51826. var channel = animation.channels[i];
  51827. var sampler = animation.samplers[channel.sampler];
  51828. if (!sampler) {
  51829. continue;
  51830. }
  51831. var inputData = null;
  51832. var outputData = null;
  51833. if (animation.parameters) {
  51834. inputData = animation.parameters[sampler.input];
  51835. outputData = animation.parameters[sampler.output];
  51836. }
  51837. else {
  51838. inputData = sampler.input;
  51839. outputData = sampler.output;
  51840. }
  51841. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  51842. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  51843. var targetID = channel.target.id;
  51844. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  51845. if (targetNode === null) {
  51846. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  51847. }
  51848. if (targetNode === null) {
  51849. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  51850. continue;
  51851. }
  51852. var isBone = targetNode instanceof BABYLON.Bone;
  51853. // Get target path (position, rotation or scaling)
  51854. var targetPath = channel.target.path;
  51855. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  51856. if (targetPathIndex !== -1) {
  51857. targetPath = babylonAnimationPaths[targetPathIndex];
  51858. }
  51859. // Determine animation type
  51860. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  51861. if (!isBone) {
  51862. if (targetPath === "rotationQuaternion") {
  51863. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  51864. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  51865. }
  51866. else {
  51867. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  51868. }
  51869. }
  51870. // Create animation and key frames
  51871. var babylonAnimation = null;
  51872. var keys = [];
  51873. var arrayOffset = 0;
  51874. var modifyKey = false;
  51875. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  51876. babylonAnimation = lastAnimation;
  51877. modifyKey = true;
  51878. }
  51879. if (!modifyKey) {
  51880. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51881. }
  51882. // For each frame
  51883. for (var j = 0; j < bufferInput.length; j++) {
  51884. var value = null;
  51885. if (targetPath === "rotationQuaternion") {
  51886. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  51887. arrayOffset += 4;
  51888. }
  51889. else {
  51890. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  51891. arrayOffset += 3;
  51892. }
  51893. if (isBone) {
  51894. var bone = targetNode;
  51895. var translation = BABYLON.Vector3.Zero();
  51896. var rotationQuaternion = new BABYLON.Quaternion();
  51897. var scaling = BABYLON.Vector3.Zero();
  51898. // Warning on decompose
  51899. var mat = bone.getBaseMatrix();
  51900. if (modifyKey) {
  51901. mat = lastAnimation.getKeys()[j].value;
  51902. }
  51903. mat.decompose(scaling, rotationQuaternion, translation);
  51904. if (targetPath === "position") {
  51905. translation = value;
  51906. }
  51907. else if (targetPath === "rotationQuaternion") {
  51908. rotationQuaternion = value;
  51909. }
  51910. else {
  51911. scaling = value;
  51912. }
  51913. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  51914. }
  51915. if (!modifyKey) {
  51916. keys.push({
  51917. frame: bufferInput[j],
  51918. value: value
  51919. });
  51920. }
  51921. else {
  51922. lastAnimation.getKeys()[j].value = value;
  51923. }
  51924. }
  51925. // Finish
  51926. if (!modifyKey) {
  51927. babylonAnimation.setKeys(keys);
  51928. targetNode.animations.push(babylonAnimation);
  51929. }
  51930. lastAnimation = babylonAnimation;
  51931. gltfRuntime.scene.stopAnimation(targetNode);
  51932. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  51933. }
  51934. }
  51935. };
  51936. /**
  51937. * Returns the bones transformation matrix
  51938. */
  51939. var configureBoneTransformation = function (node) {
  51940. var mat = null;
  51941. if (node.translation || node.rotation || node.scale) {
  51942. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  51943. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  51944. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  51945. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  51946. }
  51947. else {
  51948. mat = BABYLON.Matrix.FromArray(node.matrix);
  51949. }
  51950. return mat;
  51951. };
  51952. /**
  51953. * Returns the parent bone
  51954. */
  51955. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  51956. // Try to find
  51957. for (var i = 0; i < newSkeleton.bones.length; i++) {
  51958. if (newSkeleton.bones[i].name === jointName) {
  51959. return newSkeleton.bones[i];
  51960. }
  51961. }
  51962. // Not found, search in gltf nodes
  51963. var nodes = gltfRuntime.nodes;
  51964. for (var nde in nodes) {
  51965. var node = nodes[nde];
  51966. if (!node.jointName) {
  51967. continue;
  51968. }
  51969. var children = node.children;
  51970. for (var i = 0; i < children.length; i++) {
  51971. var child = gltfRuntime.nodes[children[i]];
  51972. if (!child.jointName) {
  51973. continue;
  51974. }
  51975. if (child.jointName === jointName) {
  51976. var mat = configureBoneTransformation(node);
  51977. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  51978. bone.id = nde;
  51979. return bone;
  51980. }
  51981. }
  51982. }
  51983. return null;
  51984. };
  51985. /**
  51986. * Returns the appropriate root node
  51987. */
  51988. var getNodeToRoot = function (nodesToRoot, id) {
  51989. for (var i = 0; i < nodesToRoot.length; i++) {
  51990. var nodeToRoot = nodesToRoot[i];
  51991. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  51992. var child = nodeToRoot.node.children[j];
  51993. if (child === id) {
  51994. return nodeToRoot.bone;
  51995. }
  51996. }
  51997. }
  51998. return null;
  51999. };
  52000. /**
  52001. * Returns the node with the joint name
  52002. */
  52003. var getJointNode = function (gltfRuntime, jointName) {
  52004. var nodes = gltfRuntime.nodes;
  52005. var node = nodes[jointName];
  52006. if (node) {
  52007. return {
  52008. node: node,
  52009. id: jointName
  52010. };
  52011. }
  52012. for (var nde in nodes) {
  52013. node = nodes[nde];
  52014. if (node.jointName === jointName) {
  52015. return {
  52016. node: node,
  52017. id: nde
  52018. };
  52019. }
  52020. }
  52021. return null;
  52022. };
  52023. /**
  52024. * Checks if a nodes is in joints
  52025. */
  52026. var nodeIsInJoints = function (skins, id) {
  52027. for (var i = 0; i < skins.jointNames.length; i++) {
  52028. if (skins.jointNames[i] === id) {
  52029. return true;
  52030. }
  52031. }
  52032. return false;
  52033. };
  52034. /**
  52035. * Fills the nodes to root for bones and builds hierarchy
  52036. */
  52037. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  52038. // Creates nodes for root
  52039. for (var nde in gltfRuntime.nodes) {
  52040. var node = gltfRuntime.nodes[nde];
  52041. var id = nde;
  52042. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  52043. continue;
  52044. }
  52045. // Create node to root bone
  52046. var mat = configureBoneTransformation(node);
  52047. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  52048. bone.id = id;
  52049. nodesToRoot.push({ bone: bone, node: node, id: id });
  52050. }
  52051. // Parenting
  52052. for (var i = 0; i < nodesToRoot.length; i++) {
  52053. var nodeToRoot = nodesToRoot[i];
  52054. var children = nodeToRoot.node.children;
  52055. for (var j = 0; j < children.length; j++) {
  52056. var child = null;
  52057. for (var k = 0; k < nodesToRoot.length; k++) {
  52058. if (nodesToRoot[k].id === children[j]) {
  52059. child = nodesToRoot[k];
  52060. break;
  52061. }
  52062. }
  52063. if (child) {
  52064. child.bone._parent = nodeToRoot.bone;
  52065. nodeToRoot.bone.children.push(child.bone);
  52066. }
  52067. }
  52068. }
  52069. };
  52070. var printMat = function (m) {
  52071. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  52072. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  52073. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  52074. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  52075. };
  52076. /**
  52077. * Imports a skeleton
  52078. */
  52079. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  52080. if (!newSkeleton) {
  52081. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  52082. }
  52083. if (!skins.babylonSkeleton) {
  52084. return newSkeleton;
  52085. }
  52086. // Matrices
  52087. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  52088. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52089. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  52090. // Find the root bones
  52091. var nodesToRoot = [];
  52092. var nodesToRootToAdd = [];
  52093. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  52094. newSkeleton.bones = [];
  52095. // Joints
  52096. for (var i = 0; i < skins.jointNames.length; i++) {
  52097. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  52098. var node = jointNode.node;
  52099. if (!node) {
  52100. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  52101. continue;
  52102. }
  52103. var id = jointNode.id;
  52104. // Optimize, if the bone already exists...
  52105. var existingBone = gltfRuntime.scene.getBoneByID(id);
  52106. if (existingBone) {
  52107. newSkeleton.bones.push(existingBone);
  52108. continue;
  52109. }
  52110. // Search for parent bone
  52111. var foundBone = false;
  52112. var parentBone = null;
  52113. for (var j = 0; j < i; j++) {
  52114. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  52115. if (!joint) {
  52116. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  52117. continue;
  52118. }
  52119. var children = joint.children;
  52120. if (!children) {
  52121. continue;
  52122. }
  52123. foundBone = false;
  52124. for (var k = 0; k < children.length; k++) {
  52125. if (children[k] === id) {
  52126. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  52127. foundBone = true;
  52128. break;
  52129. }
  52130. }
  52131. if (foundBone) {
  52132. break;
  52133. }
  52134. }
  52135. // Create bone
  52136. var mat = configureBoneTransformation(node);
  52137. if (!parentBone && nodesToRoot.length > 0) {
  52138. parentBone = getNodeToRoot(nodesToRoot, id);
  52139. if (parentBone) {
  52140. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  52141. nodesToRootToAdd.push(parentBone);
  52142. }
  52143. }
  52144. }
  52145. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  52146. bone.id = id;
  52147. }
  52148. // Polish
  52149. var bones = newSkeleton.bones;
  52150. newSkeleton.bones = [];
  52151. for (var i = 0; i < skins.jointNames.length; i++) {
  52152. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  52153. if (!jointNode) {
  52154. continue;
  52155. }
  52156. for (var j = 0; j < bones.length; j++) {
  52157. if (bones[j].id === jointNode.id) {
  52158. newSkeleton.bones.push(bones[j]);
  52159. break;
  52160. }
  52161. }
  52162. }
  52163. newSkeleton.prepare();
  52164. // Finish
  52165. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  52166. newSkeleton.bones.push(nodesToRootToAdd[i]);
  52167. }
  52168. return newSkeleton;
  52169. };
  52170. /**
  52171. * Imports a mesh and its geometries
  52172. */
  52173. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  52174. if (!newMesh) {
  52175. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  52176. newMesh.id = id;
  52177. }
  52178. if (!node.babylonNode) {
  52179. return newMesh;
  52180. }
  52181. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  52182. if (!newMesh.material) {
  52183. newMesh.material = multiMat;
  52184. }
  52185. var vertexData = new BABYLON.VertexData();
  52186. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  52187. var verticesStarts = [];
  52188. var verticesCounts = [];
  52189. var indexStarts = [];
  52190. var indexCounts = [];
  52191. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  52192. var meshID = meshes[meshIndex];
  52193. var mesh = gltfRuntime.meshes[meshID];
  52194. if (!mesh) {
  52195. continue;
  52196. }
  52197. // Positions, normals and UVs
  52198. for (var i = 0; i < mesh.primitives.length; i++) {
  52199. // Temporary vertex data
  52200. var tempVertexData = new BABYLON.VertexData();
  52201. var primitive = mesh.primitives[i];
  52202. if (primitive.mode !== 4) {
  52203. // continue;
  52204. }
  52205. var attributes = primitive.attributes;
  52206. var accessor = null;
  52207. var buffer = null;
  52208. // Set positions, normal and uvs
  52209. for (var semantic in attributes) {
  52210. // Link accessor and buffer view
  52211. accessor = gltfRuntime.accessors[attributes[semantic]];
  52212. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52213. if (semantic === "NORMAL") {
  52214. tempVertexData.normals = new Float32Array(buffer.length);
  52215. tempVertexData.normals.set(buffer);
  52216. }
  52217. else if (semantic === "POSITION") {
  52218. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  52219. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  52220. for (var j = 0; j < buffer.length; j += 4) {
  52221. tempVertexData.positions[j] = buffer[j];
  52222. tempVertexData.positions[j + 1] = buffer[j + 1];
  52223. tempVertexData.positions[j + 2] = buffer[j + 2];
  52224. }
  52225. }
  52226. else {
  52227. tempVertexData.positions = new Float32Array(buffer.length);
  52228. tempVertexData.positions.set(buffer);
  52229. }
  52230. verticesCounts.push(tempVertexData.positions.length);
  52231. }
  52232. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  52233. var channel = Number(semantic.split("_")[1]);
  52234. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  52235. var uvs = new Float32Array(buffer.length);
  52236. uvs.set(buffer);
  52237. normalizeUVs(uvs);
  52238. tempVertexData.set(uvs, uvKind);
  52239. }
  52240. else if (semantic === "JOINT") {
  52241. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  52242. tempVertexData.matricesIndices.set(buffer);
  52243. }
  52244. else if (semantic === "WEIGHT") {
  52245. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  52246. tempVertexData.matricesWeights.set(buffer);
  52247. }
  52248. else if (semantic === "COLOR") {
  52249. tempVertexData.colors = new Float32Array(buffer.length);
  52250. tempVertexData.colors.set(buffer);
  52251. }
  52252. }
  52253. // Indices
  52254. accessor = gltfRuntime.accessors[primitive.indices];
  52255. if (accessor) {
  52256. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52257. tempVertexData.indices = new Int32Array(buffer.length);
  52258. tempVertexData.indices.set(buffer);
  52259. indexCounts.push(tempVertexData.indices.length);
  52260. }
  52261. else {
  52262. // Set indices on the fly
  52263. var indices = [];
  52264. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  52265. indices.push(j);
  52266. }
  52267. tempVertexData.indices = new Int32Array(indices);
  52268. indexCounts.push(tempVertexData.indices.length);
  52269. }
  52270. vertexData.merge(tempVertexData);
  52271. tempVertexData = undefined;
  52272. // Sub material
  52273. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  52274. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  52275. // Update vertices start and index start
  52276. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  52277. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  52278. }
  52279. }
  52280. // Apply geometry
  52281. geometry.setAllVerticesData(vertexData, false);
  52282. newMesh.computeWorldMatrix(true);
  52283. // Apply submeshes
  52284. newMesh.subMeshes = [];
  52285. var index = 0;
  52286. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  52287. var meshID = meshes[meshIndex];
  52288. var mesh = gltfRuntime.meshes[meshID];
  52289. if (!mesh) {
  52290. continue;
  52291. }
  52292. for (var i = 0; i < mesh.primitives.length; i++) {
  52293. if (mesh.primitives[i].mode !== 4) {
  52294. //continue;
  52295. }
  52296. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  52297. index++;
  52298. }
  52299. }
  52300. // Finish
  52301. return newMesh;
  52302. };
  52303. /**
  52304. * Configure node transformation from position, rotation and scaling
  52305. */
  52306. var configureNode = function (newNode, position, rotation, scaling) {
  52307. if (newNode.position) {
  52308. newNode.position = position;
  52309. }
  52310. if (newNode.rotationQuaternion || newNode.rotation) {
  52311. newNode.rotationQuaternion = rotation;
  52312. }
  52313. if (newNode.scaling) {
  52314. newNode.scaling = scaling;
  52315. }
  52316. };
  52317. /**
  52318. * Configures node from transformation matrix
  52319. */
  52320. var configureNodeFromMatrix = function (newNode, node, parent) {
  52321. if (node.matrix) {
  52322. var position = new BABYLON.Vector3(0, 0, 0);
  52323. var rotation = new BABYLON.Quaternion();
  52324. var scaling = new BABYLON.Vector3(0, 0, 0);
  52325. var mat = BABYLON.Matrix.FromArray(node.matrix);
  52326. mat.decompose(scaling, rotation, position);
  52327. configureNode(newNode, position, rotation, scaling);
  52328. }
  52329. else {
  52330. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  52331. }
  52332. newNode.computeWorldMatrix(true);
  52333. };
  52334. /**
  52335. * Imports a node
  52336. */
  52337. var importNode = function (gltfRuntime, node, id, parent) {
  52338. var lastNode = null;
  52339. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  52340. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  52341. return null;
  52342. }
  52343. }
  52344. // Meshes
  52345. if (node.skin) {
  52346. if (node.meshes) {
  52347. var skin = gltfRuntime.skins[node.skin];
  52348. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  52349. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  52350. if (newMesh.skeleton === null) {
  52351. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  52352. if (!skin.babylonSkeleton) {
  52353. skin.babylonSkeleton = newMesh.skeleton;
  52354. }
  52355. }
  52356. lastNode = newMesh;
  52357. }
  52358. }
  52359. else if (node.meshes) {
  52360. /**
  52361. * Improve meshes property
  52362. */
  52363. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  52364. lastNode = newMesh;
  52365. }
  52366. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  52367. var light = gltfRuntime.lights[node.light];
  52368. if (light) {
  52369. if (light.type === "ambient") {
  52370. var ambienLight = light[light.type];
  52371. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52372. hemiLight.name = node.name;
  52373. if (ambienLight.color) {
  52374. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  52375. }
  52376. lastNode = hemiLight;
  52377. }
  52378. else if (light.type === "directional") {
  52379. var directionalLight = light[light.type];
  52380. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52381. dirLight.name = node.name;
  52382. if (directionalLight.color) {
  52383. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  52384. }
  52385. lastNode = dirLight;
  52386. }
  52387. else if (light.type === "point") {
  52388. var pointLight = light[light.type];
  52389. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52390. ptLight.name = node.name;
  52391. if (pointLight.color) {
  52392. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  52393. }
  52394. lastNode = ptLight;
  52395. }
  52396. else if (light.type === "spot") {
  52397. var spotLight = light[light.type];
  52398. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  52399. spLight.name = node.name;
  52400. if (spotLight.color) {
  52401. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  52402. }
  52403. if (spotLight.fallOfAngle) {
  52404. spLight.angle = spotLight.fallOfAngle;
  52405. }
  52406. if (spotLight.fallOffExponent) {
  52407. spLight.exponent = spotLight.fallOffExponent;
  52408. }
  52409. lastNode = spLight;
  52410. }
  52411. }
  52412. }
  52413. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  52414. var camera = gltfRuntime.cameras[node.camera];
  52415. if (camera) {
  52416. if (camera.type === "orthographic") {
  52417. var orthographicCamera = camera[camera.type];
  52418. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52419. orthoCamera.name = node.name;
  52420. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  52421. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  52422. lastNode = orthoCamera;
  52423. }
  52424. else if (camera.type === "perspective") {
  52425. var perspectiveCamera = camera[camera.type];
  52426. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52427. persCamera.name = node.name;
  52428. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  52429. if (!perspectiveCamera.aspectRatio) {
  52430. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  52431. }
  52432. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  52433. persCamera.maxZ = perspectiveCamera.zfar;
  52434. persCamera.minZ = perspectiveCamera.znear;
  52435. }
  52436. lastNode = persCamera;
  52437. }
  52438. }
  52439. }
  52440. // Empty node
  52441. if (!node.jointName) {
  52442. if (node.babylonNode) {
  52443. return node.babylonNode;
  52444. }
  52445. else if (lastNode === null) {
  52446. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  52447. node.babylonNode = dummy;
  52448. lastNode = dummy;
  52449. }
  52450. }
  52451. if (lastNode !== null) {
  52452. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  52453. configureNodeFromMatrix(lastNode, node, parent);
  52454. }
  52455. else {
  52456. var translation = node.translation || [0, 0, 0];
  52457. var rotation = node.rotation || [0, 0, 0, 1];
  52458. var scale = node.scale || [1, 1, 1];
  52459. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  52460. }
  52461. lastNode.updateCache(true);
  52462. node.babylonNode = lastNode;
  52463. }
  52464. return lastNode;
  52465. };
  52466. /**
  52467. * Traverses nodes and creates them
  52468. */
  52469. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  52470. var node = gltfRuntime.nodes[id];
  52471. var newNode = null;
  52472. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  52473. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  52474. meshIncluded = true;
  52475. }
  52476. else {
  52477. meshIncluded = false;
  52478. }
  52479. }
  52480. else {
  52481. meshIncluded = true;
  52482. }
  52483. if (!node.jointName && meshIncluded) {
  52484. newNode = importNode(gltfRuntime, node, id, parent);
  52485. if (newNode !== null) {
  52486. newNode.id = id;
  52487. newNode.parent = parent;
  52488. }
  52489. }
  52490. if (node.children) {
  52491. for (var i = 0; i < node.children.length; i++) {
  52492. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  52493. }
  52494. }
  52495. };
  52496. /**
  52497. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  52498. */
  52499. var postLoad = function (gltfRuntime) {
  52500. // Nodes
  52501. var currentScene = gltfRuntime.currentScene;
  52502. if (currentScene) {
  52503. for (var i = 0; i < currentScene.nodes.length; i++) {
  52504. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52505. }
  52506. }
  52507. else {
  52508. for (var thing in gltfRuntime.scenes) {
  52509. currentScene = gltfRuntime.scenes[thing];
  52510. for (var i = 0; i < currentScene.nodes.length; i++) {
  52511. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52512. }
  52513. }
  52514. }
  52515. // Set animations
  52516. loadAnimations(gltfRuntime);
  52517. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  52518. var skeleton = gltfRuntime.scene.skeletons[i];
  52519. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  52520. }
  52521. };
  52522. /**
  52523. * onBind shaderrs callback to set uniforms and matrices
  52524. */
  52525. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  52526. var materialValues = material.values || technique.parameters;
  52527. for (var unif in unTreatedUniforms) {
  52528. var uniform = unTreatedUniforms[unif];
  52529. var type = uniform.type;
  52530. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  52531. if (uniform.semantic && !uniform.source && !uniform.node) {
  52532. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  52533. }
  52534. else if (uniform.semantic && (uniform.source || uniform.node)) {
  52535. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  52536. if (source === null) {
  52537. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  52538. }
  52539. if (source === null) {
  52540. continue;
  52541. }
  52542. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  52543. }
  52544. }
  52545. else {
  52546. var value = materialValues[technique.uniforms[unif]];
  52547. if (!value) {
  52548. continue;
  52549. }
  52550. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  52551. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  52552. if (texture === null || texture === undefined) {
  52553. continue;
  52554. }
  52555. shaderMaterial.getEffect().setTexture(unif, texture);
  52556. }
  52557. else {
  52558. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  52559. }
  52560. }
  52561. }
  52562. onSuccess(shaderMaterial);
  52563. };
  52564. /**
  52565. * Prepare uniforms to send the only one time
  52566. * Loads the appropriate textures
  52567. */
  52568. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  52569. var materialValues = material.values || technique.parameters;
  52570. var techniqueUniforms = technique.uniforms;
  52571. /**
  52572. * Prepare values here (not matrices)
  52573. */
  52574. for (var unif in unTreatedUniforms) {
  52575. var uniform = unTreatedUniforms[unif];
  52576. var type = uniform.type;
  52577. var value = materialValues[techniqueUniforms[unif]];
  52578. if (value === undefined) {
  52579. // In case the value is the same for all materials
  52580. value = uniform.value;
  52581. }
  52582. if (!value) {
  52583. continue;
  52584. }
  52585. var onLoadTexture = function (uniformName) {
  52586. return function (texture) {
  52587. if (uniform.value) {
  52588. // Static uniform
  52589. shaderMaterial.setTexture(uniformName, texture);
  52590. delete unTreatedUniforms[uniformName];
  52591. }
  52592. };
  52593. };
  52594. // Texture (sampler2D)
  52595. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  52596. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  52597. }
  52598. else {
  52599. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  52600. // Static uniform
  52601. delete unTreatedUniforms[unif];
  52602. }
  52603. }
  52604. }
  52605. };
  52606. /**
  52607. * Shader compilation failed
  52608. */
  52609. var onShaderCompileError = function (program, shaderMaterial, onError) {
  52610. return function (effect, error) {
  52611. shaderMaterial.dispose(true);
  52612. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  52613. };
  52614. };
  52615. /**
  52616. * Shader compilation success
  52617. */
  52618. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  52619. return function (_) {
  52620. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  52621. shaderMaterial.onBind = function (mesh) {
  52622. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  52623. };
  52624. };
  52625. };
  52626. /**
  52627. * Returns the appropriate uniform if already handled by babylon
  52628. */
  52629. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  52630. for (var unif in technique.uniforms) {
  52631. var uniform = technique.uniforms[unif];
  52632. var uniformParameter = technique.parameters[uniform];
  52633. if (tokenizer.currentIdentifier === unif) {
  52634. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  52635. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  52636. if (transformIndex !== -1) {
  52637. delete unTreatedUniforms[unif];
  52638. return babylonTransforms[transformIndex];
  52639. }
  52640. }
  52641. }
  52642. }
  52643. return tokenizer.currentIdentifier;
  52644. };
  52645. /**
  52646. * All shaders loaded. Create materials one by one
  52647. */
  52648. var importMaterials = function (gltfRuntime) {
  52649. // Create materials
  52650. for (var mat in gltfRuntime.materials) {
  52651. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  52652. }
  52653. };
  52654. /**
  52655. * Implementation of the base glTF spec
  52656. */
  52657. var GLTFLoaderBase = (function () {
  52658. function GLTFLoaderBase() {
  52659. }
  52660. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  52661. var gltfRuntime = {
  52662. extensions: {},
  52663. accessors: {},
  52664. buffers: {},
  52665. bufferViews: {},
  52666. meshes: {},
  52667. lights: {},
  52668. cameras: {},
  52669. nodes: {},
  52670. images: {},
  52671. textures: {},
  52672. shaders: {},
  52673. programs: {},
  52674. samplers: {},
  52675. techniques: {},
  52676. materials: {},
  52677. animations: {},
  52678. skins: {},
  52679. extensionsUsed: [],
  52680. scenes: {},
  52681. buffersCount: 0,
  52682. shaderscount: 0,
  52683. scene: scene,
  52684. rootUrl: rootUrl,
  52685. loadedBufferCount: 0,
  52686. loadedBufferViews: {},
  52687. loadedShaderCount: 0,
  52688. importOnlyMeshes: false,
  52689. dummyNodes: []
  52690. };
  52691. // Parse
  52692. if (parsedData.extensions) {
  52693. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  52694. }
  52695. if (parsedData.extensionsUsed) {
  52696. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  52697. }
  52698. if (parsedData.buffers) {
  52699. parseBuffers(parsedData.buffers, gltfRuntime);
  52700. }
  52701. if (parsedData.bufferViews) {
  52702. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  52703. }
  52704. if (parsedData.accessors) {
  52705. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  52706. }
  52707. if (parsedData.meshes) {
  52708. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  52709. }
  52710. if (parsedData.lights) {
  52711. parseObject(parsedData.lights, "lights", gltfRuntime);
  52712. }
  52713. if (parsedData.cameras) {
  52714. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  52715. }
  52716. if (parsedData.nodes) {
  52717. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  52718. }
  52719. if (parsedData.images) {
  52720. parseObject(parsedData.images, "images", gltfRuntime);
  52721. }
  52722. if (parsedData.textures) {
  52723. parseObject(parsedData.textures, "textures", gltfRuntime);
  52724. }
  52725. if (parsedData.shaders) {
  52726. parseShaders(parsedData.shaders, gltfRuntime);
  52727. }
  52728. if (parsedData.programs) {
  52729. parseObject(parsedData.programs, "programs", gltfRuntime);
  52730. }
  52731. if (parsedData.samplers) {
  52732. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  52733. }
  52734. if (parsedData.techniques) {
  52735. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  52736. }
  52737. if (parsedData.materials) {
  52738. parseObject(parsedData.materials, "materials", gltfRuntime);
  52739. }
  52740. if (parsedData.animations) {
  52741. parseObject(parsedData.animations, "animations", gltfRuntime);
  52742. }
  52743. if (parsedData.skins) {
  52744. parseObject(parsedData.skins, "skins", gltfRuntime);
  52745. }
  52746. if (parsedData.scenes) {
  52747. gltfRuntime.scenes = parsedData.scenes;
  52748. }
  52749. if (parsedData.scene && parsedData.scenes) {
  52750. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  52751. }
  52752. return gltfRuntime;
  52753. };
  52754. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  52755. var buffer = gltfRuntime.buffers[id];
  52756. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  52757. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  52758. }
  52759. else {
  52760. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  52761. onError(request.status + " " + request.statusText);
  52762. });
  52763. }
  52764. };
  52765. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  52766. var texture = gltfRuntime.textures[id];
  52767. if (!texture || !texture.source) {
  52768. onError(null);
  52769. return;
  52770. }
  52771. if (texture.babylonTexture) {
  52772. onSuccess(null);
  52773. return;
  52774. }
  52775. var source = gltfRuntime.images[texture.source];
  52776. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  52777. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  52778. }
  52779. else {
  52780. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  52781. onError(request.status + " " + request.statusText);
  52782. });
  52783. }
  52784. };
  52785. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  52786. var texture = gltfRuntime.textures[id];
  52787. if (texture.babylonTexture) {
  52788. onSuccess(texture.babylonTexture);
  52789. return;
  52790. }
  52791. var sampler = gltfRuntime.samplers[texture.sampler];
  52792. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  52793. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  52794. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  52795. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  52796. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  52797. var blob = new Blob([buffer]);
  52798. var blobURL = URL.createObjectURL(blob);
  52799. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  52800. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  52801. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  52802. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  52803. newTexture.name = id;
  52804. texture.babylonTexture = newTexture;
  52805. onSuccess(newTexture);
  52806. };
  52807. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  52808. var shader = gltfRuntime.shaders[id];
  52809. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  52810. var shaderString = atob(shader.uri.split(",")[1]);
  52811. onSuccess(shaderString);
  52812. }
  52813. else {
  52814. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  52815. onError(request.status + " " + request.statusText);
  52816. });
  52817. }
  52818. };
  52819. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  52820. var material = gltfRuntime.materials[id];
  52821. var technique = gltfRuntime.techniques[material.technique];
  52822. if (!technique) {
  52823. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  52824. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  52825. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  52826. onSuccess(defaultMaterial);
  52827. return;
  52828. }
  52829. var program = gltfRuntime.programs[technique.program];
  52830. var states = technique.states;
  52831. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  52832. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  52833. var newVertexShader = "";
  52834. var newPixelShader = "";
  52835. var vertexTokenizer = new Tokenizer(vertexShader);
  52836. var pixelTokenizer = new Tokenizer(pixelShader);
  52837. var unTreatedUniforms = {};
  52838. var uniforms = [];
  52839. var attributes = [];
  52840. var samplers = [];
  52841. // Fill uniform, sampler2D and attributes
  52842. for (var unif in technique.uniforms) {
  52843. var uniform = technique.uniforms[unif];
  52844. var uniformParameter = technique.parameters[uniform];
  52845. unTreatedUniforms[unif] = uniformParameter;
  52846. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  52847. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  52848. if (transformIndex !== -1) {
  52849. uniforms.push(babylonTransforms[transformIndex]);
  52850. delete unTreatedUniforms[unif];
  52851. }
  52852. else {
  52853. uniforms.push(unif);
  52854. }
  52855. }
  52856. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  52857. samplers.push(unif);
  52858. }
  52859. else {
  52860. uniforms.push(unif);
  52861. }
  52862. }
  52863. for (var attr in technique.attributes) {
  52864. var attribute = technique.attributes[attr];
  52865. var attributeParameter = technique.parameters[attribute];
  52866. if (attributeParameter.semantic) {
  52867. attributes.push(getAttribute(attributeParameter));
  52868. }
  52869. }
  52870. // Configure vertex shader
  52871. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  52872. var tokenType = vertexTokenizer.currentToken;
  52873. if (tokenType !== ETokenType.IDENTIFIER) {
  52874. newVertexShader += vertexTokenizer.currentString;
  52875. continue;
  52876. }
  52877. var foundAttribute = false;
  52878. for (var attr in technique.attributes) {
  52879. var attribute = technique.attributes[attr];
  52880. var attributeParameter = technique.parameters[attribute];
  52881. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  52882. newVertexShader += getAttribute(attributeParameter);
  52883. foundAttribute = true;
  52884. break;
  52885. }
  52886. }
  52887. if (foundAttribute) {
  52888. continue;
  52889. }
  52890. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  52891. }
  52892. // Configure pixel shader
  52893. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  52894. var tokenType = pixelTokenizer.currentToken;
  52895. if (tokenType !== ETokenType.IDENTIFIER) {
  52896. newPixelShader += pixelTokenizer.currentString;
  52897. continue;
  52898. }
  52899. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  52900. }
  52901. // Create shader material
  52902. var shaderPath = {
  52903. vertex: program.vertexShader + id,
  52904. fragment: program.fragmentShader + id
  52905. };
  52906. var options = {
  52907. attributes: attributes,
  52908. uniforms: uniforms,
  52909. samplers: samplers,
  52910. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  52911. };
  52912. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  52913. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  52914. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  52915. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  52916. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  52917. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  52918. if (states && states.functions) {
  52919. var functions = states.functions;
  52920. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  52921. shaderMaterial.backFaceCulling = false;
  52922. }
  52923. var blendFunc = functions.blendFuncSeparate;
  52924. if (blendFunc) {
  52925. 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) {
  52926. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  52927. }
  52928. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52929. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  52930. }
  52931. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52932. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  52933. }
  52934. 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) {
  52935. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  52936. }
  52937. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  52938. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  52939. }
  52940. 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) {
  52941. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  52942. }
  52943. }
  52944. }
  52945. };
  52946. return GLTFLoaderBase;
  52947. }());
  52948. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  52949. /**
  52950. * glTF V1 Loader
  52951. */
  52952. var GLTFLoader = (function () {
  52953. function GLTFLoader() {
  52954. }
  52955. GLTFLoader.RegisterExtension = function (extension) {
  52956. if (GLTFLoader.Extensions[extension.name]) {
  52957. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  52958. return;
  52959. }
  52960. GLTFLoader.Extensions[extension.name] = extension;
  52961. };
  52962. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  52963. var _this = this;
  52964. scene.useRightHandedSystem = true;
  52965. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  52966. gltfRuntime.importOnlyMeshes = true;
  52967. if (meshesNames === "") {
  52968. gltfRuntime.importMeshesNames = [];
  52969. }
  52970. else if (typeof meshesNames === "string") {
  52971. gltfRuntime.importMeshesNames = [meshesNames];
  52972. }
  52973. else if (meshesNames && !(meshesNames instanceof Array)) {
  52974. gltfRuntime.importMeshesNames = [meshesNames];
  52975. }
  52976. else {
  52977. gltfRuntime.importMeshesNames = [];
  52978. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  52979. }
  52980. // Create nodes
  52981. _this._createNodes(gltfRuntime);
  52982. var meshes = [];
  52983. var skeletons = [];
  52984. // Fill arrays of meshes and skeletons
  52985. for (var nde in gltfRuntime.nodes) {
  52986. var node = gltfRuntime.nodes[nde];
  52987. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  52988. meshes.push(node.babylonNode);
  52989. }
  52990. }
  52991. for (var skl in gltfRuntime.skins) {
  52992. var skin = gltfRuntime.skins[skl];
  52993. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  52994. skeletons.push(skin.babylonSkeleton);
  52995. }
  52996. }
  52997. // Load buffers, shaders, materials, etc.
  52998. _this._loadBuffersAsync(gltfRuntime, function () {
  52999. _this._loadShadersAsync(gltfRuntime, function () {
  53000. importMaterials(gltfRuntime);
  53001. postLoad(gltfRuntime);
  53002. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  53003. onSuccess(meshes, null, skeletons);
  53004. }
  53005. });
  53006. }, onProgress);
  53007. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  53008. onSuccess(meshes, null, skeletons);
  53009. }
  53010. }, onError);
  53011. return true;
  53012. };
  53013. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  53014. var _this = this;
  53015. scene.useRightHandedSystem = true;
  53016. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  53017. // Load runtime extensios
  53018. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  53019. // Create nodes
  53020. _this._createNodes(gltfRuntime);
  53021. // Load buffers, shaders, materials, etc.
  53022. _this._loadBuffersAsync(gltfRuntime, function () {
  53023. _this._loadShadersAsync(gltfRuntime, function () {
  53024. importMaterials(gltfRuntime);
  53025. postLoad(gltfRuntime);
  53026. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  53027. onSuccess();
  53028. }
  53029. });
  53030. });
  53031. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  53032. onSuccess();
  53033. }
  53034. }, onError);
  53035. }, onError);
  53036. };
  53037. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  53038. var hasShaders = false;
  53039. var processShader = function (sha, shader) {
  53040. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  53041. gltfRuntime.loadedShaderCount++;
  53042. if (shaderString) {
  53043. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  53044. }
  53045. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  53046. onload();
  53047. }
  53048. }, function () {
  53049. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  53050. });
  53051. };
  53052. for (var sha in gltfRuntime.shaders) {
  53053. hasShaders = true;
  53054. var shader = gltfRuntime.shaders[sha];
  53055. if (shader) {
  53056. processShader.bind(this, sha, shader)();
  53057. }
  53058. else {
  53059. BABYLON.Tools.Error("No shader named: " + sha);
  53060. }
  53061. }
  53062. if (!hasShaders) {
  53063. onload();
  53064. }
  53065. };
  53066. ;
  53067. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  53068. var hasBuffers = false;
  53069. var processBuffer = function (buf, buffer) {
  53070. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  53071. gltfRuntime.loadedBufferCount++;
  53072. if (bufferView) {
  53073. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  53074. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  53075. }
  53076. gltfRuntime.loadedBufferViews[buf] = bufferView;
  53077. }
  53078. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  53079. onLoad();
  53080. }
  53081. }, function () {
  53082. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  53083. });
  53084. };
  53085. for (var buf in gltfRuntime.buffers) {
  53086. hasBuffers = true;
  53087. var buffer = gltfRuntime.buffers[buf];
  53088. if (buffer) {
  53089. processBuffer.bind(this, buf, buffer)();
  53090. }
  53091. else {
  53092. BABYLON.Tools.Error("No buffer named: " + buf);
  53093. }
  53094. }
  53095. if (!hasBuffers) {
  53096. onLoad();
  53097. }
  53098. };
  53099. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  53100. var currentScene = gltfRuntime.currentScene;
  53101. if (currentScene) {
  53102. // Only one scene even if multiple scenes are defined
  53103. for (var i = 0; i < currentScene.nodes.length; i++) {
  53104. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  53105. }
  53106. }
  53107. else {
  53108. // Load all scenes
  53109. for (var thing in gltfRuntime.scenes) {
  53110. currentScene = gltfRuntime.scenes[thing];
  53111. for (var i = 0; i < currentScene.nodes.length; i++) {
  53112. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  53113. }
  53114. }
  53115. }
  53116. };
  53117. GLTFLoader.Extensions = {};
  53118. return GLTFLoader;
  53119. }());
  53120. GLTF1.GLTFLoader = GLTFLoader;
  53121. ;
  53122. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  53123. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53124. })(BABYLON || (BABYLON = {}));
  53125. //# sourceMappingURL=babylon.glTFLoader.js.map
  53126. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53127. var BABYLON;
  53128. (function (BABYLON) {
  53129. var GLTF1;
  53130. (function (GLTF1) {
  53131. /**
  53132. * Utils functions for GLTF
  53133. */
  53134. var GLTFUtils = (function () {
  53135. function GLTFUtils() {
  53136. }
  53137. /**
  53138. * Sets the given "parameter" matrix
  53139. * @param scene: the {BABYLON.Scene} object
  53140. * @param source: the source node where to pick the matrix
  53141. * @param parameter: the GLTF technique parameter
  53142. * @param uniformName: the name of the shader's uniform
  53143. * @param shaderMaterial: the shader material
  53144. */
  53145. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  53146. var mat = null;
  53147. if (parameter.semantic === "MODEL") {
  53148. mat = source.getWorldMatrix();
  53149. }
  53150. else if (parameter.semantic === "PROJECTION") {
  53151. mat = scene.getProjectionMatrix();
  53152. }
  53153. else if (parameter.semantic === "VIEW") {
  53154. mat = scene.getViewMatrix();
  53155. }
  53156. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  53157. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  53158. }
  53159. else if (parameter.semantic === "MODELVIEW") {
  53160. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  53161. }
  53162. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  53163. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  53164. }
  53165. else if (parameter.semantic === "MODELINVERSE") {
  53166. mat = source.getWorldMatrix().invert();
  53167. }
  53168. else if (parameter.semantic === "VIEWINVERSE") {
  53169. mat = scene.getViewMatrix().invert();
  53170. }
  53171. else if (parameter.semantic === "PROJECTIONINVERSE") {
  53172. mat = scene.getProjectionMatrix().invert();
  53173. }
  53174. else if (parameter.semantic === "MODELVIEWINVERSE") {
  53175. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  53176. }
  53177. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  53178. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  53179. }
  53180. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  53181. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  53182. }
  53183. else {
  53184. debugger;
  53185. }
  53186. switch (parameter.type) {
  53187. case GLTF1.EParameterType.FLOAT_MAT2:
  53188. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  53189. break;
  53190. case GLTF1.EParameterType.FLOAT_MAT3:
  53191. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  53192. break;
  53193. case GLTF1.EParameterType.FLOAT_MAT4:
  53194. shaderMaterial.setMatrix(uniformName, mat);
  53195. break;
  53196. default: break;
  53197. }
  53198. };
  53199. /**
  53200. * Sets the given "parameter" matrix
  53201. * @param shaderMaterial: the shader material
  53202. * @param uniform: the name of the shader's uniform
  53203. * @param value: the value of the uniform
  53204. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  53205. */
  53206. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  53207. switch (type) {
  53208. case GLTF1.EParameterType.FLOAT:
  53209. shaderMaterial.setFloat(uniform, value);
  53210. return true;
  53211. case GLTF1.EParameterType.FLOAT_VEC2:
  53212. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  53213. return true;
  53214. case GLTF1.EParameterType.FLOAT_VEC3:
  53215. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  53216. return true;
  53217. case GLTF1.EParameterType.FLOAT_VEC4:
  53218. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  53219. return true;
  53220. default: return false;
  53221. }
  53222. };
  53223. /**
  53224. * If the uri is a base64 string
  53225. * @param uri: the uri to test
  53226. */
  53227. GLTFUtils.IsBase64 = function (uri) {
  53228. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  53229. };
  53230. /**
  53231. * Decode the base64 uri
  53232. * @param uri: the uri to decode
  53233. */
  53234. GLTFUtils.DecodeBase64 = function (uri) {
  53235. var decodedString = atob(uri.split(",")[1]);
  53236. var bufferLength = decodedString.length;
  53237. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  53238. for (var i = 0; i < bufferLength; i++) {
  53239. bufferView[i] = decodedString.charCodeAt(i);
  53240. }
  53241. return bufferView.buffer;
  53242. };
  53243. /**
  53244. * Returns the wrap mode of the texture
  53245. * @param mode: the mode value
  53246. */
  53247. GLTFUtils.GetWrapMode = function (mode) {
  53248. switch (mode) {
  53249. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  53250. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  53251. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  53252. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  53253. }
  53254. };
  53255. /**
  53256. * Returns the byte stride giving an accessor
  53257. * @param accessor: the GLTF accessor objet
  53258. */
  53259. GLTFUtils.GetByteStrideFromType = function (accessor) {
  53260. // Needs this function since "byteStride" isn't requiered in glTF format
  53261. var type = accessor.type;
  53262. switch (type) {
  53263. case "VEC2": return 2;
  53264. case "VEC3": return 3;
  53265. case "VEC4": return 4;
  53266. case "MAT2": return 4;
  53267. case "MAT3": return 9;
  53268. case "MAT4": return 16;
  53269. default: return 1;
  53270. }
  53271. };
  53272. /**
  53273. * Returns the texture filter mode giving a mode value
  53274. * @param mode: the filter mode value
  53275. */
  53276. GLTFUtils.GetTextureFilterMode = function (mode) {
  53277. switch (mode) {
  53278. case GLTF1.ETextureFilterType.LINEAR:
  53279. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  53280. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  53281. case GLTF1.ETextureFilterType.NEAREST:
  53282. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  53283. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  53284. }
  53285. };
  53286. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  53287. var byteOffset = bufferView.byteOffset + byteOffset;
  53288. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  53289. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  53290. throw new Error("Buffer access is out of range");
  53291. }
  53292. var buffer = loadedBufferView.buffer;
  53293. byteOffset += loadedBufferView.byteOffset;
  53294. switch (componentType) {
  53295. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  53296. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  53297. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  53298. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  53299. default: return new Float32Array(buffer, byteOffset, byteLength);
  53300. }
  53301. };
  53302. /**
  53303. * Returns a buffer from its accessor
  53304. * @param gltfRuntime: the GLTF runtime
  53305. * @param accessor: the GLTF accessor
  53306. */
  53307. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  53308. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  53309. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  53310. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  53311. };
  53312. /**
  53313. * Decodes a buffer view into a string
  53314. * @param view: the buffer view
  53315. */
  53316. GLTFUtils.DecodeBufferToText = function (view) {
  53317. var result = "";
  53318. var length = view.byteLength;
  53319. for (var i = 0; i < length; ++i) {
  53320. result += String.fromCharCode(view[i]);
  53321. }
  53322. return result;
  53323. };
  53324. /**
  53325. * Returns the default material of gltf. Related to
  53326. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  53327. * @param scene: the Babylon.js scene
  53328. */
  53329. GLTFUtils.GetDefaultMaterial = function (scene) {
  53330. if (!GLTFUtils._DefaultMaterial) {
  53331. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  53332. "precision highp float;",
  53333. "",
  53334. "uniform mat4 worldView;",
  53335. "uniform mat4 projection;",
  53336. "",
  53337. "attribute vec3 position;",
  53338. "",
  53339. "void main(void)",
  53340. "{",
  53341. " gl_Position = projection * worldView * vec4(position, 1.0);",
  53342. "}"
  53343. ].join("\n");
  53344. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  53345. "precision highp float;",
  53346. "",
  53347. "uniform vec4 u_emission;",
  53348. "",
  53349. "void main(void)",
  53350. "{",
  53351. " gl_FragColor = u_emission;",
  53352. "}"
  53353. ].join("\n");
  53354. var shaderPath = {
  53355. vertex: "GLTFDefaultMaterial",
  53356. fragment: "GLTFDefaultMaterial"
  53357. };
  53358. var options = {
  53359. attributes: ["position"],
  53360. uniforms: ["worldView", "projection", "u_emission"],
  53361. samplers: [],
  53362. needAlphaBlending: false
  53363. };
  53364. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  53365. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  53366. }
  53367. return GLTFUtils._DefaultMaterial;
  53368. };
  53369. // The GLTF default material
  53370. GLTFUtils._DefaultMaterial = null;
  53371. return GLTFUtils;
  53372. }());
  53373. GLTF1.GLTFUtils = GLTFUtils;
  53374. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53375. })(BABYLON || (BABYLON = {}));
  53376. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  53377. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53378. var BABYLON;
  53379. (function (BABYLON) {
  53380. var GLTF1;
  53381. (function (GLTF1) {
  53382. var GLTFLoaderExtension = (function () {
  53383. function GLTFLoaderExtension(name) {
  53384. this._name = name;
  53385. }
  53386. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  53387. get: function () {
  53388. return this._name;
  53389. },
  53390. enumerable: true,
  53391. configurable: true
  53392. });
  53393. /**
  53394. * Defines an override for loading the runtime
  53395. * Return true to stop further extensions from loading the runtime
  53396. */
  53397. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53398. return false;
  53399. };
  53400. /**
  53401. * Defines an onverride for creating gltf runtime
  53402. * Return true to stop further extensions from creating the runtime
  53403. */
  53404. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53405. return false;
  53406. };
  53407. /**
  53408. * Defines an override for loading buffers
  53409. * Return true to stop further extensions from loading this buffer
  53410. */
  53411. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  53412. return false;
  53413. };
  53414. /**
  53415. * Defines an override for loading texture buffers
  53416. * Return true to stop further extensions from loading this texture data
  53417. */
  53418. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53419. return false;
  53420. };
  53421. /**
  53422. * Defines an override for creating textures
  53423. * Return true to stop further extensions from loading this texture
  53424. */
  53425. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  53426. return false;
  53427. };
  53428. /**
  53429. * Defines an override for loading shader strings
  53430. * Return true to stop further extensions from loading this shader data
  53431. */
  53432. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53433. return false;
  53434. };
  53435. /**
  53436. * Defines an override for loading materials
  53437. * Return true to stop further extensions from loading this material
  53438. */
  53439. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53440. return false;
  53441. };
  53442. // ---------
  53443. // Utilities
  53444. // ---------
  53445. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53446. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53447. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  53448. }, function () {
  53449. setTimeout(function () {
  53450. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  53451. });
  53452. });
  53453. };
  53454. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53455. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53456. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  53457. }, function () {
  53458. setTimeout(function () {
  53459. onSuccess();
  53460. });
  53461. });
  53462. };
  53463. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  53464. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53465. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  53466. }, function () {
  53467. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  53468. });
  53469. };
  53470. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  53471. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  53472. };
  53473. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53474. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53475. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  53476. }, function () {
  53477. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  53478. });
  53479. };
  53480. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53481. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53482. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  53483. }, function () {
  53484. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  53485. });
  53486. };
  53487. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53488. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53489. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  53490. }, function () {
  53491. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  53492. });
  53493. };
  53494. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  53495. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53496. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  53497. }, function () {
  53498. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  53499. });
  53500. };
  53501. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  53502. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  53503. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  53504. if (func(loaderExtension)) {
  53505. return;
  53506. }
  53507. }
  53508. defaultFunc();
  53509. };
  53510. return GLTFLoaderExtension;
  53511. }());
  53512. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  53513. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53514. })(BABYLON || (BABYLON = {}));
  53515. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  53516. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53517. var BABYLON;
  53518. (function (BABYLON) {
  53519. var GLTF1;
  53520. (function (GLTF1) {
  53521. var BinaryExtensionBufferName = "binary_glTF";
  53522. var EContentFormat;
  53523. (function (EContentFormat) {
  53524. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  53525. })(EContentFormat || (EContentFormat = {}));
  53526. ;
  53527. ;
  53528. ;
  53529. var GLTFBinaryExtension = (function (_super) {
  53530. __extends(GLTFBinaryExtension, _super);
  53531. function GLTFBinaryExtension() {
  53532. return _super.call(this, "KHR_binary_glTF") || this;
  53533. }
  53534. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53535. var extensionsUsed = data.json.extensionsUsed;
  53536. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  53537. return false;
  53538. }
  53539. this._bin = data.bin;
  53540. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  53541. return true;
  53542. };
  53543. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53544. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  53545. return false;
  53546. }
  53547. if (id !== BinaryExtensionBufferName) {
  53548. return false;
  53549. }
  53550. onSuccess(this._bin);
  53551. return true;
  53552. };
  53553. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53554. var texture = gltfRuntime.textures[id];
  53555. var source = gltfRuntime.images[texture.source];
  53556. if (!source.extensions || !(this.name in source.extensions)) {
  53557. return false;
  53558. }
  53559. var sourceExt = source.extensions[this.name];
  53560. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  53561. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  53562. onSuccess(buffer);
  53563. return true;
  53564. };
  53565. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53566. var shader = gltfRuntime.shaders[id];
  53567. if (!shader.extensions || !(this.name in shader.extensions)) {
  53568. return false;
  53569. }
  53570. var binaryExtensionShader = shader.extensions[this.name];
  53571. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  53572. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  53573. setTimeout(function () {
  53574. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  53575. onSuccess(shaderString);
  53576. });
  53577. return true;
  53578. };
  53579. return GLTFBinaryExtension;
  53580. }(GLTF1.GLTFLoaderExtension));
  53581. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  53582. var BinaryReader = (function () {
  53583. function BinaryReader(arrayBuffer) {
  53584. this._arrayBuffer = arrayBuffer;
  53585. this._dataView = new DataView(arrayBuffer);
  53586. this._byteOffset = 0;
  53587. }
  53588. BinaryReader.prototype.getUint32 = function () {
  53589. var value = this._dataView.getUint32(this._byteOffset, true);
  53590. this._byteOffset += 4;
  53591. return value;
  53592. };
  53593. BinaryReader.prototype.getUint8Array = function (length) {
  53594. if (!length) {
  53595. length = this._arrayBuffer.byteLength - this._byteOffset;
  53596. }
  53597. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  53598. this._byteOffset += length;
  53599. return value;
  53600. };
  53601. return BinaryReader;
  53602. }());
  53603. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  53604. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53605. })(BABYLON || (BABYLON = {}));
  53606. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  53607. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53608. var BABYLON;
  53609. (function (BABYLON) {
  53610. var GLTF1;
  53611. (function (GLTF1) {
  53612. ;
  53613. ;
  53614. ;
  53615. var GLTFMaterialsCommonExtension = (function (_super) {
  53616. __extends(GLTFMaterialsCommonExtension, _super);
  53617. function GLTFMaterialsCommonExtension() {
  53618. return _super.call(this, "KHR_materials_common") || this;
  53619. }
  53620. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53621. if (!gltfRuntime.extensions)
  53622. return false;
  53623. var extension = gltfRuntime.extensions[this.name];
  53624. if (!extension)
  53625. return false;
  53626. // Create lights
  53627. var lights = extension.lights;
  53628. if (lights) {
  53629. for (var thing in lights) {
  53630. var light = lights[thing];
  53631. switch (light.type) {
  53632. case "ambient":
  53633. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  53634. var ambient = light.ambient;
  53635. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  53636. break;
  53637. case "point":
  53638. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  53639. var point = light.point;
  53640. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  53641. break;
  53642. case "directional":
  53643. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  53644. var directional = light.directional;
  53645. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  53646. break;
  53647. case "spot":
  53648. var spot = light.spot;
  53649. 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);
  53650. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  53651. break;
  53652. default:
  53653. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  53654. break;
  53655. }
  53656. }
  53657. }
  53658. return false;
  53659. };
  53660. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53661. var material = gltfRuntime.materials[id];
  53662. if (!material || !material.extensions)
  53663. return false;
  53664. var extension = material.extensions[this.name];
  53665. if (!extension)
  53666. return false;
  53667. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  53668. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  53669. if (extension.technique === "CONSTANT") {
  53670. standardMaterial.disableLighting = true;
  53671. }
  53672. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  53673. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  53674. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  53675. // Ambient
  53676. if (typeof extension.values.ambient === "string") {
  53677. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  53678. }
  53679. else {
  53680. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  53681. }
  53682. // Diffuse
  53683. if (typeof extension.values.diffuse === "string") {
  53684. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  53685. }
  53686. else {
  53687. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  53688. }
  53689. // Emission
  53690. if (typeof extension.values.emission === "string") {
  53691. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  53692. }
  53693. else {
  53694. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  53695. }
  53696. // Specular
  53697. if (typeof extension.values.specular === "string") {
  53698. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  53699. }
  53700. else {
  53701. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  53702. }
  53703. return true;
  53704. };
  53705. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  53706. // Create buffer from texture url
  53707. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  53708. // Create texture from buffer
  53709. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  53710. }, onError);
  53711. };
  53712. return GLTFMaterialsCommonExtension;
  53713. }(GLTF1.GLTFLoaderExtension));
  53714. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  53715. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  53716. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53717. })(BABYLON || (BABYLON = {}));
  53718. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  53719. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53720. var BABYLON;
  53721. (function (BABYLON) {
  53722. var GLTF2;
  53723. (function (GLTF2) {
  53724. /**
  53725. * Enums
  53726. */
  53727. var EComponentType;
  53728. (function (EComponentType) {
  53729. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  53730. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  53731. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  53732. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  53733. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  53734. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  53735. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  53736. var EMeshPrimitiveMode;
  53737. (function (EMeshPrimitiveMode) {
  53738. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  53739. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  53740. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  53741. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  53742. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  53743. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  53744. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  53745. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  53746. var ETextureMagFilter;
  53747. (function (ETextureMagFilter) {
  53748. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  53749. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  53750. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  53751. var ETextureMinFilter;
  53752. (function (ETextureMinFilter) {
  53753. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  53754. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  53755. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  53756. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  53757. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  53758. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  53759. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  53760. var ETextureWrapMode;
  53761. (function (ETextureWrapMode) {
  53762. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  53763. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  53764. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  53765. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  53766. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  53767. })(BABYLON || (BABYLON = {}));
  53768. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  53769. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53770. var BABYLON;
  53771. (function (BABYLON) {
  53772. var GLTF2;
  53773. (function (GLTF2) {
  53774. var GLTFLoader = (function () {
  53775. function GLTFLoader(parent) {
  53776. this._renderReady = false;
  53777. this._disposed = false;
  53778. this._objectURLs = new Array();
  53779. this._blockPendingTracking = false;
  53780. // Observable with boolean indicating success or error.
  53781. this._renderReadyObservable = new BABYLON.Observable();
  53782. // Count of pending work that needs to complete before the asset is rendered.
  53783. this._renderPendingCount = 0;
  53784. // Count of pending work that needs to complete before the loader is cleared.
  53785. this._loaderPendingCount = 0;
  53786. this._parent = parent;
  53787. }
  53788. GLTFLoader.RegisterExtension = function (extension) {
  53789. if (GLTFLoader.Extensions[extension.name]) {
  53790. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  53791. return;
  53792. }
  53793. GLTFLoader.Extensions[extension.name] = extension;
  53794. // Keep the order of registration so that extensions registered first are called first.
  53795. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  53796. };
  53797. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  53798. get: function () {
  53799. return this._gltf;
  53800. },
  53801. enumerable: true,
  53802. configurable: true
  53803. });
  53804. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  53805. get: function () {
  53806. return this._babylonScene;
  53807. },
  53808. enumerable: true,
  53809. configurable: true
  53810. });
  53811. GLTFLoader.prototype.executeWhenRenderReady = function (func) {
  53812. if (this._renderReady) {
  53813. func();
  53814. }
  53815. else {
  53816. this._renderReadyObservable.add(func);
  53817. }
  53818. };
  53819. GLTFLoader.prototype.dispose = function () {
  53820. if (this._disposed) {
  53821. return;
  53822. }
  53823. this._disposed = true;
  53824. // Revoke object urls created during load
  53825. this._objectURLs.forEach(function (url) { return URL.revokeObjectURL(url); });
  53826. this._objectURLs.length = 0;
  53827. this._gltf = undefined;
  53828. this._babylonScene = undefined;
  53829. this._rootUrl = undefined;
  53830. this._defaultMaterial = undefined;
  53831. this._successCallback = undefined;
  53832. this._errorCallback = undefined;
  53833. this._renderReady = false;
  53834. this._renderReadyObservable.clear();
  53835. this._renderPendingCount = 0;
  53836. this._loaderPendingCount = 0;
  53837. };
  53838. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53839. var _this = this;
  53840. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  53841. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  53842. }, onProgress, onError);
  53843. };
  53844. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  53845. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  53846. };
  53847. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53848. this._loadData(data);
  53849. this._babylonScene = scene;
  53850. this._rootUrl = rootUrl;
  53851. this._successCallback = onSuccess;
  53852. this._progressCallback = onProgress;
  53853. this._errorCallback = onError;
  53854. this.addPendingData(this);
  53855. this._loadScene(nodeNames);
  53856. this._loadAnimations();
  53857. this.removePendingData(this);
  53858. };
  53859. GLTFLoader.prototype._onError = function (message) {
  53860. this._errorCallback(message);
  53861. this.dispose();
  53862. };
  53863. GLTFLoader.prototype._onProgress = function (event) {
  53864. this._progressCallback(event);
  53865. };
  53866. GLTFLoader.prototype._onRenderReady = function () {
  53867. switch (this._parent.coordinateSystemMode) {
  53868. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  53869. if (!this._babylonScene.useRightHandedSystem) {
  53870. this._addRightHandToLeftHandRootTransform();
  53871. }
  53872. break;
  53873. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  53874. // do nothing
  53875. break;
  53876. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  53877. this._babylonScene.useRightHandedSystem = true;
  53878. break;
  53879. default:
  53880. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  53881. break;
  53882. }
  53883. this._showMeshes();
  53884. this._startAnimations();
  53885. this._successCallback();
  53886. this._renderReadyObservable.notifyObservers(this);
  53887. };
  53888. GLTFLoader.prototype._onLoaderComplete = function () {
  53889. if (this._parent.onComplete) {
  53890. this._parent.onComplete();
  53891. }
  53892. };
  53893. GLTFLoader.prototype._onLoaderFirstLODComplete = function () {
  53894. if (this._parent.onFirstLODComplete) {
  53895. this._parent.onFirstLODComplete();
  53896. }
  53897. };
  53898. GLTFLoader.prototype._loadData = function (data) {
  53899. this._gltf = data.json;
  53900. var binaryBuffer;
  53901. var buffers = this._gltf.buffers;
  53902. if (buffers.length > 0 && buffers[0].uri === undefined) {
  53903. binaryBuffer = buffers[0];
  53904. }
  53905. if (data.bin) {
  53906. if (binaryBuffer) {
  53907. if (binaryBuffer.byteLength != data.bin.byteLength) {
  53908. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  53909. }
  53910. }
  53911. else {
  53912. BABYLON.Tools.Warn("Unexpected BIN chunk");
  53913. }
  53914. binaryBuffer.loadedData = data.bin;
  53915. }
  53916. };
  53917. GLTFLoader.prototype._addRightHandToLeftHandRootTransform = function () {
  53918. var rootMesh = new BABYLON.Mesh("root", this._babylonScene);
  53919. rootMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  53920. rootMesh.rotation.y = Math.PI;
  53921. var nodes = this._gltf.nodes;
  53922. for (var i = 0; i < nodes.length; i++) {
  53923. var mesh = nodes[i].babylonMesh;
  53924. if (mesh && !mesh.parent) {
  53925. mesh.parent = rootMesh;
  53926. }
  53927. }
  53928. };
  53929. GLTFLoader.prototype._getMeshes = function () {
  53930. var meshes = [];
  53931. var nodes = this._gltf.nodes;
  53932. if (nodes) {
  53933. nodes.forEach(function (node) {
  53934. if (node.babylonMesh) {
  53935. meshes.push(node.babylonMesh);
  53936. }
  53937. });
  53938. }
  53939. return meshes;
  53940. };
  53941. GLTFLoader.prototype._getSkeletons = function () {
  53942. var skeletons = [];
  53943. var skins = this._gltf.skins;
  53944. if (skins) {
  53945. skins.forEach(function (skin) {
  53946. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  53947. skeletons.push(skin.babylonSkeleton);
  53948. }
  53949. });
  53950. }
  53951. return skeletons;
  53952. };
  53953. GLTFLoader.prototype._getAnimationTargets = function () {
  53954. var targets = [];
  53955. var animations = this._gltf.animations;
  53956. if (animations) {
  53957. animations.forEach(function (animation) {
  53958. targets.push.apply(targets, animation.targets);
  53959. });
  53960. }
  53961. return targets;
  53962. };
  53963. GLTFLoader.prototype._showMeshes = function () {
  53964. this._getMeshes().forEach(function (mesh) { return mesh.isVisible = true; });
  53965. };
  53966. GLTFLoader.prototype._startAnimations = function () {
  53967. var _this = this;
  53968. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  53969. };
  53970. GLTFLoader.prototype._loadScene = function (nodeNames) {
  53971. var _this = this;
  53972. var scene = this._gltf.scenes[this._gltf.scene || 0];
  53973. var nodeIndices = scene.nodes;
  53974. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  53975. node.index = index;
  53976. node.parent = parentNode;
  53977. return true;
  53978. });
  53979. var materials = this._gltf.materials;
  53980. if (materials) {
  53981. materials.forEach(function (material, index) { return material.index = index; });
  53982. }
  53983. if (nodeNames) {
  53984. if (!(nodeNames instanceof Array)) {
  53985. nodeNames = [nodeNames];
  53986. }
  53987. var filteredNodeIndices = new Array();
  53988. this._traverseNodes(nodeIndices, function (node) {
  53989. if (nodeNames.indexOf(node.name) === -1) {
  53990. return true;
  53991. }
  53992. filteredNodeIndices.push(node.index);
  53993. return false;
  53994. });
  53995. nodeIndices = filteredNodeIndices;
  53996. }
  53997. this._traverseNodes(nodeIndices, function (node) { return _this._loadSkin(node); });
  53998. this._traverseNodes(nodeIndices, function (node) { return _this._loadMesh(node); });
  53999. };
  54000. GLTFLoader.prototype._loadSkin = function (node) {
  54001. var _this = this;
  54002. if (node.skin !== undefined) {
  54003. var skin = this._gltf.skins[node.skin];
  54004. var skeletonId = "skeleton" + node.skin;
  54005. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  54006. skin.index = node.skin;
  54007. for (var i = 0; i < skin.joints.length; i++) {
  54008. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  54009. }
  54010. if (skin.skeleton === undefined) {
  54011. // TODO: handle when skeleton is not defined
  54012. throw new Error("Not implemented");
  54013. }
  54014. if (skin.inverseBindMatrices === undefined) {
  54015. // TODO: handle when inverse bind matrices are not defined
  54016. throw new Error("Not implemented");
  54017. }
  54018. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  54019. this._loadAccessorAsync(accessor, function (data) {
  54020. _this._traverseNode(skin.skeleton, function (node, index, parent) { return _this._updateBone(node, parent, skin, data); });
  54021. });
  54022. }
  54023. return true;
  54024. };
  54025. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  54026. var jointIndex = skin.joints.indexOf(node.index);
  54027. if (jointIndex === -1) {
  54028. this._createBone(node, skin);
  54029. }
  54030. var babylonBone = node.babylonSkinToBones[skin.index];
  54031. // TODO: explain the math
  54032. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  54033. matrix.invertToRef(matrix);
  54034. if (parentNode) {
  54035. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  54036. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  54037. }
  54038. babylonBone.updateMatrix(matrix);
  54039. return true;
  54040. };
  54041. GLTFLoader.prototype._createBone = function (node, skin) {
  54042. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  54043. node.babylonSkinToBones = node.babylonSkinToBones || {};
  54044. node.babylonSkinToBones[skin.index] = babylonBone;
  54045. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  54046. node.babylonAnimationTargets.push(babylonBone);
  54047. return babylonBone;
  54048. };
  54049. GLTFLoader.prototype._loadMesh = function (node) {
  54050. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  54051. babylonMesh.isVisible = false;
  54052. this._loadTransform(node, babylonMesh);
  54053. if (node.mesh !== undefined) {
  54054. var mesh = this._gltf.meshes[node.mesh];
  54055. this._loadMeshData(node, mesh, babylonMesh);
  54056. }
  54057. babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  54058. node.babylonMesh = babylonMesh;
  54059. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  54060. node.babylonAnimationTargets.push(node.babylonMesh);
  54061. if (node.skin !== undefined) {
  54062. var skin = this._gltf.skins[node.skin];
  54063. babylonMesh.skeleton = skin.babylonSkeleton;
  54064. }
  54065. if (node.camera !== undefined) {
  54066. // TODO: handle cameras
  54067. }
  54068. return true;
  54069. };
  54070. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  54071. var _this = this;
  54072. babylonMesh.name = mesh.name || babylonMesh.name;
  54073. var babylonMultiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  54074. babylonMesh.material = babylonMultiMaterial;
  54075. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  54076. var vertexData = new BABYLON.VertexData();
  54077. vertexData.positions = [];
  54078. vertexData.indices = [];
  54079. var subMeshInfos = [];
  54080. var loadedPrimitives = 0;
  54081. var totalPrimitives = mesh.primitives.length;
  54082. var _loop_1 = function (i) {
  54083. var primitive = mesh.primitives[i];
  54084. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  54085. // TODO: handle other primitive modes
  54086. throw new Error("Not implemented");
  54087. }
  54088. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  54089. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  54090. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  54091. subMeshInfos.push({
  54092. materialIndex: i,
  54093. verticesStart: vertexData.positions.length,
  54094. verticesCount: subVertexData.positions.length,
  54095. indicesStart: vertexData.indices.length,
  54096. indicesCount: subVertexData.indices.length,
  54097. loadMaterial: function () {
  54098. if (primitive.material === undefined) {
  54099. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  54100. }
  54101. else {
  54102. var material = _this._gltf.materials[primitive.material];
  54103. _this.loadMaterial(material, function (babylonMaterial, isNew) {
  54104. if (isNew && _this._parent.onMaterialLoaded) {
  54105. _this._parent.onMaterialLoaded(babylonMaterial);
  54106. }
  54107. if (_this._parent.onBeforeMaterialReadyAsync) {
  54108. _this.addLoaderPendingData(material);
  54109. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  54110. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  54111. _this.removeLoaderPendingData(material);
  54112. });
  54113. }
  54114. else {
  54115. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  54116. }
  54117. });
  54118. }
  54119. }
  54120. });
  54121. vertexData.merge(subVertexData);
  54122. if (++loadedPrimitives === totalPrimitives) {
  54123. geometry.setAllVerticesData(vertexData, false);
  54124. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  54125. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  54126. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  54127. babylonMesh.subMeshes = [];
  54128. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh); });
  54129. }
  54130. });
  54131. };
  54132. var this_1 = this;
  54133. for (var i = 0; i < totalPrimitives; i++) {
  54134. _loop_1(i);
  54135. }
  54136. };
  54137. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  54138. var _this = this;
  54139. var attributes = primitive.attributes;
  54140. if (!attributes) {
  54141. this._onError("Primitive has no attributes");
  54142. return;
  54143. }
  54144. var vertexData = new BABYLON.VertexData();
  54145. var loadedAttributes = 0;
  54146. var totalAttributes = Object.keys(attributes).length;
  54147. var _loop_2 = function (semantic) {
  54148. accessor = this_2._gltf.accessors[attributes[semantic]];
  54149. this_2._loadAccessorAsync(accessor, function (data) {
  54150. switch (semantic) {
  54151. case "NORMAL":
  54152. vertexData.normals = data;
  54153. break;
  54154. case "POSITION":
  54155. vertexData.positions = data;
  54156. break;
  54157. case "TANGENT":
  54158. vertexData.tangents = data;
  54159. break;
  54160. case "TEXCOORD_0":
  54161. vertexData.uvs = data;
  54162. break;
  54163. case "TEXCOORD_1":
  54164. vertexData.uvs2 = data;
  54165. break;
  54166. case "JOINTS_0":
  54167. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  54168. break;
  54169. case "WEIGHTS_0":
  54170. vertexData.matricesWeights = data;
  54171. break;
  54172. case "COLOR_0":
  54173. vertexData.colors = data;
  54174. break;
  54175. default:
  54176. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  54177. break;
  54178. }
  54179. if (++loadedAttributes === totalAttributes) {
  54180. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  54181. if (indicesAccessor) {
  54182. _this._loadAccessorAsync(indicesAccessor, function (data) {
  54183. vertexData.indices = data;
  54184. onSuccess(vertexData);
  54185. });
  54186. }
  54187. else {
  54188. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  54189. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  54190. onSuccess(vertexData);
  54191. }
  54192. }
  54193. });
  54194. };
  54195. var this_2 = this, accessor;
  54196. for (var semantic in attributes) {
  54197. _loop_2(semantic);
  54198. }
  54199. };
  54200. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  54201. var targets = primitive.targets;
  54202. if (!targets) {
  54203. return;
  54204. }
  54205. if (!babylonMesh.morphTargetManager) {
  54206. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  54207. }
  54208. for (var index = 0; index < targets.length; index++) {
  54209. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  54210. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  54211. }
  54212. };
  54213. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  54214. var targets = primitive.targets;
  54215. if (!targets) {
  54216. return;
  54217. }
  54218. var _loop_3 = function () {
  54219. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  54220. attributes = targets[index];
  54221. var _loop_4 = function (semantic) {
  54222. accessor = this_3._gltf.accessors[attributes[semantic]];
  54223. this_3._loadAccessorAsync(accessor, function (data) {
  54224. if (accessor.name) {
  54225. babylonMorphTarget.name = accessor.name;
  54226. }
  54227. // glTF stores morph target information as deltas while babylon.js expects the final data.
  54228. // As a result we have to add the original data to the delta to calculate the final data.
  54229. var values = data;
  54230. switch (semantic) {
  54231. case "NORMAL":
  54232. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  54233. babylonMorphTarget.setNormals(values);
  54234. break;
  54235. case "POSITION":
  54236. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  54237. babylonMorphTarget.setPositions(values);
  54238. break;
  54239. case "TANGENT":
  54240. // Tangent data for morph targets is stored as xyz delta.
  54241. // The vertexData.tangent is stored as xyzw.
  54242. // So we need to skip every fourth vertexData.tangent.
  54243. for (var i = 0, j = 0; i < values.length; i++, j++) {
  54244. values[i] += vertexData.tangents[j];
  54245. if ((i + 1) % 3 == 0) {
  54246. j++;
  54247. }
  54248. }
  54249. babylonMorphTarget.setTangents(values);
  54250. break;
  54251. default:
  54252. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  54253. break;
  54254. }
  54255. });
  54256. };
  54257. for (var semantic in attributes) {
  54258. _loop_4(semantic);
  54259. }
  54260. };
  54261. var this_3 = this, attributes, accessor;
  54262. for (var index = 0; index < targets.length; index++) {
  54263. _loop_3();
  54264. }
  54265. };
  54266. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  54267. var position = BABYLON.Vector3.Zero();
  54268. var rotation = BABYLON.Quaternion.Identity();
  54269. var scaling = BABYLON.Vector3.One();
  54270. if (node.matrix) {
  54271. var mat = BABYLON.Matrix.FromArray(node.matrix);
  54272. mat.decompose(scaling, rotation, position);
  54273. }
  54274. else {
  54275. if (node.translation)
  54276. position = BABYLON.Vector3.FromArray(node.translation);
  54277. if (node.rotation)
  54278. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  54279. if (node.scale)
  54280. scaling = BABYLON.Vector3.FromArray(node.scale);
  54281. }
  54282. babylonMesh.position = position;
  54283. babylonMesh.rotationQuaternion = rotation;
  54284. babylonMesh.scaling = scaling;
  54285. };
  54286. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  54287. if (parentNode === void 0) { parentNode = null; }
  54288. for (var i = 0; i < indices.length; i++) {
  54289. this._traverseNode(indices[i], action, parentNode);
  54290. }
  54291. };
  54292. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  54293. if (parentNode === void 0) { parentNode = null; }
  54294. var node = this._gltf.nodes[index];
  54295. if (!action(node, index, parentNode)) {
  54296. return;
  54297. }
  54298. if (node.children) {
  54299. for (var i = 0; i < node.children.length; i++) {
  54300. this._traverseNode(node.children[i], action, node);
  54301. }
  54302. }
  54303. };
  54304. GLTFLoader.prototype._loadAnimations = function () {
  54305. var animations = this._gltf.animations;
  54306. if (!animations || animations.length === 0) {
  54307. return;
  54308. }
  54309. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  54310. var animation = animations[animationIndex];
  54311. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  54312. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  54313. }
  54314. }
  54315. };
  54316. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  54317. var channel = animation.channels[channelIndex];
  54318. var samplerIndex = channel.sampler;
  54319. var sampler = animation.samplers[samplerIndex];
  54320. var targetNode = this._gltf.nodes[channel.target.node];
  54321. if (!targetNode) {
  54322. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  54323. return;
  54324. }
  54325. var targetPath = {
  54326. "translation": "position",
  54327. "rotation": "rotationQuaternion",
  54328. "scale": "scaling",
  54329. "weights": "influence"
  54330. }[channel.target.path];
  54331. if (!targetPath) {
  54332. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  54333. return;
  54334. }
  54335. var animationType = {
  54336. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  54337. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  54338. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  54339. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  54340. }[targetPath];
  54341. var inputData;
  54342. var outputData;
  54343. var checkSuccess = function () {
  54344. if (!inputData || !outputData) {
  54345. return;
  54346. }
  54347. var outputBufferOffset = 0;
  54348. var getNextOutputValue = {
  54349. "position": function () {
  54350. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  54351. outputBufferOffset += 3;
  54352. return value;
  54353. },
  54354. "rotationQuaternion": function () {
  54355. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  54356. outputBufferOffset += 4;
  54357. return value;
  54358. },
  54359. "scaling": function () {
  54360. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  54361. outputBufferOffset += 3;
  54362. return value;
  54363. },
  54364. "influence": function () {
  54365. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  54366. var value = new Array(numTargets);
  54367. for (var i = 0; i < numTargets; i++) {
  54368. value[i] = outputData[outputBufferOffset++];
  54369. }
  54370. return value;
  54371. },
  54372. }[targetPath];
  54373. var getNextKey = {
  54374. "LINEAR": function (frameIndex) { return ({
  54375. frame: inputData[frameIndex],
  54376. value: getNextOutputValue()
  54377. }); },
  54378. "CUBICSPLINE": function (frameIndex) { return ({
  54379. frame: inputData[frameIndex],
  54380. inTangent: getNextOutputValue(),
  54381. value: getNextOutputValue(),
  54382. outTangent: getNextOutputValue()
  54383. }); },
  54384. }[sampler.interpolation];
  54385. var keys = new Array(inputData.length);
  54386. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  54387. keys[frameIndex] = getNextKey(frameIndex);
  54388. }
  54389. animation.targets = animation.targets || [];
  54390. if (targetPath === "influence") {
  54391. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  54392. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  54393. var morphTarget = morphTargetManager.getTarget(targetIndex);
  54394. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  54395. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  54396. babylonAnimation.setKeys(keys.map(function (key) { return ({
  54397. frame: key.frame,
  54398. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  54399. value: key.value[targetIndex],
  54400. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  54401. }); }));
  54402. morphTarget.animations.push(babylonAnimation);
  54403. animation.targets.push(morphTarget);
  54404. }
  54405. }
  54406. else {
  54407. var animationName = animation.name || "anim" + animationIndex;
  54408. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  54409. babylonAnimation.setKeys(keys);
  54410. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  54411. var target = targetNode.babylonAnimationTargets[i];
  54412. target.animations.push(babylonAnimation.clone());
  54413. animation.targets.push(target);
  54414. }
  54415. }
  54416. };
  54417. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  54418. inputData = data;
  54419. checkSuccess();
  54420. });
  54421. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  54422. outputData = data;
  54423. checkSuccess();
  54424. });
  54425. };
  54426. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  54427. var _this = this;
  54428. var buffer = this._gltf.buffers[index];
  54429. this.addPendingData(buffer);
  54430. if (buffer.loadedData) {
  54431. setTimeout(function () {
  54432. onSuccess(buffer.loadedData);
  54433. _this.removePendingData(buffer);
  54434. });
  54435. }
  54436. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  54437. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  54438. buffer.loadedData = new Uint8Array(data);
  54439. setTimeout(function () {
  54440. onSuccess(buffer.loadedData);
  54441. _this.removePendingData(buffer);
  54442. });
  54443. }
  54444. else if (buffer.loadedObservable) {
  54445. buffer.loadedObservable.add(function (buffer) {
  54446. onSuccess(buffer.loadedData);
  54447. _this.removePendingData(buffer);
  54448. });
  54449. }
  54450. else {
  54451. buffer.loadedObservable = new BABYLON.Observable();
  54452. buffer.loadedObservable.add(function (buffer) {
  54453. onSuccess(buffer.loadedData);
  54454. _this.removePendingData(buffer);
  54455. });
  54456. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  54457. buffer.loadedData = new Uint8Array(data);
  54458. buffer.loadedObservable.notifyObservers(buffer);
  54459. buffer.loadedObservable = null;
  54460. }, function (event) {
  54461. if (!_this._disposed) {
  54462. _this._onProgress(event);
  54463. }
  54464. }, this._babylonScene.database, true, function (request) {
  54465. if (!_this._disposed) {
  54466. _this._onError("Failed to load file '" + buffer.uri + "': " + request.status + " " + request.statusText);
  54467. _this.removePendingData(buffer);
  54468. }
  54469. });
  54470. }
  54471. };
  54472. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, componentType, onSuccess) {
  54473. var _this = this;
  54474. byteOffset += (bufferView.byteOffset || 0);
  54475. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  54476. if (byteOffset + byteLength > bufferData.byteLength) {
  54477. _this._onError("Buffer access is out of range");
  54478. return;
  54479. }
  54480. var buffer = bufferData.buffer;
  54481. byteOffset += bufferData.byteOffset;
  54482. var bufferViewData;
  54483. switch (componentType) {
  54484. case GLTF2.EComponentType.BYTE:
  54485. bufferViewData = new Int8Array(buffer, byteOffset, byteLength);
  54486. break;
  54487. case GLTF2.EComponentType.UNSIGNED_BYTE:
  54488. bufferViewData = new Uint8Array(buffer, byteOffset, byteLength);
  54489. break;
  54490. case GLTF2.EComponentType.SHORT:
  54491. bufferViewData = new Int16Array(buffer, byteOffset, byteLength);
  54492. break;
  54493. case GLTF2.EComponentType.UNSIGNED_SHORT:
  54494. bufferViewData = new Uint16Array(buffer, byteOffset, byteLength);
  54495. break;
  54496. case GLTF2.EComponentType.UNSIGNED_INT:
  54497. bufferViewData = new Uint32Array(buffer, byteOffset, byteLength);
  54498. break;
  54499. case GLTF2.EComponentType.FLOAT:
  54500. bufferViewData = new Float32Array(buffer, byteOffset, byteLength);
  54501. break;
  54502. default:
  54503. _this._onError("Invalid component type (" + componentType + ")");
  54504. return;
  54505. }
  54506. onSuccess(bufferViewData);
  54507. });
  54508. };
  54509. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  54510. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  54511. var byteOffset = accessor.byteOffset || 0;
  54512. var byteLength = accessor.count * this._getByteStrideFromType(accessor);
  54513. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, accessor.componentType, onSuccess);
  54514. };
  54515. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  54516. switch (accessor.type) {
  54517. case "SCALAR": return 1;
  54518. case "VEC2": return 2;
  54519. case "VEC3": return 3;
  54520. case "VEC4": return 4;
  54521. case "MAT2": return 4;
  54522. case "MAT3": return 9;
  54523. case "MAT4": return 16;
  54524. default:
  54525. this._onError("Invalid accessor type (" + accessor.type + ")");
  54526. return 0;
  54527. }
  54528. };
  54529. Object.defineProperty(GLTFLoader.prototype, "blockPendingTracking", {
  54530. set: function (value) {
  54531. this._blockPendingTracking = value;
  54532. },
  54533. enumerable: true,
  54534. configurable: true
  54535. });
  54536. GLTFLoader.prototype.addPendingData = function (data) {
  54537. if (!this._renderReady) {
  54538. this._renderPendingCount++;
  54539. }
  54540. this.addLoaderPendingData(data);
  54541. };
  54542. GLTFLoader.prototype.removePendingData = function (data) {
  54543. if (!this._renderReady) {
  54544. if (--this._renderPendingCount === 0) {
  54545. this._renderReady = true;
  54546. this._onRenderReady();
  54547. }
  54548. }
  54549. this.removeLoaderPendingData(data);
  54550. };
  54551. GLTFLoader.prototype.addLoaderNonBlockingPendingData = function (data) {
  54552. if (!this._nonBlockingData) {
  54553. this._nonBlockingData = new Array();
  54554. }
  54555. this._nonBlockingData.push(data);
  54556. };
  54557. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  54558. if (this._blockPendingTracking) {
  54559. this.addLoaderNonBlockingPendingData(data);
  54560. return;
  54561. }
  54562. this._loaderPendingCount++;
  54563. };
  54564. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  54565. var indexInPending = this._nonBlockingData ? this._nonBlockingData.indexOf(data) : -1;
  54566. if (indexInPending !== -1) {
  54567. this._nonBlockingData.splice(indexInPending, 1);
  54568. }
  54569. else if (--this._loaderPendingCount === 0) {
  54570. this._onLoaderFirstLODComplete();
  54571. }
  54572. if ((!this._nonBlockingData || this._nonBlockingData.length === 0) && this._loaderPendingCount === 0) {
  54573. this._onLoaderComplete();
  54574. this.dispose();
  54575. }
  54576. };
  54577. GLTFLoader.prototype._getDefaultMaterial = function () {
  54578. if (!this._defaultMaterial) {
  54579. var id = "__gltf_default";
  54580. var material = this._babylonScene.getMaterialByName(id);
  54581. if (!material) {
  54582. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  54583. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  54584. material.metallic = 1;
  54585. material.roughness = 1;
  54586. }
  54587. this._defaultMaterial = material;
  54588. }
  54589. return this._defaultMaterial;
  54590. };
  54591. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  54592. var babylonMaterial = material.babylonMaterial;
  54593. // Ensure metallic workflow
  54594. babylonMaterial.metallic = 1;
  54595. babylonMaterial.roughness = 1;
  54596. var properties = material.pbrMetallicRoughness;
  54597. if (!properties) {
  54598. return;
  54599. }
  54600. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  54601. babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  54602. babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  54603. if (properties.baseColorTexture) {
  54604. babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  54605. }
  54606. if (properties.metallicRoughnessTexture) {
  54607. babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  54608. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  54609. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  54610. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  54611. }
  54612. this.loadMaterialAlphaProperties(material, properties.baseColorFactor);
  54613. };
  54614. GLTFLoader.prototype.loadMaterial = function (material, assign) {
  54615. if (material.babylonMaterial) {
  54616. assign(material.babylonMaterial, false);
  54617. return;
  54618. }
  54619. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  54620. return;
  54621. }
  54622. this.createPbrMaterial(material);
  54623. this.loadMaterialBaseProperties(material);
  54624. this._loadMaterialMetallicRoughnessProperties(material);
  54625. assign(material.babylonMaterial, true);
  54626. };
  54627. GLTFLoader.prototype.createPbrMaterial = function (material) {
  54628. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  54629. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  54630. material.babylonMaterial = babylonMaterial;
  54631. };
  54632. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  54633. var babylonMaterial = material.babylonMaterial;
  54634. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  54635. if (material.doubleSided) {
  54636. babylonMaterial.backFaceCulling = false;
  54637. babylonMaterial.twoSidedLighting = true;
  54638. }
  54639. if (material.normalTexture) {
  54640. babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  54641. babylonMaterial.invertNormalMapX = true;
  54642. babylonMaterial.invertNormalMapY = false;
  54643. if (material.normalTexture.scale !== undefined) {
  54644. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  54645. }
  54646. }
  54647. if (material.occlusionTexture) {
  54648. babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  54649. babylonMaterial.useAmbientInGrayScale = true;
  54650. if (material.occlusionTexture.strength !== undefined) {
  54651. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  54652. }
  54653. }
  54654. if (material.emissiveTexture) {
  54655. babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  54656. }
  54657. };
  54658. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material, colorFactor) {
  54659. var babylonMaterial = material.babylonMaterial;
  54660. var alphaMode = material.alphaMode || "OPAQUE";
  54661. switch (alphaMode) {
  54662. case "OPAQUE":
  54663. // default is opaque
  54664. break;
  54665. case "MASK":
  54666. case "BLEND":
  54667. if (colorFactor) {
  54668. babylonMaterial.alpha = colorFactor[3];
  54669. }
  54670. if (babylonMaterial.albedoTexture) {
  54671. babylonMaterial.albedoTexture.hasAlpha = true;
  54672. babylonMaterial.useAlphaFromAlbedoTexture = (alphaMode === "BLEND");
  54673. }
  54674. break;
  54675. default:
  54676. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  54677. break;
  54678. }
  54679. };
  54680. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  54681. var _this = this;
  54682. var texture = this._gltf.textures[textureInfo.index];
  54683. var texCoord = textureInfo.texCoord || 0;
  54684. if (!texture || texture.source === undefined) {
  54685. return null;
  54686. }
  54687. // check the cache first
  54688. var babylonTexture;
  54689. if (texture.babylonTextures) {
  54690. babylonTexture = texture.babylonTextures[texCoord];
  54691. if (!babylonTexture) {
  54692. for (var i = 0; i < texture.babylonTextures.length; i++) {
  54693. babylonTexture = texture.babylonTextures[i];
  54694. if (babylonTexture) {
  54695. babylonTexture = babylonTexture.clone();
  54696. babylonTexture.coordinatesIndex = texCoord;
  54697. break;
  54698. }
  54699. }
  54700. }
  54701. return babylonTexture;
  54702. }
  54703. var source = this._gltf.images[texture.source];
  54704. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  54705. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  54706. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  54707. this.addPendingData(texture);
  54708. babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  54709. if (!_this._disposed) {
  54710. _this.removePendingData(texture);
  54711. }
  54712. }, function () {
  54713. if (!_this._disposed) {
  54714. _this._onError("Failed to load texture '" + source.uri + "'");
  54715. _this.removePendingData(texture);
  54716. }
  54717. });
  54718. var setTextureData = function (data) {
  54719. var url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  54720. _this._objectURLs.push(url);
  54721. babylonTexture.updateURL(url);
  54722. };
  54723. if (!source.uri) {
  54724. var bufferView = this._gltf.bufferViews[source.bufferView];
  54725. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  54726. }
  54727. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  54728. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  54729. }
  54730. else {
  54731. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  54732. if (!_this._disposed) {
  54733. _this._onProgress(event);
  54734. }
  54735. }, this._babylonScene.database, true, function (request) {
  54736. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  54737. });
  54738. }
  54739. babylonTexture.coordinatesIndex = texCoord;
  54740. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  54741. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  54742. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  54743. // Cache the texture
  54744. texture.babylonTextures = texture.babylonTextures || [];
  54745. texture.babylonTextures[texCoord] = babylonTexture;
  54746. if (this._parent.onTextureLoaded) {
  54747. this._parent.onTextureLoaded(babylonTexture);
  54748. }
  54749. return babylonTexture;
  54750. };
  54751. GLTFLoader.Extensions = {};
  54752. return GLTFLoader;
  54753. }());
  54754. GLTF2.GLTFLoader = GLTFLoader;
  54755. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  54756. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54757. })(BABYLON || (BABYLON = {}));
  54758. //# sourceMappingURL=babylon.glTFLoader.js.map
  54759. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  54760. var BABYLON;
  54761. (function (BABYLON) {
  54762. var GLTF2;
  54763. (function (GLTF2) {
  54764. /**
  54765. * Utils functions for GLTF
  54766. */
  54767. var GLTFUtils = (function () {
  54768. function GLTFUtils() {
  54769. }
  54770. /**
  54771. * If the uri is a base64 string
  54772. * @param uri: the uri to test
  54773. */
  54774. GLTFUtils.IsBase64 = function (uri) {
  54775. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  54776. };
  54777. /**
  54778. * Decode the base64 uri
  54779. * @param uri: the uri to decode
  54780. */
  54781. GLTFUtils.DecodeBase64 = function (uri) {
  54782. var decodedString = atob(uri.split(",")[1]);
  54783. var bufferLength = decodedString.length;
  54784. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  54785. for (var i = 0; i < bufferLength; i++) {
  54786. bufferView[i] = decodedString.charCodeAt(i);
  54787. }
  54788. return bufferView.buffer;
  54789. };
  54790. GLTFUtils.ForEach = function (view, func) {
  54791. for (var index = 0; index < view.length; index++) {
  54792. func(view[index], index);
  54793. }
  54794. };
  54795. GLTFUtils.GetTextureWrapMode = function (mode) {
  54796. // Set defaults if undefined
  54797. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  54798. switch (mode) {
  54799. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  54800. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  54801. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  54802. default:
  54803. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  54804. return BABYLON.Texture.WRAP_ADDRESSMODE;
  54805. }
  54806. };
  54807. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  54808. // Set defaults if undefined
  54809. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  54810. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST : minFilter;
  54811. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  54812. switch (minFilter) {
  54813. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  54814. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  54815. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  54816. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  54817. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  54818. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  54819. default:
  54820. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  54821. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  54822. }
  54823. }
  54824. else {
  54825. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  54826. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  54827. }
  54828. switch (minFilter) {
  54829. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  54830. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  54831. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  54832. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  54833. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  54834. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  54835. default:
  54836. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  54837. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  54838. }
  54839. }
  54840. };
  54841. /**
  54842. * Decodes a buffer view into a string
  54843. * @param view: the buffer view
  54844. */
  54845. GLTFUtils.DecodeBufferToText = function (view) {
  54846. var result = "";
  54847. var length = view.byteLength;
  54848. for (var i = 0; i < length; ++i) {
  54849. result += String.fromCharCode(view[i]);
  54850. }
  54851. return result;
  54852. };
  54853. return GLTFUtils;
  54854. }());
  54855. GLTF2.GLTFUtils = GLTFUtils;
  54856. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54857. })(BABYLON || (BABYLON = {}));
  54858. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  54859. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  54860. var BABYLON;
  54861. (function (BABYLON) {
  54862. var GLTF2;
  54863. (function (GLTF2) {
  54864. var GLTFLoaderExtension = (function () {
  54865. function GLTFLoaderExtension() {
  54866. this.enabled = true;
  54867. }
  54868. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  54869. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  54870. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  54871. };
  54872. GLTFLoaderExtension._ApplyExtensions = function (action) {
  54873. var extensions = GLTFLoaderExtension._Extensions;
  54874. if (!extensions) {
  54875. return;
  54876. }
  54877. for (var i = 0; i < extensions.length; i++) {
  54878. var extension = extensions[i];
  54879. if (extension.enabled && action(extension)) {
  54880. return true;
  54881. }
  54882. }
  54883. return false;
  54884. };
  54885. //
  54886. // Utilities
  54887. //
  54888. GLTFLoaderExtension._Extensions = [];
  54889. return GLTFLoaderExtension;
  54890. }());
  54891. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  54892. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54893. })(BABYLON || (BABYLON = {}));
  54894. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  54895. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  54896. var BABYLON;
  54897. (function (BABYLON) {
  54898. var GLTF2;
  54899. (function (GLTF2) {
  54900. var Extensions;
  54901. (function (Extensions) {
  54902. var MSFTLOD = (function (_super) {
  54903. __extends(MSFTLOD, _super);
  54904. function MSFTLOD() {
  54905. return _super !== null && _super.apply(this, arguments) || this;
  54906. }
  54907. Object.defineProperty(MSFTLOD.prototype, "name", {
  54908. get: function () {
  54909. return "MSFT_lod";
  54910. },
  54911. enumerable: true,
  54912. configurable: true
  54913. });
  54914. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  54915. if (!material.extensions) {
  54916. return false;
  54917. }
  54918. var properties = material.extensions[this.name];
  54919. if (!properties) {
  54920. return false;
  54921. }
  54922. // Clear out the extension so that it won't get loaded again.
  54923. material.extensions[this.name] = undefined;
  54924. // Tell the loader not to clear its state until the highest LOD is loaded.
  54925. var materialLODs = [material.index].concat(properties.ids);
  54926. loader.addLoaderPendingData(material);
  54927. for (var index = 0; index < materialLODs.length; index++) {
  54928. loader.addLoaderNonBlockingPendingData(index);
  54929. }
  54930. // Start with the lowest quality LOD.
  54931. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  54932. return true;
  54933. };
  54934. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  54935. var _this = this;
  54936. var materialLOD = loader.gltf.materials[materialLODs[lod]];
  54937. if (lod !== materialLODs.length - 1) {
  54938. loader.blockPendingTracking = true;
  54939. }
  54940. loader.loadMaterial(materialLOD, function (babylonMaterial, isNew) {
  54941. assign(babylonMaterial, isNew);
  54942. loader.removeLoaderPendingData(lod);
  54943. // Loading is considered complete if this is the lowest quality LOD.
  54944. if (lod === materialLODs.length - 1) {
  54945. loader.removeLoaderPendingData(material);
  54946. }
  54947. if (lod === 0) {
  54948. loader.blockPendingTracking = false;
  54949. return;
  54950. }
  54951. // Load the next LOD when the loader is ready to render and
  54952. // all active material textures of the current LOD are loaded.
  54953. loader.executeWhenRenderReady(function () {
  54954. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  54955. setTimeout(function () {
  54956. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  54957. }, MSFTLOD.MinimalLODDelay);
  54958. });
  54959. });
  54960. });
  54961. };
  54962. /**
  54963. * Specify the minimal delay between LODs in ms (default = 250)
  54964. */
  54965. MSFTLOD.MinimalLODDelay = 250;
  54966. return MSFTLOD;
  54967. }(GLTF2.GLTFLoaderExtension));
  54968. Extensions.MSFTLOD = MSFTLOD;
  54969. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  54970. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  54971. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54972. })(BABYLON || (BABYLON = {}));
  54973. //# sourceMappingURL=MSFT_lod.js.map
  54974. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  54975. var BABYLON;
  54976. (function (BABYLON) {
  54977. var GLTF2;
  54978. (function (GLTF2) {
  54979. var Extensions;
  54980. (function (Extensions) {
  54981. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  54982. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  54983. function KHRMaterialsPbrSpecularGlossiness() {
  54984. return _super !== null && _super.apply(this, arguments) || this;
  54985. }
  54986. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  54987. get: function () {
  54988. return "KHR_materials_pbrSpecularGlossiness";
  54989. },
  54990. enumerable: true,
  54991. configurable: true
  54992. });
  54993. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  54994. if (!material.extensions) {
  54995. return false;
  54996. }
  54997. var properties = material.extensions[this.name];
  54998. if (!properties) {
  54999. return false;
  55000. }
  55001. loader.createPbrMaterial(material);
  55002. loader.loadMaterialBaseProperties(material);
  55003. this._loadSpecularGlossinessProperties(loader, material, properties);
  55004. assign(material.babylonMaterial, true);
  55005. return true;
  55006. };
  55007. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  55008. var babylonMaterial = material.babylonMaterial;
  55009. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  55010. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  55011. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  55012. if (properties.diffuseTexture) {
  55013. babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  55014. loader.loadMaterialAlphaProperties(material);
  55015. }
  55016. if (properties.specularGlossinessTexture) {
  55017. babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  55018. babylonMaterial.reflectivityTexture.hasAlpha = true;
  55019. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  55020. }
  55021. loader.loadMaterialAlphaProperties(material, properties.diffuseFactor);
  55022. };
  55023. return KHRMaterialsPbrSpecularGlossiness;
  55024. }(GLTF2.GLTFLoaderExtension));
  55025. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  55026. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  55027. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  55028. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  55029. })(BABYLON || (BABYLON = {}));
  55030. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  55031. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  55032. module.exports = BABYLON;
  55033. };